am 8fbee008: am b365037f: Add @Deprecated to match @deprecated where it\'s missing in libcore.
* commit '8fbee008f35fa08642a11a728b6d3699ff933efc':
Add @Deprecated to match @deprecated where it's missing in libcore.
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/BlockGuard.java b/dalvik/src/main/java/dalvik/system/BlockGuard.java
index 4cb2c59..eed1de1 100644
--- a/dalvik/src/main/java/dalvik/system/BlockGuard.java
+++ b/dalvik/src/main/java/dalvik/system/BlockGuard.java
@@ -220,7 +220,7 @@
mFileSystem.truncate(fileDescriptor, size);
}
- public int getAllocGranularity() throws IOException {
+ public int getAllocGranularity() {
return mFileSystem.getAllocGranularity();
}
@@ -297,7 +297,12 @@
}
public boolean isConnected(FileDescriptor fd, int timeout) throws IOException {
- BlockGuard.getThreadPolicy().onNetwork();
+ if (timeout != 0) {
+ // Less than 0 is blocking forever.
+ // Greater than 0 is a timeout.
+ // Zero is okay.
+ BlockGuard.getThreadPolicy().onNetwork();
+ }
return mNetwork.isConnected(fd, timeout);
}
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..71486f3
--- /dev/null
+++ b/dalvik/src/main/java/dalvik/system/CloseGuard.java
@@ -0,0 +1,233 @@
+/*
+ * 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 implicit 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 explicitly 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();
+
+ /**
+ * Enabled by default so we can catch issues early in VM startup
+ */
+ private static boolean ENABLED = true;
+
+ /**
+ * Hook for customizing how CloseGuard issues are reported.
+ */
+ private static Reporter REPORTER = new DefaultReporter();
+
+ /**
+ * 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
+ * instance is returned.
+ */
+ public static CloseGuard get() {
+ if (!ENABLED) {
+ return NOOP;
+ }
+ return new CloseGuard();
+ }
+
+ /**
+ * Used to enable or disable CloseGuard. Note that CloseGuard only
+ * warns if it is enabled for both allocation and finalization.
+ */
+ public static void setEnabled(boolean enabled) {
+ ENABLED = enabled;
+ }
+
+ /**
+ * Used to replace default Reporter used to warn of CloseGuard
+ * violations. Must be non-null.
+ */
+ public static void setReporter(Reporter reporter) {
+ if (reporter == null) {
+ throw new NullPointerException("reporter == null");
+ }
+ REPORTER = reporter;
+ }
+
+ /**
+ * Returns non-null CloseGuard.Reporter.
+ */
+ public static Reporter getReporter() {
+ return REPORTER;
+ }
+
+ private CloseGuard() {}
+
+ /**
+ * If CloseGuard is enabled, {@code open} initializes the instance
+ * with a warning that the caller should have explicitly called the
+ * {@code closer} method instead of relying on finalization.
+ *
+ * @param closer non-null name of explicit 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 (this == NOOP || !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 || !ENABLED) {
+ return;
+ }
+
+ String message =
+ ("A resource was acquired at attached stack trace but never released. "
+ + "See java.io.Closeable for information on avoiding resource leaks.");
+
+ REPORTER.report(message, allocationSite);
+ }
+
+ /**
+ * Interface to allow customization of reporting behavior.
+ */
+ public static interface Reporter {
+ public void report (String message, Throwable allocationSite);
+ }
+
+ /**
+ * Default Reporter which uses a Logger to report CloseGuard
+ * violations.
+ */
+ private static final class DefaultReporter implements Reporter {
+ public void report (String message, Throwable allocationSite) {
+ Logger.getLogger(CloseGuard.class.getName())
+ .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/dalvik/src/main/java/dalvik/system/PathClassLoader.java b/dalvik/src/main/java/dalvik/system/PathClassLoader.java
index 626c1a3..96be57c 100644
--- a/dalvik/src/main/java/dalvik/system/PathClassLoader.java
+++ b/dalvik/src/main/java/dalvik/system/PathClassLoader.java
@@ -30,6 +30,7 @@
import java.util.NoSuchElementException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
+import libcore.io.IoUtils;
/**
* Provides a simple {@link ClassLoader} implementation that operates on a list
@@ -330,30 +331,13 @@
* Returns null if the class wasn't found.
*/
private byte[] loadFromDirectory(String path) {
- RandomAccessFile raf;
- byte[] fileData;
-
- //System.out.println("Trying to load from " + path);
try {
- raf = new RandomAccessFile(path, "r");
- }
- catch (FileNotFoundException fnfe) {
- //System.out.println(" Not found: " + path);
- return null;
- }
-
- try {
- fileData = new byte[(int) raf.length()];
- raf.read(fileData);
- raf.close();
- }
- catch (IOException ioe) {
+ return IoUtils.readFileAsByteArray(path);
+ } catch (IOException ex) {
System.err.println("Error reading from " + path);
// swallow it, return null instead
- fileData = null;
+ return null;
}
-
- return fileData;
}
/*
diff --git a/dalvik/src/main/java/dalvik/system/SamplingProfiler.java b/dalvik/src/main/java/dalvik/system/SamplingProfiler.java
index 31ecf65..c21d97d 100644
--- a/dalvik/src/main/java/dalvik/system/SamplingProfiler.java
+++ b/dalvik/src/main/java/dalvik/system/SamplingProfiler.java
@@ -48,17 +48,17 @@
* The following example shows how to use the {@code
* SamplingProfiler}. It samples the current thread's stack to a depth
* of 12 stack frame elements over two different measurement periods
- * at a rate of 10 samples a second. In then prints the results in
- * hprof format to the standard output.
+ * with samples taken every 100 milliseconds. In then prints the
+ * results in hprof format to the standard output.
*
* <pre> {@code
* ThreadSet threadSet = SamplingProfiler.newArrayThreadSet(Thread.currentThread());
* SamplingProfiler profiler = new SamplingProfiler(12, threadSet);
- * profiler.start(10);
+ * profiler.start(100);
* // period of measurement
* profiler.stop();
* // period of non-measurement
- * profiler.start(10);
+ * profiler.start(100);
* // another period of measurement
* profiler.stop();
* profiler.shutdown();
@@ -238,17 +238,17 @@
/**
* Starts profiler sampling at the specified rate.
*
- * @param samplesPerSecond The number of samples to take a second
+ * @param interval The number of milliseconds between samples
*/
- public void start(int samplesPerSecond) {
- if (samplesPerSecond < 1) {
- throw new IllegalArgumentException("samplesPerSecond < 1");
+ public void start(int interval) {
+ if (interval < 1) {
+ throw new IllegalArgumentException("interval < 1");
}
if (sampler != null) {
throw new IllegalStateException("profiling already started");
}
sampler = new Sampler();
- timer.scheduleAtFixedRate(sampler, 0, 1000/samplesPerSecond);
+ timer.scheduleAtFixedRate(sampler, 0, interval);
}
/**
@@ -317,6 +317,9 @@
// TODO replace with a VMStack.getThreadStackTrace
// variant to avoid allocating unneeded elements
StackTraceElement[] stack = thread.getStackTrace();
+ if (stack.length == 0) {
+ continue;
+ }
if (stack.length > depth) {
stack = Arrays.copyOfRange(stack, 0, depth);
}
diff --git a/dalvik/src/main/java/dalvik/system/TouchDexLoader.java b/dalvik/src/main/java/dalvik/system/TouchDexLoader.java
index 032224b..e5f9743 100644
--- a/dalvik/src/main/java/dalvik/system/TouchDexLoader.java
+++ b/dalvik/src/main/java/dalvik/system/TouchDexLoader.java
@@ -26,6 +26,7 @@
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
+import libcore.io.IoUtils;
/**
* Cloned out of PathClassLoader for TouchDex. This could be made
@@ -237,30 +238,13 @@
* Returns null if the class wasn't found.
*/
private byte[] loadFromDirectory(String path) {
- RandomAccessFile raf;
- byte[] fileData;
-
- //System.out.println("Trying to load from " + path);
try {
- raf = new RandomAccessFile(path, "r");
- }
- catch (FileNotFoundException fnfe) {
- //System.out.println(" Not found: " + path);
- return null;
- }
-
- try {
- fileData = new byte[(int) raf.length()];
- raf.read(fileData);
- raf.close();
- }
- catch (IOException ioe) {
+ return IoUtils.readFileAsByteArray(path);
+ } catch (IOException ex) {
System.err.println("Error reading from " + path);
// swallow it, return null instead
- fileData = null;
+ return null;
}
-
- return fileData;
}
/*
@@ -329,4 +313,3 @@
return null;
}
}
-
diff --git a/expectations/brokentests.txt b/expectations/brokentests.txt
index 53075ec..70c82cd 100644
--- a/expectations/brokentests.txt
+++ b/expectations/brokentests.txt
@@ -873,4 +873,4 @@
name: "java.io.FileOutputStream.FileOpenPos",
substring: "java.lang.ArrayIndexOutOfBoundsException"
}
-]
\ No newline at end of file
+]
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/files/cacerts.bks b/luni/src/main/files/cacerts.bks
index 3dbbe49..bb314dd 100644
--- a/luni/src/main/files/cacerts.bks
+++ b/luni/src/main/files/cacerts.bks
Binary files differ
diff --git a/luni/src/main/files/cacerts/256fd83b.0 b/luni/src/main/files/cacerts/256fd83b.0
deleted file mode 100644
index 39ef065..0000000
--- a/luni/src/main/files/cacerts/256fd83b.0
+++ /dev/null
@@ -1,63 +0,0 @@
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 1002 (0x3ea)
- Signature Algorithm: md5WithRSAEncryption
- Issuer: C=DE, ST=Hamburg, L=Hamburg, O=TC TrustCenter for Security in Data Networks GmbH, OU=TC TrustCenter Class 2 CA/emailAddress=certificate@trustcenter.de
- Validity
- Not Before: Mar 9 11:59:59 1998 GMT
- Not After : Jan 1 11:59:59 2011 GMT
- Subject: C=DE, ST=Hamburg, L=Hamburg, O=TC TrustCenter for Security in Data Networks GmbH, OU=TC TrustCenter Class 2 CA/emailAddress=certificate@trustcenter.de
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:da:38:e8:ed:32:00:29:71:83:01:0d:bf:8c:01:
- dc:da:c6:ad:39:a4:a9:8a:2f:d5:8b:5c:68:5f:50:
- c6:62:f5:66:bd:ca:91:22:ec:aa:1d:51:d7:3d:b3:
- 51:b2:83:4e:5d:cb:49:b0:f0:4c:55:e5:6b:2d:c7:
- 85:0b:30:1c:92:4e:82:d4:ca:02:ed:f7:6f:be:dc:
- e0:e3:14:b8:05:53:f2:9a:f4:56:8b:5a:9e:85:93:
- d1:b4:82:56:ae:4d:bb:a8:4b:57:16:bc:fe:f8:58:
- 9e:f8:29:8d:b0:7b:cd:78:c9:4f:ac:8b:67:0c:f1:
- 9c:fb:fc:57:9b:57:5c:4f:0d
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints: critical
- CA:TRUE
- X509v3 Key Usage: critical
- Digital Signature, Certificate Sign, CRL Sign
- Netscape CA Policy Url:
- http://www.trustcenter.de/guidelines
- Netscape Cert Type:
- SSL CA, S/MIME CA, Object Signing CA
- Signature Algorithm: md5WithRSAEncryption
- 84:52:fb:28:df:ff:1f:75:01:bc:01:be:04:56:97:6a:74:42:
- 24:31:83:f9:46:b1:06:8a:89:cf:96:2c:33:bf:8c:b5:5f:7a:
- 72:a1:85:06:ce:86:f8:05:8e:e8:f9:25:ca:da:83:8c:06:ac:
- eb:36:6d:85:91:34:04:36:f4:42:f0:f8:79:2e:0a:48:5c:ab:
- cc:51:4f:78:76:a0:d9:ac:19:bd:2a:d1:69:04:28:91:ca:36:
- 10:27:80:57:5b:d2:5c:f5:c2:5b:ab:64:81:63:74:51:f4:97:
- bf:cd:12:28:f7:4d:66:7f:a7:f0:1c:01:26:78:b2:66:47:70:
- 51:64
-SHA1 Fingerprint=83:8E:30:F7:7F:DD:14:AA:38:5E:D1:45:00:9C:0E:22:36:49:4F:AA
------BEGIN CERTIFICATE-----
-MIIDXDCCAsWgAwIBAgICA+owDQYJKoZIhvcNAQEEBQAwgbwxCzAJBgNVBAYTAkRF
-MRAwDgYDVQQIEwdIYW1idXJnMRAwDgYDVQQHEwdIYW1idXJnMTowOAYDVQQKEzFU
-QyBUcnVzdENlbnRlciBmb3IgU2VjdXJpdHkgaW4gRGF0YSBOZXR3b3JrcyBHbWJI
-MSIwIAYDVQQLExlUQyBUcnVzdENlbnRlciBDbGFzcyAyIENBMSkwJwYJKoZIhvcN
-AQkBFhpjZXJ0aWZpY2F0ZUB0cnVzdGNlbnRlci5kZTAeFw05ODAzMDkxMTU5NTla
-Fw0xMTAxMDExMTU5NTlaMIG8MQswCQYDVQQGEwJERTEQMA4GA1UECBMHSGFtYnVy
-ZzEQMA4GA1UEBxMHSGFtYnVyZzE6MDgGA1UEChMxVEMgVHJ1c3RDZW50ZXIgZm9y
-IFNlY3VyaXR5IGluIERhdGEgTmV0d29ya3MgR21iSDEiMCAGA1UECxMZVEMgVHJ1
-c3RDZW50ZXIgQ2xhc3MgMiBDQTEpMCcGCSqGSIb3DQEJARYaY2VydGlmaWNhdGVA
-dHJ1c3RjZW50ZXIuZGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANo46O0y
-AClxgwENv4wB3NrGrTmkqYov1YtcaF9QxmL1Zr3KkSLsqh1R1z2zUbKDTl3LSbDw
-TFXlay3HhQswHJJOgtTKAu33b77c4OMUuAVT8pr0VotanoWT0bSCVq5Nu6hLVxa8
-/vhYnvgpjbB7zXjJT6yLZwzxnPv8V5tXXE8NAgMBAAGjazBpMA8GA1UdEwEB/wQF
-MAMBAf8wDgYDVR0PAQH/BAQDAgGGMDMGCWCGSAGG+EIBCAQmFiRodHRwOi8vd3d3
-LnRydXN0Y2VudGVyLmRlL2d1aWRlbGluZXMwEQYJYIZIAYb4QgEBBAQDAgAHMA0G
-CSqGSIb3DQEBBAUAA4GBAIRS+yjf/x91AbwBvgRWl2p0QiQxg/lGsQaKic+WLDO/
-jLVfenKhhQbOhvgFjuj5Jcrag4wGrOs2bYWRNAQ29ELw+HkuCkhcq8xRT3h2oNms
-Gb0q0WkEKJHKNhAngFdb0lz1wlurZIFjdFH0l7/NEij3TWZ/p/AcASZ4smZHcFFk
------END CERTIFICATE-----
diff --git a/luni/src/main/files/cacerts/54edfa5d.0 b/luni/src/main/files/cacerts/54edfa5d.0
deleted file mode 100644
index e2530a4..0000000
--- a/luni/src/main/files/cacerts/54edfa5d.0
+++ /dev/null
@@ -1,63 +0,0 @@
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 1003 (0x3eb)
- Signature Algorithm: md5WithRSAEncryption
- Issuer: C=DE, ST=Hamburg, L=Hamburg, O=TC TrustCenter for Security in Data Networks GmbH, OU=TC TrustCenter Class 3 CA/emailAddress=certificate@trustcenter.de
- Validity
- Not Before: Mar 9 11:59:59 1998 GMT
- Not After : Jan 1 11:59:59 2011 GMT
- Subject: C=DE, ST=Hamburg, L=Hamburg, O=TC TrustCenter for Security in Data Networks GmbH, OU=TC TrustCenter Class 3 CA/emailAddress=certificate@trustcenter.de
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:b6:b4:c1:35:05:2e:0d:8d:ec:a0:40:6a:1c:0e:
- 27:a6:50:92:6b:50:1b:07:de:2e:e7:76:cc:e0:da:
- fc:84:a8:5e:8c:63:6a:2b:4d:d9:4e:02:76:11:c1:
- 0b:f2:8d:79:ca:00:b6:f1:b0:0e:d7:fb:a4:17:3d:
- af:ab:69:7a:96:27:bf:af:33:a1:9a:2a:59:aa:c4:
- b5:37:08:f2:12:a5:31:b6:43:f5:32:96:71:28:28:
- ab:8d:28:86:df:bb:ee:e3:0c:7d:30:d6:c3:52:ab:
- 8f:5d:27:9c:6b:c0:a3:e7:05:6b:57:49:44:b3:6e:
- ea:64:cf:d2:8e:7a:50:77:77
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints: critical
- CA:TRUE
- X509v3 Key Usage: critical
- Digital Signature, Certificate Sign, CRL Sign
- Netscape CA Policy Url:
- http://www.trustcenter.de/guidelines
- Netscape Cert Type:
- SSL CA, S/MIME CA, Object Signing CA
- Signature Algorithm: md5WithRSAEncryption
- 16:3d:c6:cd:c1:bb:85:71:85:46:9f:3e:20:8f:51:28:99:ec:
- 2d:45:21:63:23:5b:04:bb:4c:90:b8:88:92:04:4d:bd:7d:01:
- a3:3f:f6:ec:ce:f1:de:fe:7d:e5:e1:3e:bb:c6:ab:5e:0b:dd:
- 3d:96:c4:cb:a9:d4:f9:26:e6:06:4e:9e:0c:a5:7a:ba:6e:c3:
- 7c:82:19:d1:c7:b1:b1:c3:db:0d:8e:9b:40:7c:37:0b:f1:5d:
- e8:fd:1f:90:88:a5:0e:4e:37:64:21:a8:4e:8d:b4:9f:f1:de:
- 48:ad:d5:56:18:52:29:8b:47:34:12:09:d4:bb:92:35:ef:0f:
- db:34
-SHA1 Fingerprint=9F:C7:96:E8:F8:52:4F:86:3A:E1:49:6D:38:12:42:10:5F:1B:78:F5
------BEGIN CERTIFICATE-----
-MIIDXDCCAsWgAwIBAgICA+swDQYJKoZIhvcNAQEEBQAwgbwxCzAJBgNVBAYTAkRF
-MRAwDgYDVQQIEwdIYW1idXJnMRAwDgYDVQQHEwdIYW1idXJnMTowOAYDVQQKEzFU
-QyBUcnVzdENlbnRlciBmb3IgU2VjdXJpdHkgaW4gRGF0YSBOZXR3b3JrcyBHbWJI
-MSIwIAYDVQQLExlUQyBUcnVzdENlbnRlciBDbGFzcyAzIENBMSkwJwYJKoZIhvcN
-AQkBFhpjZXJ0aWZpY2F0ZUB0cnVzdGNlbnRlci5kZTAeFw05ODAzMDkxMTU5NTla
-Fw0xMTAxMDExMTU5NTlaMIG8MQswCQYDVQQGEwJERTEQMA4GA1UECBMHSGFtYnVy
-ZzEQMA4GA1UEBxMHSGFtYnVyZzE6MDgGA1UEChMxVEMgVHJ1c3RDZW50ZXIgZm9y
-IFNlY3VyaXR5IGluIERhdGEgTmV0d29ya3MgR21iSDEiMCAGA1UECxMZVEMgVHJ1
-c3RDZW50ZXIgQ2xhc3MgMyBDQTEpMCcGCSqGSIb3DQEJARYaY2VydGlmaWNhdGVA
-dHJ1c3RjZW50ZXIuZGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALa0wTUF
-Lg2N7KBAahwOJ6ZQkmtQGwfeLud2zODa/ISoXoxjaitN2U4CdhHBC/KNecoAtvGw
-Dtf7pBc9r6tpepYnv68zoZoqWarEtTcI8hKlMbZD9TKWcSgoq40oht+77uMMfTDW
-w1Krj10nnGvAo+cFa1dJRLNu6mTP0o56UHd3AgMBAAGjazBpMA8GA1UdEwEB/wQF
-MAMBAf8wDgYDVR0PAQH/BAQDAgGGMDMGCWCGSAGG+EIBCAQmFiRodHRwOi8vd3d3
-LnRydXN0Y2VudGVyLmRlL2d1aWRlbGluZXMwEQYJYIZIAYb4QgEBBAQDAgAHMA0G
-CSqGSIb3DQEBBAUAA4GBABY9xs3Bu4VxhUafPiCPUSiZ7C1FIWMjWwS7TJC4iJIE
-Tb19AaM/9uzO8d7+feXhPrvGq14L3T2WxMup1Pkm5gZOngylerpuw3yCGdHHsbHD
-2w2Om0B8NwvxXej9H5CIpQ5ON2QhqE6NtJ/x3kit1VYYUimLRzQSCdS7kjXvD9s0
------END CERTIFICATE-----
diff --git a/luni/src/main/files/cacerts/7651b327.0 b/luni/src/main/files/cacerts/7651b327.0
index c0cee71..e2efa82 100644
--- a/luni/src/main/files/cacerts/7651b327.0
+++ b/luni/src/main/files/cacerts/7651b327.0
@@ -2,12 +2,12 @@
Data:
Version: 1 (0x0)
Serial Number:
- 70:ba:e4:1d:10:d9:29:34:b6:38:ca:7b:03:cc:ba:bf
- Signature Algorithm: md2WithRSAEncryption
+ 3c:91:31:cb:1f:f6:d0:1b:0e:9a:b8:d0:44:bf:12:be
+ Signature Algorithm: sha1WithRSAEncryption
Issuer: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority
Validity
Not Before: Jan 29 00:00:00 1996 GMT
- Not After : Aug 1 23:59:59 2028 GMT
+ Not After : Aug 2 23:59:59 2028 GMT
Subject: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
@@ -23,27 +23,27 @@
e7:3d:be:7d:9a:fe:24:45:33:dc:76:15:ed:0f:a2:
71:64:4c:65:2e:81:68:45:a7
Exponent: 65537 (0x10001)
- Signature Algorithm: md2WithRSAEncryption
- bb:4c:12:2b:cf:2c:26:00:4f:14:13:dd:a6:fb:fc:0a:11:84:
- 8c:f3:28:1c:67:92:2f:7c:b6:c5:fa:df:f0:e8:95:bc:1d:8f:
- 6c:2c:a8:51:cc:73:d8:a4:c0:53:f0:4e:d6:26:c0:76:01:57:
- 81:92:5e:21:f1:d1:b1:ff:e7:d0:21:58:cd:69:17:e3:44:1c:
- 9c:19:44:39:89:5c:dc:9c:00:0f:56:8d:02:99:ed:a2:90:45:
- 4c:e4:bb:10:a4:3d:f0:32:03:0e:f1:ce:f8:e8:c9:51:8c:e6:
- 62:9f:e6:9f:c0:7d:b7:72:9c:c9:36:3a:6b:9f:4e:a8:ff:64:
- 0d:64
-SHA1 Fingerprint=74:2C:31:92:E6:07:E4:24:EB:45:49:54:2B:E1:BB:C5:3E:61:74:E2
+ Signature Algorithm: sha1WithRSAEncryption
+ 10:72:52:a9:05:14:19:32:08:41:f0:c5:6b:0a:cc:7e:0f:21:
+ 19:cd:e4:67:dc:5f:a9:1b:e6:ca:e8:73:9d:22:d8:98:6e:73:
+ 03:61:91:c5:7c:b0:45:40:6e:44:9d:8d:b0:b1:96:74:61:2d:
+ 0d:a9:45:d2:a4:92:2a:d6:9a:75:97:6e:3f:53:fd:45:99:60:
+ 1d:a8:2b:4c:f9:5e:a7:09:d8:75:30:d7:d2:65:60:3d:67:d6:
+ 48:55:75:69:3f:91:f5:48:0b:47:69:22:69:82:96:be:c9:c8:
+ 38:86:4a:7a:2c:73:19:48:69:4e:6b:7c:65:bf:0f:fc:70:ce:
+ 88:90
+SHA1 Fingerprint=A1:DB:63:93:91:6F:17:E4:18:55:09:40:04:15:C7:02:40:B0:AE:6B
-----BEGIN CERTIFICATE-----
-MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkG
+MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkG
A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFz
cyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2
-MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVowXzELMAkGA1UEBhMCVVMxFzAVBgNV
+MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVowXzELMAkGA1UEBhMCVVMxFzAVBgNV
BAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmlt
YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUAA4GN
ADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhE
BarsAx94f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/is
I19wKTakyYbnsZogy1Olhec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0G
-CSqGSIb3DQEBAgUAA4GBALtMEivPLCYATxQT3ab7/AoRhIzzKBxnki98tsX63/Do
-lbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59AhWM1pF+NEHJwZRDmJXNyc
-AA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2OmufTqj/ZA1k
+CSqGSIb3DQEBBQUAA4GBABByUqkFFBkyCEHwxWsKzH4PIRnN5GfcX6kb5sroc50i
+2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWXbj9T/UWZYB2oK0z5XqcJ
+2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/D/xwzoiQ
-----END CERTIFICATE-----
diff --git a/luni/src/main/files/cacerts/89c02a45.0 b/luni/src/main/files/cacerts/89c02a45.0
new file mode 100644
index 0000000..7361019
--- /dev/null
+++ b/luni/src/main/files/cacerts/89c02a45.0
@@ -0,0 +1,54 @@
+Certificate:
+ Data:
+ Version: 3 (0x2)
+ Serial Number:
+ 1f:47:af:aa:62:00:70:50:54:4c:01:9e:9b:63:99:2a
+ Signature Algorithm: 1.2.840.10045.4.3.3
+ Issuer: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO ECC Certification Authority
+ Validity
+ Not Before: Mar 6 00:00:00 2008 GMT
+ Not After : Jan 18 23:59:59 2038 GMT
+ Subject: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO ECC Certification Authority
+ Subject Public Key Info:
+ Public Key Algorithm: id-ecPublicKey
+ EC Public Key:
+ pub:
+ 04:03:47:7b:2f:75:c9:82:15:85:fb:75:e4:91:16:
+ d4:ab:62:99:f5:3e:52:0b:06:ce:41:00:7f:97:e1:
+ 0a:24:3c:1d:01:04:ee:3d:d2:8d:09:97:0c:e0:75:
+ e4:fa:fb:77:8a:2a:f5:03:60:4b:36:8b:16:23:16:
+ ad:09:71:f4:4a:f4:28:50:b4:fe:88:1c:6e:3f:6c:
+ 2f:2f:09:59:5b:a5:5b:0b:33:99:e2:c3:3d:89:f9:
+ 6a:2c:ef:b2:d3:06:e9
+ ASN1 OID: secp384r1
+ X509v3 extensions:
+ X509v3 Subject Key Identifier:
+ 75:71:A7:19:48:19:BC:9D:9D:EA:41:47:DF:94:C4:48:77:99:D3:79
+ X509v3 Key Usage: critical
+ Certificate Sign, CRL Sign
+ X509v3 Basic Constraints: critical
+ CA:TRUE
+ Signature Algorithm: 1.2.840.10045.4.3.3
+ 30:65:02:31:00:ef:03:5b:7a:ac:b7:78:0a:72:b7:88:df:ff:
+ b5:46:14:09:0a:fa:a0:e6:7d:08:c6:1a:87:bd:18:a8:73:bd:
+ 26:ca:60:0c:9d:ce:99:9f:cf:5c:0f:30:e1:be:14:31:ea:02:
+ 30:14:f4:93:3c:49:a7:33:7a:90:46:47:b3:63:7d:13:9b:4e:
+ b7:6f:18:37:80:53:fe:dd:20:e0:35:9a:36:d1:c7:01:b9:e6:
+ dc:dd:f3:ff:1d:2c:3a:16:57:d9:92:39:d6
+SHA1 Fingerprint=9F:74:4E:9F:2B:4D:BA:EC:0F:31:2C:50:B6:56:3B:8E:2D:93:C3:11
+-----BEGIN CERTIFICATE-----
+MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL
+MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE
+BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT
+IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw
+MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy
+ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N
+T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv
+biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR
+FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J
+cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW
+BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/
+BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm
+fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv
+GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=
+-----END CERTIFICATE-----
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" <<< "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" <<< "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/BufferedOutputStream.java b/luni/src/main/java/java/io/BufferedOutputStream.java
index 9937629..88e9848 100644
--- a/luni/src/main/java/java/io/BufferedOutputStream.java
+++ b/luni/src/main/java/java/io/BufferedOutputStream.java
@@ -139,11 +139,10 @@
}
// flush the internal buffer first if we have not enough space left
- if (length >= (internalBuffer.length - count)) {
+ if (length > (internalBuffer.length - count)) {
flushInternal();
}
- // the length is always less than (internalBuffer.length - count) here so arraycopy is safe
System.arraycopy(buffer, offset, internalBuffer, count, length);
count += length;
}
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..e02d27c 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
@@ -107,44 +107,40 @@
public abstract float readFloat() throws IOException;
/**
- * Reads bytes into the byte array {@code buffer}. This method will block
- * until {@code buffer.length} number of bytes have been read.
- *
- * @param buffer
- * the buffer to read bytes into.
- * @throws EOFException if the end of the input is reached before the read
- * request can be satisfied.
- * @throws IOException
- * if an I/O error occurs while reading.
- * @see DataOutput#write(byte[])
- * @see DataOutput#write(byte[], int, int)
+ * Equivalent to {@code readFully(dst, 0, dst.length);}.
*/
- public abstract void readFully(byte[] buffer) throws IOException;
+ public abstract void readFully(byte[] dst) throws IOException;
/**
- * Reads bytes and stores them in the byte array {@code buffer} starting at
- * offset {@code offset}. This method blocks until {@code count} number of
- * bytes have been read.
+ * Reads {@code byteCount} bytes from this stream and stores them in the byte
+ * array {@code dst} starting at {@code offset}. If {@code byteCount} is zero, then this
+ * method returns without reading any bytes. Otherwise, this method blocks until
+ * {@code byteCount} bytes have been read. If insufficient bytes are available,
+ * {@code EOFException} is thrown. If an I/O error occurs, {@code IOException} is
+ * thrown. When an exception is thrown, some bytes may have been consumed from the stream
+ * and written into the array.
*
- * @param buffer
- * the byte array in which to store the bytes read.
+ * @param dst
+ * the byte array into which the data is read.
* @param offset
- * the initial position in {@code buffer} to store the bytes
- * read.
- * @param count
- * the maximum number of bytes to store in {@code buffer}.
- * @throws EOFException if the end of the input is reached before the read
- * request can be satisfied.
+ * the offset in {@code dst} at which to store the bytes.
+ * @param byteCount
+ * the number of bytes to read.
+ * @throws EOFException
+ * if the end of the source stream is reached before enough
+ * bytes have been read.
+ * @throws IndexOutOfBoundsException
+ * if {@code offset < 0} or {@code byteCount < 0}, or
+ * {@code offset + byteCount > dst.length}.
* @throws IOException
- * if an I/O error occurs while reading.
- * @see DataOutput#write(byte[])
- * @see DataOutput#write(byte[], int, int)
+ * if a problem occurs while reading from this stream.
+ * @throws NullPointerException
+ * if {@code dst} is null.
*/
- public abstract void readFully(byte[] buffer, int offset, int count)
- throws IOException;
+ public abstract void readFully(byte[] dst, int offset, int byteCount) 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 +167,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 +179,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 +203,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 8ebcafd..935867a 100644
--- a/luni/src/main/java/java/io/DataInputStream.java
+++ b/luni/src/main/java/java/io/DataInputStream.java
@@ -17,10 +17,14 @@
package java.io;
+import java.nio.ByteOrder;
import java.nio.charset.ModifiedUtf8;
+import libcore.base.Streams;
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
/**
- * 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
@@ -30,7 +34,7 @@
*/
public class DataInputStream extends FilterInputStream implements DataInput {
- byte[] buff;
+ private final byte[] scratch = new byte[8];
/**
* Constructs a new DataInputStream on the InputStream {@code in}. All
@@ -48,7 +52,6 @@
*/
public DataInputStream(InputStream in) {
super(in);
- buff = new byte[8];
}
/**
@@ -90,22 +93,10 @@
* @see DataOutput#write(byte[], int, int)
*/
@Override
- public final int read(byte[] buffer, int offset, int length)
- throws IOException {
+ public final int read(byte[] buffer, int offset, int length) throws IOException {
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) {
@@ -114,17 +105,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) {
@@ -133,175 +113,31 @@
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();
- }
- return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
-
+ return (char) readShort();
}
- private int readToBuff(int count) throws IOException {
- int offset = 0;
-
- while(offset < count) {
- int bytesRead = in.read(buff, offset, count - offset);
- 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);
+ public final void readFully(byte[] dst) throws IOException {
+ readFully(dst, 0, dst.length);
}
- /**
- * Reads bytes from this stream and stores them in the byte array {@code
- * buffer} starting at the position {@code offset}. This method blocks until
- * {@code length} bytes have been read. If {@code length} is zero, then this
- * method returns without reading any bytes.
- *
- * @param buffer
- * the byte array into which the data is read.
- * @param offset
- * the offset in {@code buffer} from where to store the bytes
- * read.
- * @param length
- * the maximum number of bytes to read.
- * @throws EOFException
- * if the end of the source stream is reached before enough
- * bytes have been read.
- * @throws IndexOutOfBoundsException
- * if {@code offset < 0} or {@code length < 0}, or if {@code
- * offset + length} is greater than the size of {@code buffer}.
- * @throws IOException
- * if a problem occurs while reading from this stream.
- * @throws NullPointerException
- * if {@code buffer} or the source stream are null.
- * @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;
- }
- if (in == null) {
- throw new NullPointerException("in == null");
- }
- if (buffer == null) {
- throw new NullPointerException("buffer == null");
- }
- // BEGIN android-changed
- // Exception priorities (in case of multiple errors) differ from
- // RI, but are spec-compliant.
- // used (offset | length) < 0 instead of separate (offset < 0) and
- // (length < 0) check to safe one operation
- if ((offset | length) < 0 || offset > buffer.length - length) {
- throw new IndexOutOfBoundsException();
- }
- // END android-changed
- while (length > 0) {
- int result = in.read(buffer, offset, length);
- if (result < 0) {
- throw new EOFException();
- }
- offset += result;
- length -= result;
- }
+ public final void readFully(byte[] dst, int offset, int byteCount) throws IOException {
+ Streams.readFully(in, dst, offset, byteCount);
}
- /**
- * 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();
- }
- return ((buff[0] & 0xff) << 24) | ((buff[1] & 0xff) << 16) |
- ((buff[2] & 0xff) << 8) | (buff[3] & 0xff);
+ Streams.readFully(in, scratch, 0, SizeOf.INT);
+ return OSMemory.peekInt(scratch, 0, ByteOrder.BIG_ENDIAN);
}
- /**
- * 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
@@ -337,59 +173,16 @@
}
}
- /**
- * 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();
- }
- int i1 = ((buff[0] & 0xff) << 24) | ((buff[1] & 0xff) << 16) |
- ((buff[2] & 0xff) << 8) | (buff[3] & 0xff);
- int i2 = ((buff[4] & 0xff) << 24) | ((buff[5] & 0xff) << 16) |
- ((buff[6] & 0xff) << 8) | (buff[7] & 0xff);
-
- return ((i1 & 0xffffffffL) << 32) | (i2 & 0xffffffffL);
+ Streams.readFully(in, scratch, 0, SizeOf.LONG);
+ return OSMemory.peekLong(scratch, 0, ByteOrder.BIG_ENDIAN);
}
- /**
- * 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();
- }
- return (short) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
+ Streams.readFully(in, scratch, 0, SizeOf.SHORT);
+ return OSMemory.peekShort(scratch, 0, ByteOrder.BIG_ENDIAN);
}
- /**
- * 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) {
@@ -398,42 +191,14 @@
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();
- }
- return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
+ return ((int) readShort()) & 0xffff;
}
- /**
- * 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);
}
@@ -444,18 +209,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);
}
@@ -481,11 +234,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..62a5cd2 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
@@ -37,8 +37,6 @@
* the buffer to write.
* @throws IOException
* if an I/O error occurs while writing.
- * @see DataInput#readFully(byte[])
- * @see DataInput#readFully(byte[], int, int)
*/
public abstract void write(byte[] buffer) throws IOException;
@@ -54,13 +52,8 @@
* the number of bytes from the {@code buffer} to write.
* @throws IOException
* if an I/O error occurs while writing.
- * @see DataInput#readFully(byte[])
- * @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.
@@ -103,15 +96,12 @@
* the string containing the bytes to write.
* @throws IOException
* if an I/O error occurs while writing.
- * @see DataInput#readFully(byte[])
- * @see DataInput#readFully(byte[],int,int)
*/
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 +112,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 +123,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 +135,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 +147,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 +158,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 +169,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 c96b7bf..cc34278 100644
--- a/luni/src/main/java/java/io/DataOutputStream.java
+++ b/luni/src/main/java/java/io/DataOutputStream.java
@@ -17,8 +17,13 @@
package java.io;
+import java.nio.ByteOrder;
+import java.nio.charset.ModifiedUtf8;
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
+
/**
- * 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.
@@ -26,12 +31,12 @@
* @see DataInputStream
*/
public class DataOutputStream extends FilterOutputStream implements DataOutput {
+ private final byte[] scratch = new byte[8];
/**
* The number of bytes written out so far.
*/
protected int written;
- byte[] buff;
/**
* Constructs a new {@code DataOutputStream} on the {@code OutputStream}
@@ -44,7 +49,6 @@
*/
public DataOutputStream(OutputStream out) {
super(out);
- buff = new byte[8];
}
/**
@@ -85,14 +89,9 @@
* if an error occurs while writing to the target stream.
* @throws NullPointerException
* if {@code buffer} is {@code null}.
- * @see DataInputStream#readFully(byte[])
- * @see DataInputStream#readFully(byte[], int, int)
*/
@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");
}
@@ -146,16 +145,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;
@@ -168,217 +157,43 @@
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;
- out.write(buff, 0, 2);
- written += 2;
+ writeShort(val);
}
- /**
- * 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);
- buff[2] = (byte) (val >> 8);
- buff[3] = (byte) val;
- out.write(buff, 0, 4);
- written += 4;
+ OSMemory.pokeInt(scratch, 0, val, ByteOrder.BIG_ENDIAN);
+ out.write(scratch, 0, SizeOf.INT);
+ written += SizeOf.INT;
}
- /**
- * 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);
- buff[2] = (byte) (val >> 40);
- buff[3] = (byte) (val >> 32);
- buff[4] = (byte) (val >> 24);
- buff[5] = (byte) (val >> 16);
- buff[6] = (byte) (val >> 8);
- buff[7] = (byte) val;
- out.write(buff, 0, 8);
- written += 8;
+ OSMemory.pokeLong(scratch, 0, val, ByteOrder.BIG_ENDIAN);
+ out.write(scratch, 0, SizeOf.LONG);
+ written += SizeOf.LONG;
}
- 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;
- out.write(buff, 0, 2);
- written += 2;
+ OSMemory.pokeShort(scratch, 0, (short) val, ByteOrder.BIG_ENDIAN);
+ out.write(scratch, 0, SizeOf.SHORT);
+ written += SizeOf.SHORT;
}
- 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);
- // BEGIN android-changed
- // removed unused parameter count
- offset = writeUTFBytesToBuffer(str, buffer, offset);
- // BEGIN android-changed
- 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 {
- // BEGIN android-note
- // removed unused parameter count
- // END android-note
- 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 bb8829d..5fce3e4 100644
--- a/luni/src/main/java/java/io/FileInputStream.java
+++ b/luni/src/main/java/java/io/FileInputStream.java
@@ -17,44 +17,52 @@
package java.io;
+import dalvik.system.CloseGuard;
+import java.nio.NioUtils;
import java.nio.channels.FileChannel;
import libcore.io.IoUtils;
import org.apache.harmony.luni.platform.IFileSystem;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.nio.FileChannelFactory;
/**
- * A specialized {@link InputStream} that reads from a file in the file system.
- * All read requests made by calling methods in this class are directly
- * forwarded to the equivalent function of the underlying operating system.
- * Since this may induce some performance penalty, in particular if many small
- * read requests are made, a FileInputStream is often wrapped by a
- * BufferedInputStream.
+ * An input stream that reads bytes from a file.
+ * <pre> {@code
+ * File file = ...
+ * InputStream in = null;
+ * try {
+ * in = new BufferedInputStream(new FileInputStream(file));
+ * ...
+ * } finally {
+ * if (in != null) {
+ * in.close();
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>This stream is <strong>not buffered</strong>. Most callers should wrap
+ * this stream with a {@link BufferedInputStream}.
+ *
+ * <p>Use {@link FileReader} to read characters, as opposed to bytes, from a
+ * file.
*
* @see BufferedInputStream
* @see FileOutputStream
*/
public class FileInputStream extends InputStream implements Closeable {
- /**
- * The {@link FileDescriptor} representing this {@code FileInputStream}.
- */
- FileDescriptor fd;
- // The unique file channel associated with this FileInputStream (lazily
- // initialized).
+ private final FileDescriptor fd;
+
+ /** The unique file channel. Lazily initialized because it's rarely needed. */
private FileChannel channel;
- boolean innerFD;
+ private final boolean shouldCloseFd;
- private IFileSystem fileSystem = Platform.getFileSystem();
+ private final Object repositioningLock = new Object();
- private static class RepositioningLock {
- }
-
- private Object repositioningLock = new RepositioningLock();
+ private final CloseGuard guard = CloseGuard.get();
/**
- * Constructs a new {@code FileInputStream} based on {@code file}.
+ * Constructs a new {@code FileInputStream} that reads from {@code file}.
*
* @param file
* the file from which this stream reads.
@@ -65,30 +73,22 @@
* read request.
*/
public FileInputStream(File file) throws FileNotFoundException {
- super();
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- // For compatibility, nulls are passed to the manager.
- String filePath = (null == file ? null : file.getPath());
- security.checkRead(filePath);
- }
if (file == null) {
throw new NullPointerException("file == null");
}
+ SecurityManager securityManager = System.getSecurityManager();
+ if (securityManager != null) {
+ securityManager.checkRead(file.getPath());
+ }
fd = new FileDescriptor();
fd.readOnly = true;
- fd.descriptor = fileSystem.open(file.getAbsolutePath(), IFileSystem.O_RDONLY);
- innerFD = true;
- // BEGIN android-removed
- // channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- // IFileSystem.O_RDONLY);
- // END android-removed
+ fd.descriptor = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), IFileSystem.O_RDONLY);
+ shouldCloseFd = true;
+ guard.open("close");
}
/**
- * Constructs a new {@code FileInputStream} on the {@link FileDescriptor}
- * {@code fd}. The file must already be open, therefore no
- * {@code FileNotFoundException} will be thrown.
+ * Constructs a new {@code FileInputStream} that reads from {@code fd}.
*
* @param fd
* the FileDescriptor from which this stream reads.
@@ -99,64 +99,43 @@
* read request.
*/
public FileInputStream(FileDescriptor fd) {
- super();
if (fd == null) {
throw new NullPointerException("fd == null");
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(fd);
+ SecurityManager securityManager = System.getSecurityManager();
+ if (securityManager != null) {
+ securityManager.checkRead(fd);
}
this.fd = fd;
- innerFD = false;
- // BEGIN android-removed
- // channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- // IFileSystem.O_RDONLY);
- // END android-removed
+ this.shouldCloseFd = false;
+ // Note that we do not call guard.open here because the
+ // FileDescriptor is not owned by the stream.
}
/**
- * Constructs a new {@code FileInputStream} on the file named
- * {@code fileName}. The path of {@code fileName} may be absolute or
- * relative to the system property {@code "user.dir"}.
- *
- * @param fileName
- * the path and name of the file from which this stream reads.
- * @throws FileNotFoundException
- * if there is no file named {@code fileName}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * read request.
+ * Equivalent to {@code new FileInputStream(new File(path))}.
*/
- public FileInputStream(String fileName) throws FileNotFoundException {
- this(null == fileName ? (File) null : new File(fileName));
+ public FileInputStream(String path) throws FileNotFoundException {
+ this(new File(path));
}
@Override
public int available() throws IOException {
- openCheck();
- return fileSystem.ioctlAvailable(fd);
+ checkOpen();
+ return Platform.FILE_SYSTEM.ioctlAvailable(fd);
}
- /**
- * Closes this stream.
- *
- * @throws IOException
- * if an error occurs attempting to close this stream.
- */
@Override
public void close() throws IOException {
- // BEGIN android-changed
+ guard.close();
synchronized (this) {
- if (channel != null && channel.isOpen()) {
+ if (channel != null) {
channel.close();
- channel = null;
}
- if (fd != null && fd.valid() && innerFD) {
+ if (shouldCloseFd && fd.valid()) {
IoUtils.close(fd);
}
}
- // END android-changed
}
/**
@@ -168,168 +147,96 @@
*/
@Override protected void finalize() throws IOException {
try {
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
close();
} finally {
try {
super.finalize();
} catch (Throwable t) {
+ // for consistency with the RI, we must override Object.finalize() to
+ // remove the 'throws Throwable' clause.
throw new AssertionError(t);
}
}
}
/**
- * Returns the {@link FileChannel} equivalent to this input stream.
- * <p>
- * The file channel is read-only and has an initial position within the file
- * that is the same as the current position of this stream within the file.
- * All changes made to the underlying file descriptor state via the channel
- * are visible by the input stream and vice versa.
- *
- * @return the file channel for this stream.
+ * Returns a read-only {@link FileChannel} that shares its position with
+ * this stream.
*/
public FileChannel getChannel() {
- // BEGIN android-changed
- synchronized(this) {
+ synchronized (this) {
if (channel == null) {
- channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- IFileSystem.O_RDONLY);
+ channel = NioUtils.newFileChannel(this, fd.descriptor, IFileSystem.O_RDONLY);
}
return channel;
}
- // END android-changed
}
/**
- * Returns the {@link FileDescriptor} representing the operating system
- * resource for this stream.
- *
- * @return the {@code FileDescriptor} for this stream.
- * @throws IOException
- * if an error occurs while getting this stream's
- * {@code FileDescriptor}.
+ * Returns the underlying file descriptor.
*/
public final FileDescriptor getFD() throws IOException {
return fd;
}
- /**
- * Reads a single byte from this stream and returns it as an integer in the
- * range from 0 to 255. Returns -1 if the end of this stream has been
- * reached.
- *
- * @return the byte read or -1 if the end of this stream has been reached.
- * @throws IOException
- * if this stream is closed or another I/O error occurs.
- */
@Override
public int read() throws IOException {
- byte[] readed = new byte[1];
- int result = read(readed, 0, 1);
- return result == -1 ? -1 : readed[0] & 0xff;
+ byte[] buffer = new byte[1];
+ int result = read(buffer, 0, 1);
+ return result == -1 ? -1 : buffer[0] & 0xff;
}
- /**
- * Reads bytes from this stream and stores them in the byte array
- * {@code buffer}.
- *
- * @param buffer
- * the byte array in which to store the bytes read.
- * @return the number of bytes actually read or -1 if the end of the stream
- * has been reached.
- * @throws IOException
- * if this stream is closed or another I/O error occurs.
- */
@Override
public int read(byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
- /**
- * Reads at most {@code count} bytes from this stream and stores them in the
- * byte array {@code buffer} starting at {@code offset}.
- *
- * @param buffer
- * the byte array in which to store the bytes read.
- * @param offset
- * the initial position in {@code buffer} to store the bytes read
- * from this stream.
- * @param count
- * the maximum number of bytes to store in {@code buffer}.
- * @return the number of bytes actually read or -1 if the end of the stream
- * has been reached.
- * @throws IndexOutOfBoundsException
- * if {@code offset < 0} or {@code count < 0}, or if
- * {@code offset + count} is greater than the size of
- * {@code buffer}.
- * @throws IOException
- * if the stream is closed or another IOException occurs.
- */
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
- // BEGIN android-changed
- // Exception priorities (in case of multiple errors) differ from
- // RI, but are spec-compliant.
- // made implicit null check explicit,
- // used (offset | count) < 0 instead of (offset < 0) || (count < 0)
- // to safe one operation
if (buffer == null) {
throw new NullPointerException("buffer == null");
}
if ((count | offset) < 0 || count > buffer.length - offset) {
throw new IndexOutOfBoundsException();
}
- // END android-changed
- if (0 == count) {
- return 0;
- }
- openCheck();
- synchronized (repositioningLock) {
- // BEGIN android-changed
- // If you only support Linux, there's nothing special about stdin.
- return (int) fileSystem.read(fd.descriptor, buffer, offset, count);
- // END android-changed
- }
- }
-
- /**
- * Skips {@code count} number of bytes in this stream. Subsequent
- * {@code read()}s will not return these bytes unless {@code reset()} is
- * used. If the underlying stream is unseekable, an IOException is thrown.
- *
- * @param count
- * the number of bytes to skip.
- * @return the number of bytes actually skipped.
- * @throws IOException
- * if {@code count < 0}, this stream is closed or unseekable,
- * or another IOException occurs.
- */
- @Override
- public long skip(long count) throws IOException {
- openCheck();
-
if (count == 0) {
return 0;
}
- if (count < 0) {
- throw new IOException("count < 0");
+ checkOpen();
+ synchronized (repositioningLock) {
+ return (int) Platform.FILE_SYSTEM.read(fd.descriptor, buffer, offset, count);
+ }
+ }
+
+ @Override
+ public long skip(long byteCount) throws IOException {
+ checkOpen();
+
+ if (byteCount == 0) {
+ return 0;
+ }
+ if (byteCount < 0) {
+ throw new IOException("byteCount < 0");
}
// The RI doesn't treat stdin as special. It throws IOException for
// all non-seekable streams, so we do too. If you did want to support
// non-seekable streams, the best way to do it would be to recognize
- // when lseek(2) fails with ESPIPE and call super.skip(count).
+ // when lseek(2) fails with ESPIPE and call super.skip(byteCount).
synchronized (repositioningLock) {
// Our seek returns the new offset, but we know it will throw an
// exception if it couldn't perform exactly the seek we asked for.
- fileSystem.seek(fd.descriptor, count, IFileSystem.SEEK_CUR);
- return count;
+ Platform.FILE_SYSTEM.seek(fd.descriptor, byteCount, IFileSystem.SEEK_CUR);
+ return byteCount;
}
}
- private synchronized void openCheck() throws IOException {
- if (fd.descriptor < 0) {
- throw new IOException();
+ private synchronized void checkOpen() throws IOException {
+ if (!fd.valid()) {
+ throw new IOException("stream is closed");
}
}
}
diff --git a/luni/src/main/java/java/io/FileOutputStream.java b/luni/src/main/java/java/io/FileOutputStream.java
index 7c73c2e..de7fabb 100644
--- a/luni/src/main/java/java/io/FileOutputStream.java
+++ b/luni/src/main/java/java/io/FileOutputStream.java
@@ -17,49 +17,59 @@
package java.io;
+import dalvik.system.CloseGuard;
+import java.nio.NioUtils;
import java.nio.channels.FileChannel;
import libcore.io.IoUtils;
import org.apache.harmony.luni.platform.IFileSystem;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.nio.FileChannelFactory;
/**
- * A specialized {@link OutputStream} that writes to a file in the file system.
- * All write requests made by calling methods in this class are directly
- * forwarded to the equivalent function of the underlying operating system.
- * Since this may induce some performance penalty, in particular if many small
- * write requests are made, a FileOutputStream is often wrapped by a
- * BufferedOutputStream.
+ * An output stream that writes bytes to a file. If the output file exists, it
+ * can be replaced or appended to. If it does not exist, a new file will be
+ * created.
+ * <pre> {@code
+ * File file = ...
+ * OutputStream out = null;
+ * try {
+ * out = new BufferedOutputStream(new FileOutputStream(file));
+ * ...
+ * } finally {
+ * if (out != null) {
+ * out.close();
+ * }
+ * }
+ * }</pre>
+ *
+ * <p>This stream is <strong>not buffered</strong>. Most callers should wrap
+ * this stream with a {@link BufferedOutputStream}.
+ *
+ * <p>Use {@link FileWriter} to write characters, as opposed to bytes, to a file.
*
* @see BufferedOutputStream
* @see FileInputStream
*/
public class FileOutputStream extends OutputStream implements Closeable {
- /**
- * The FileDescriptor representing this FileOutputStream.
- */
- FileDescriptor fd;
+ private final FileDescriptor fd;
- boolean innerFD;
+ private final boolean shouldCloseFd;
- // The unique file channel associated with this FileInputStream (lazily
- // initialized).
+ /** The unique file channel. Lazily initialized because it's rarely needed. */
private FileChannel channel;
- private IFileSystem fileSystem = Platform.getFileSystem();
+ /** File access mode */
+ private final int mode;
+
+ private final CloseGuard guard = CloseGuard.get();
/**
- * Constructs a new FileOutputStream on the File {@code file}. If the file
- * exists, it is overwritten.
+ * Constructs a new {@code FileOutputStream} that writes to {@code file}.
*
- * @param file
- * the file to which this stream writes.
- * @throws FileNotFoundException
- * if {@code file} cannot be opened for writing.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * write request.
+ * @param file the file to which this stream writes.
+ * @throws FileNotFoundException if file cannot be opened for writing.
+ * @throws SecurityException if a {@code SecurityManager} is installed and
+ * it denies the write request.
* @see java.lang.SecurityManager#checkWrite(FileDescriptor)
*/
public FileOutputStream(File file) throws FileNotFoundException {
@@ -67,129 +77,78 @@
}
/**
- * Constructs a new FileOutputStream on the File {@code file}. The
- * parameter {@code append} determines whether or not the file is opened and
- * appended to or just opened and overwritten.
+ * Constructs a new {@code FileOutputStream} that writes to {@code file},
+ * creating it if necessary. If {@code append} is true and the file already
+ * exists, it will be appended to. Otherwise a new file will be created.
*
- * @param file
- * the file to which this stream writes.
- * @param append
- * indicates whether or not to append to an existing file.
- * @throws FileNotFoundException
- * if the {@code file} cannot be opened for writing.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * write request.
+ * @param file the file to which this stream writes.
+ * @param append true to append to an existing file.
+ * @throws FileNotFoundException if the file cannot be opened for writing.
+ * @throws SecurityException if a {@code SecurityManager} is installed and
+ * it denies the write request.
* @see java.lang.SecurityManager#checkWrite(FileDescriptor)
* @see java.lang.SecurityManager#checkWrite(String)
*/
public FileOutputStream(File file, boolean append)
throws FileNotFoundException {
- super();
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(file.getPath());
+ SecurityManager securityManager = System.getSecurityManager();
+ if (securityManager != null) {
+ securityManager.checkWrite(file.getPath());
}
- fd = new FileDescriptor();
- fd.descriptor = fileSystem.open(file.getAbsolutePath(),
- append ? IFileSystem.O_APPEND : IFileSystem.O_WRONLY);
- innerFD = true;
- channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- append ? IFileSystem.O_APPEND : IFileSystem.O_WRONLY);
+ this.fd = new FileDescriptor();
+ 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");
}
/**
- * Constructs a new FileOutputStream on the FileDescriptor {@code fd}. The
- * file must already be open, therefore no {@code FileNotFoundException}
- * will be thrown.
+ * Constructs a new {@code FileOutputStream} that writes to {@code fd}.
*
- * @param fd
- * the FileDescriptor to which this stream writes.
- * @throws NullPointerException
- * if {@code fd} is {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * write request.
+ * @param fd the FileDescriptor to which this stream writes.
+ * @throws NullPointerException if {@code fd} is null.
+ * @throws SecurityException if a {@code SecurityManager} is installed and
+ * it denies the write request.
* @see java.lang.SecurityManager#checkWrite(FileDescriptor)
*/
public FileOutputStream(FileDescriptor fd) {
- super();
if (fd == null) {
throw new NullPointerException();
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(fd);
+ SecurityManager securityManager = System.getSecurityManager();
+ if (securityManager != null) {
+ securityManager.checkWrite(fd);
}
this.fd = fd;
- innerFD = false;
- channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- IFileSystem.O_WRONLY);
+ this.shouldCloseFd = false;
+ this.channel = NioUtils.newFileChannel(this, fd.descriptor, IFileSystem.O_WRONLY);
+ this.mode = IFileSystem.O_WRONLY;
+ // Note that we do not call guard.open here because the
+ // FileDescriptor is not owned by the stream.
}
/**
- * Constructs a new FileOutputStream on the file named {@code filename}. If
- * the file exists, it is overwritten. The {@code filename} may be absolute
- * or relative to the system property {@code "user.dir"}.
- *
- * @param filename
- * the name of the file to which this stream writes.
- * @throws FileNotFoundException
- * if the file cannot be opened for writing.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * write request.
+ * Equivalent to {@code new FileOutputStream(new File(path), false)}.
*/
- public FileOutputStream(String filename) throws FileNotFoundException {
- this(filename, false);
+ public FileOutputStream(String path) throws FileNotFoundException {
+ this(path, false);
}
/**
- * Constructs a new FileOutputStream on the file named {@code filename}.
- * The parameter {@code append} determines whether or not the file is opened
- * and appended to or just opened and overwritten. The {@code filename} may
- * be absolute or relative to the system property {@code "user.dir"}.
- *
- * @param filename
- * the name of the file to which this stream writes.
- * @param append
- * indicates whether or not to append to an existing file.
- * @throws FileNotFoundException
- * if the file cannot be opened for writing.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * write request.
+ * Equivalent to {@code new FileOutputStream(new File(path), append)}.
*/
- public FileOutputStream(String filename, boolean append)
- throws FileNotFoundException {
- this(new File(filename), append);
+ public FileOutputStream(String path, boolean append) throws FileNotFoundException {
+ this(new File(path), append);
}
- /**
- * Closes this stream. This implementation closes the underlying operating
- * system resources allocated to represent this stream.
- *
- * @throws IOException
- * if an error occurs attempting to close this stream.
- */
@Override
public void close() throws IOException {
- if (fd == null) {
- // if fd is null, then the underlying file is not opened, so nothing
- // to close
- return;
- }
-
- if (channel != null) {
- synchronized (channel) {
- if (channel.isOpen() && fd.descriptor >= 0) {
- channel.close();
- }
- }
- }
-
+ guard.close();
synchronized (this) {
- if (fd.valid() && innerFD) {
+ if (channel != null) {
+ channel.close();
+ }
+ if (shouldCloseFd && fd.valid()) {
IoUtils.close(fd);
}
}
@@ -204,123 +163,71 @@
*/
@Override protected void finalize() throws IOException {
try {
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
close();
} finally {
try {
super.finalize();
} catch (Throwable t) {
+ // for consistency with the RI, we must override Object.finalize() to
+ // remove the 'throws Throwable' clause.
throw new AssertionError(t);
}
}
}
/**
- * Returns the FileChannel equivalent to this output stream.
- * <p>
- * The file channel is write-only and has an initial position within the
- * file that is the same as the current position of this stream within the
- * file. All changes made to the underlying file descriptor state via the
- * channel are visible by the output stream and vice versa.
- *
- * @return the file channel representation for this stream.
+ * Returns a write-only {@link FileChannel} that shares its position with
+ * this stream.
*/
public FileChannel getChannel() {
- return channel;
+ synchronized (this) {
+ if (channel == null) {
+ channel = NioUtils.newFileChannel(this, fd.descriptor, mode);
+ }
+ return channel;
+ }
}
/**
- * Returns a FileDescriptor which represents the lowest level representation
- * of an operating system stream resource.
- *
- * @return a FileDescriptor representing this stream.
- * @throws IOException
- * if an error occurs attempting to get the FileDescriptor of
- * this stream.
+ * Returns the underlying file descriptor.
*/
public final FileDescriptor getFD() throws IOException {
return fd;
}
- /**
- * Writes the entire contents of the byte array {@code buffer} to this
- * stream.
- *
- * @param buffer
- * the buffer to be written to the file.
- * @throws IOException
- * if this stream is closed or an error occurs attempting to
- * write to this stream.
- */
@Override
public void write(byte[] buffer) throws IOException {
write(buffer, 0, buffer.length);
}
- /**
- * Writes {@code count} bytes from the byte array {@code buffer} starting at
- * {@code offset} to this stream.
- *
- * @param buffer
- * the buffer to write to this stream.
- * @param offset
- * the index of the first byte in {@code buffer} to write.
- * @param count
- * the number of bytes from {@code buffer} to write.
- * @throws IndexOutOfBoundsException
- * if {@code count < 0} or {@code offset < 0}, or if
- * {@code count + offset} is greater than the length of
- * {@code buffer}.
- * @throws IOException
- * if this stream is closed or an error occurs attempting to
- * write to this stream.
- * @throws NullPointerException
- * if {@code buffer} is {@code null}.
- */
@Override
public void write(byte[] buffer, int offset, int count) throws IOException {
- // BEGIN android-changed
- // Exception priorities (in case of multiple errors) differ from
- // RI, but are spec-compliant.
- // removed redundant check, made implicit null check explicit,
- // used (offset | count) < 0 instead of (offset < 0) || (count < 0)
- // to safe one operation
if (buffer == null) {
throw new NullPointerException("buffer == null");
}
if ((count | offset) < 0 || count > buffer.length - offset) {
throw new IndexOutOfBoundsException();
}
- // END android-changed
-
if (count == 0) {
return;
}
-
- openCheck();
- fileSystem.write(fd.descriptor, buffer, offset, count);
+ checkOpen();
+ Platform.FILE_SYSTEM.write(fd.descriptor, buffer, offset, count);
}
- /**
- * Writes the specified byte {@code oneByte} to this stream. Only the low
- * order byte of the integer {@code oneByte} is written.
- *
- * @param oneByte
- * the byte to be written.
- * @throws IOException
- * if this stream is closed an error occurs attempting to write
- * to this stream.
- */
@Override
public void write(int oneByte) throws IOException {
- openCheck();
- byte[] byteArray = new byte[1];
- byteArray[0] = (byte) oneByte;
- fileSystem.write(fd.descriptor, byteArray, 0, 1);
+ checkOpen();
+ byte[] buffer = { (byte) oneByte };
+ Platform.FILE_SYSTEM.write(fd.descriptor, buffer, 0, 1);
}
- private synchronized void openCheck() throws IOException {
- if (fd.descriptor < 0) {
- throw new IOException();
+ private synchronized void checkOpen() throws IOException {
+ if (!fd.valid()) {
+ throw new IOException("stream is closed");
}
}
}
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/InputStream.java b/luni/src/main/java/java/io/InputStream.java
index 6e4f561..2d59397 100644
--- a/luni/src/main/java/java/io/InputStream.java
+++ b/luni/src/main/java/java/io/InputStream.java
@@ -161,7 +161,7 @@
* Reads at most {@code length} bytes from this stream and stores them in
* the byte array {@code b} starting at {@code offset}.
*
- * @param b
+ * @param buffer
* the byte array in which to store the bytes read.
* @param offset
* the initial position in {@code buffer} to store the bytes read
@@ -177,15 +177,11 @@
* @throws IOException
* if the stream is closed or another IOException occurs.
*/
- public int read(byte[] b, int offset, int length) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
- // Force null check for b first!
- if (offset > b.length || offset < 0) {
+ public int read(byte[] buffer, int offset, int length) throws IOException {
+ if (offset > buffer.length || offset < 0) {
throw new ArrayIndexOutOfBoundsException("Offset out of bounds: " + offset);
}
- if (length < 0 || length > b.length - offset) {
+ if (length < 0 || length > buffer.length - offset) {
throw new ArrayIndexOutOfBoundsException("Length out of bounds: " + length);
}
for (int i = 0; i < length; i++) {
@@ -200,7 +196,7 @@
}
throw e;
}
- b[offset + i] = (byte) c;
+ buffer[offset + i] = (byte) c;
}
return length;
}
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/ObjectInputStream.java b/luni/src/main/java/java/io/ObjectInputStream.java
index 749eb29..25e5574 100644
--- a/luni/src/main/java/java/io/ObjectInputStream.java
+++ b/luni/src/main/java/java/io/ObjectInputStream.java
@@ -70,7 +70,7 @@
private int nestedLevels;
// All objects are assigned an ID (integer handle)
- private int currentHandle;
+ private int nextHandle;
// Where we read from
private DataInputStream input;
@@ -388,7 +388,7 @@
final Class<?> thisClass = ObjectInputStream.class;
SecurityManager sm = System.getSecurityManager();
if (sm != null && implementationClass != thisClass) {
- boolean mustCheck = (AccessController
+ boolean mustCheck = AccessController
.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
try {
@@ -399,7 +399,7 @@
if (method.getDeclaringClass() != thisClass) {
return Boolean.TRUE;
}
- } catch (NoSuchMethodException e) {
+ } catch (NoSuchMethodException ignored) {
}
try {
Method method = implementationClass
@@ -409,11 +409,11 @@
if (method.getDeclaringClass() != thisClass) {
return Boolean.TRUE;
}
- } catch (NoSuchMethodException e) {
+ } catch (NoSuchMethodException ignored) {
}
return Boolean.FALSE;
}
- })).booleanValue();
+ });
if (mustCheck) {
sm
.checkPermission(ObjectStreamConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
@@ -540,7 +540,7 @@
throws SecurityException {
if (enable) {
// The Stream has to be trusted for this feature to be enabled.
- // trusted means the stream's classloader has to be null
+ // trusted means the stream's class loader has to be null
SecurityManager currentManager = System.getSecurityManager();
if (currentManager != null) {
currentManager.checkPermission(SUBSTITUTION_PERMISSION);
@@ -605,7 +605,7 @@
* @return the next handle to represent the next cyclic reference
*/
private Integer nextHandle() {
- return Integer.valueOf(this.currentHandle++);
+ return nextHandle++;
}
/**
@@ -1156,21 +1156,21 @@
element.defaulted = false;
Class<?> type = element.field.getType();
if (type == Integer.TYPE) {
- element.fieldValue = Integer.valueOf(input.readInt());
+ element.fieldValue = input.readInt();
} else if (type == Byte.TYPE) {
- element.fieldValue = Byte.valueOf(input.readByte());
+ element.fieldValue = input.readByte();
} else if (type == Character.TYPE) {
- element.fieldValue = Character.valueOf(input.readChar());
+ element.fieldValue = input.readChar();
} else if (type == Short.TYPE) {
- element.fieldValue = Short.valueOf(input.readShort());
+ element.fieldValue = input.readShort();
} else if (type == Boolean.TYPE) {
- element.fieldValue = Boolean.valueOf(input.readBoolean());
+ element.fieldValue = input.readBoolean();
} else if (type == Long.TYPE) {
- element.fieldValue = Long.valueOf(input.readLong());
+ element.fieldValue = input.readLong();
} else if (type == Float.TYPE) {
- element.fieldValue = Float.valueOf(input.readFloat());
+ element.fieldValue = input.readFloat();
} else if (type == Double.TYPE) {
- element.fieldValue = Double.valueOf(input.readDouble());
+ element.fieldValue = input.readDouble();
} else {
// Either array or Object
try {
@@ -1271,7 +1271,7 @@
fieldDesc.getTypeCode());
}
// END android-changed
- } catch (NoSuchFieldError err) {
+ } catch (NoSuchFieldError ignored) {
}
} else {
// Object type (array included).
@@ -1336,10 +1336,10 @@
}
/**
- * Reads bytes from the source stream into the byte array {@code buffer}.
- * This method will block until {@code buffer.length} bytes have been read.
+ * Reads bytes from the source stream into the byte array {@code dst}.
+ * This method will block until {@code dst.length} bytes have been read.
*
- * @param buffer
+ * @param dst
* the array in which to store the bytes read.
* @throws EOFException
* if the end of the input is reached before the read
@@ -1347,31 +1347,28 @@
* @throws IOException
* if an error occurs while reading from the source stream.
*/
- public void readFully(byte[] buffer) throws IOException {
- primitiveTypes.readFully(buffer);
+ public void readFully(byte[] dst) throws IOException {
+ primitiveTypes.readFully(dst);
}
/**
- * Reads bytes from the source stream into the byte array {@code buffer}.
- * This method will block until {@code length} number of bytes have been
- * read.
+ * Reads {@code byteCount} bytes from the source stream into the byte array {@code dst}.
*
- * @param buffer
+ * @param dst
* the byte array in which to store the bytes read.
* @param offset
- * the initial position in {@code buffer} to store the bytes
+ * the initial position in {@code dst} to store the bytes
* read from the source stream.
- * @param length
- * the maximum number of bytes to store in {@code buffer}.
+ * @param byteCount
+ * the number of bytes to read.
* @throws EOFException
* if the end of the input is reached before the read
* request can be satisfied.
* @throws IOException
* if an error occurs while reading from the source stream.
*/
- public void readFully(byte[] buffer, int offset, int length)
- throws IOException {
- primitiveTypes.readFully(buffer, offset, length);
+ public void readFully(byte[] dst, int offset, int byteCount) throws IOException {
+ primitiveTypes.readFully(dst, offset, byteCount);
}
/**
@@ -1416,10 +1413,8 @@
nextStreamClass = nextStreamClass.getSuperclass();
}
if (object == null) {
- Iterator<ObjectStreamClass> streamIt = streamClassList.iterator();
- while (streamIt.hasNext()) {
- ObjectStreamClass streamClass = streamIt.next();
- readObjectForClass(null, streamClass);
+ for (ObjectStreamClass objectStreamClass : streamClassList) {
+ readObjectForClass(null, objectStreamClass);
}
} else {
ArrayList<Class<?>> classList = new ArrayList<Class<?>>(32);
@@ -1432,12 +1427,11 @@
nextClass = testClass;
}
int lastIndex = 0;
- for (int i = 0; i < classList.size(); i++) {
- Class<?> superclass = classList.get(i);
- int index = findStreamSuperclass(superclass, streamClassList,
- lastIndex);
+ for (Class<?> superclass : classList) {
+ int index = findStreamSuperclass(superclass, streamClassList, lastIndex);
if (index == -1) {
- readObjectNoData(object, superclass, ObjectStreamClass.lookupStreamClass(superclass));
+ readObjectNoData(object, superclass,
+ ObjectStreamClass.lookupStreamClass(superclass));
} else {
for (int j = lastIndex; j <= index; j++) {
readObjectForClass(object, streamClassList.get(j));
@@ -1479,7 +1473,7 @@
if (classDesc.hasMethodReadObjectNoData()){
final Method readMethod = classDesc.getMethodReadObjectNoData();
try {
- readMethod.invoke(object, new Object[0]);
+ readMethod.invoke(object);
} catch (InvocationTargetException e) {
Throwable ex = e.getTargetException();
if (ex instanceof RuntimeException) {
@@ -1517,7 +1511,7 @@
AccessController.doPrivileged(new PriviAction<Object>(
readMethod));
try {
- readMethod.invoke(object, new Object[] { this });
+ readMethod.invoke(object, this);
} catch (InvocationTargetException e) {
Throwable ex = e.getTargetException();
if (ex instanceof ClassNotFoundException) {
@@ -1608,7 +1602,7 @@
ObjectStreamClass classDesc = readClassDesc();
if (classDesc == null) {
- missingClassDescriptor();
+ throw missingClassDescriptor();
}
Integer newHandle = nextHandle();
@@ -1701,7 +1695,7 @@
private Class<?> readNewClass(boolean unshared) throws ClassNotFoundException, IOException {
ObjectStreamClass classDesc = readClassDesc();
if (classDesc == null) {
- missingClassDescriptor();
+ throw missingClassDescriptor();
}
Class<?> localClass = classDesc.forClass();
if (localClass != null) {
@@ -1981,8 +1975,8 @@
// Has to have an empty constructor
if (constructor == null) {
- throw new InvalidClassException(constructorClass.getName(),
- "IllegalAccessException");
+ String className = constructorClass != null ? constructorClass.getName() : null;
+ throw new InvalidClassException(className, "IllegalAccessException");
}
int constructorModifiers = constructor.getModifiers();
@@ -2124,7 +2118,7 @@
Method methodReadResolve = classDesc.getMethodReadResolve();
try {
result = methodReadResolve.invoke(result, (Object[]) null);
- } catch (IllegalAccessException iae) {
+ } catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ite) {
Throwable target = ite.getTargetException();
if (target instanceof ObjectStreamException) {
@@ -2318,7 +2312,7 @@
// END android-added
/**
- * Method to be overriden by subclasses to read the next object from the
+ * Method to be overridden by subclasses to read the next object from the
* source stream.
*
* @return the object read from the source stream.
@@ -2517,7 +2511,7 @@
*/
private void resetSeenObjects() {
objectsRead = new HashMap<Integer, Object>();
- currentHandle = baseWireHandle;
+ nextHandle = baseWireHandle;
primitiveData = emptyStream;
}
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/ObjectStreamClass.java b/luni/src/main/java/java/io/ObjectStreamClass.java
index 7f968af..38bce57 100644
--- a/luni/src/main/java/java/io/ObjectStreamClass.java
+++ b/luni/src/main/java/java/io/ObjectStreamClass.java
@@ -17,12 +17,14 @@
package java.io;
+import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
+import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -31,8 +33,8 @@
import java.util.Comparator;
import java.util.List;
import java.util.WeakHashMap;
+import org.apache.harmony.luni.platform.OSMemory;
import org.apache.harmony.luni.util.PriviAction;
-import org.apache.harmony.luni.util.ThreadLocalCache;
/**
* Represents a descriptor for identifying a class during serialization and
@@ -588,12 +590,11 @@
// now compute the UID based on the SHA
byte[] hash = digest.digest(sha.toByteArray());
-
- return littleEndianLongAt(hash, 0);
+ return OSMemory.peekLong(hash, 0, ByteOrder.LITTLE_ENDIAN);
}
/**
- * Returns what the serializaton specification calls "descriptor" given a
+ * Returns what the serialization specification calls "descriptor" given a
* field signature.
*
* @param signature
@@ -605,7 +606,7 @@
}
/**
- * Return what the serializaton specification calls "descriptor" given a
+ * Return what the serialization specification calls "descriptor" given a
* method/constructor signature.
*
* @param signature
@@ -913,23 +914,6 @@
}
/**
- * Return a little endian long stored in a given position of the buffer
- *
- * @param buffer
- * a byte array with the byte representation of the number
- * @param position
- * index where the number starts in the byte array
- * @return the number that was stored in little endian format
- */
- private static long littleEndianLongAt(byte[] buffer, int position) {
- long result = 0;
- for (int i = position + 7; i >= position; i--) {
- result = (result << 8) + (buffer[i] & 0xff);
- }
- return result;
- }
-
- /**
* Returns the descriptor for a serializable class.
* Returns null if the class doesn't implement {@code Serializable} or {@code Externalizable}.
*
@@ -974,8 +958,7 @@
* @return the corresponding descriptor
*/
static ObjectStreamClass lookupStreamClass(Class<?> cl) {
-
- WeakHashMap<Class<?>,ObjectStreamClass> tlc = OSCThreadLocalCache.oscWeakHashMap.get();
+ WeakHashMap<Class<?>,ObjectStreamClass> tlc = getCache();
ObjectStreamClass cachedValue = tlc.get(cl);
if (cachedValue == null) {
@@ -987,6 +970,26 @@
}
/**
+ * A ThreadLocal cache for lookupStreamClass, with the possibility of discarding the thread
+ * local storage content when the heap is exhausted.
+ */
+ private static SoftReference<ThreadLocal<WeakHashMap<Class<?>, ObjectStreamClass>>> storage =
+ new SoftReference<ThreadLocal<WeakHashMap<Class<?>, ObjectStreamClass>>>(null);
+
+ private static WeakHashMap<Class<?>, ObjectStreamClass> getCache() {
+ ThreadLocal<WeakHashMap<Class<?>, ObjectStreamClass>> tls = storage.get();
+ if (tls == null) {
+ tls = new ThreadLocal<WeakHashMap<Class<?>, ObjectStreamClass>>() {
+ public WeakHashMap<Class<?>, ObjectStreamClass> initialValue() {
+ return new WeakHashMap<Class<?>, ObjectStreamClass>();
+ }
+ };
+ storage = new SoftReference<ThreadLocal<WeakHashMap<Class<?>, ObjectStreamClass>>>(tls);
+ }
+ return tls.get();
+ }
+
+ /**
* Return the java.lang.reflect.Method if class <code>cl</code> implements
* <code>methodName</code> . Return null otherwise.
*
@@ -1192,19 +1195,6 @@
*/
@Override
public String toString() {
- return getName() + ": static final long serialVersionUID ="
- + getSerialVersionUID() + "L;";
+ return getName() + ": static final long serialVersionUID =" + getSerialVersionUID() + "L;";
}
-
- static class OSCThreadLocalCache extends ThreadLocalCache {
-
- // thread-local cache for ObjectStreamClass.lookup
- public static ThreadLocalCache<WeakHashMap<Class<?>,ObjectStreamClass>> oscWeakHashMap = new ThreadLocalCache<WeakHashMap<Class<?>,ObjectStreamClass>>() {
- protected WeakHashMap<Class<?>,ObjectStreamClass> initialValue() {
- return new WeakHashMap<Class<?>,ObjectStreamClass>();
- }
- };
-
- }
-
}
diff --git a/luni/src/main/java/java/io/RandomAccessFile.java b/luni/src/main/java/java/io/RandomAccessFile.java
index 615a755..414f47a 100644
--- a/luni/src/main/java/java/io/RandomAccessFile.java
+++ b/luni/src/main/java/java/io/RandomAccessFile.java
@@ -17,12 +17,17 @@
package java.io;
+import dalvik.system.CloseGuard;
+import java.nio.ByteOrder;
+import java.nio.NioUtils;
import java.nio.channels.FileChannel;
import java.nio.charset.ModifiedUtf8;
+import libcore.base.Streams;
import libcore.io.IoUtils;
+import libcore.io.SizeOf;
import org.apache.harmony.luni.platform.IFileSystem;
+import org.apache.harmony.luni.platform.OSMemory;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.nio.FileChannelFactory;
/**
* Allows reading from and writing to a file in a random-access manner. This is
@@ -44,13 +49,11 @@
// initialized).
private FileChannel channel;
- private IFileSystem fileSystem = Platform.getFileSystem();
+ private int mode;
- private boolean isReadOnly;
+ private final CloseGuard guard = CloseGuard.get();
- // BEGIN android-added
- private int options;
- // END android-added
+ private final byte[] scratch = new byte[8];
/**
* Constructs a new {@code RandomAccessFile} based on {@code file} and opens
@@ -99,15 +102,13 @@
* @see java.lang.SecurityManager#checkWrite(FileDescriptor)
*/
public RandomAccessFile(File file, String mode) throws FileNotFoundException {
- options = 0;
+ int options;
fd = new FileDescriptor();
if (mode.equals("r")) {
- isReadOnly = true;
fd.readOnly = true;
options = IFileSystem.O_RDONLY;
} else if (mode.equals("rw") || mode.equals("rws") || mode.equals("rwd")) {
- isReadOnly = false;
options = IFileSystem.O_RDWR;
if (mode.equals("rws")) {
@@ -120,20 +121,17 @@
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
+ this.mode = options;
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(file.getPath());
- if (!isReadOnly) {
+ if (!mode.equals("r")) {
security.checkWrite(file.getPath());
}
}
- fd.descriptor = fileSystem.open(file.getAbsolutePath(), options);
- // BEGIN android-removed
- // channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- // options);
- // END android-removed
+ fd.descriptor = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), this.mode);
// if we are in "rws" mode, attempt to sync file+metadata
if (syncMetadata) {
@@ -143,6 +141,7 @@
// Ignored
}
}
+ guard.open("close");
}
/**
@@ -168,8 +167,7 @@
* @see java.lang.SecurityManager#checkRead(FileDescriptor)
* @see java.lang.SecurityManager#checkWrite(FileDescriptor)
*/
- public RandomAccessFile(String fileName, String mode)
- throws FileNotFoundException {
+ public RandomAccessFile(String fileName, String mode) throws FileNotFoundException {
this(new File(fileName), mode);
}
@@ -180,6 +178,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();
@@ -193,6 +192,9 @@
@Override protected void finalize() throws Throwable {
try {
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
close();
} finally {
super.finalize();
@@ -210,12 +212,9 @@
* @return this file's file channel instance.
*/
public final synchronized FileChannel getChannel() {
- // BEGIN android-added
if(channel == null) {
- channel = FileChannelFactory.getFileChannel(this, fd.descriptor,
- options);
+ channel = NioUtils.newFileChannel(this, fd.descriptor, mode);
}
- // END android-added
return channel;
}
@@ -244,7 +243,7 @@
*/
public long getFilePointer() throws IOException {
openCheck();
- return fileSystem.seek(fd.descriptor, 0L, IFileSystem.SEEK_CUR);
+ return Platform.FILE_SYSTEM.seek(fd.descriptor, 0L, IFileSystem.SEEK_CUR);
}
/**
@@ -269,7 +268,7 @@
*/
public long length() throws IOException {
openCheck();
- return fileSystem.length(fd.descriptor);
+ return Platform.FILE_SYSTEM.length(fd.descriptor);
}
/**
@@ -284,9 +283,8 @@
*/
public int read() throws IOException {
openCheck();
- byte[] bytes = new byte[1];
- long byteCount = fileSystem.read(fd.descriptor, bytes, 0, 1);
- return byteCount == -1 ? -1 : bytes[0] & 0xff;
+ long byteCount = Platform.FILE_SYSTEM.read(fd.descriptor, scratch, 0, 1);
+ return byteCount == -1 ? -1 : scratch[0] & 0xff;
}
/**
@@ -341,11 +339,11 @@
throw new IndexOutOfBoundsException();
}
// END android-changed
- if (0 == count) {
+ if (count == 0) {
return 0;
}
openCheck();
- return (int) fileSystem.read(fd.descriptor, buffer, offset, count);
+ return (int) Platform.FILE_SYSTEM.read(fd.descriptor, buffer, offset, count);
}
/**
@@ -389,7 +387,7 @@
}
/**
- * Reads a 16-bit character from the current position in this file. Blocks until
+ * Reads a big-endian 16-bit character from the current position in this file. Blocks until
* two bytes have been read, the end of the file is reached or an exception is
* thrown.
*
@@ -401,15 +399,11 @@
* @see #writeChar(int)
*/
public final char readChar() throws IOException {
- byte[] buffer = new byte[2];
- if (read(buffer, 0, buffer.length) != buffer.length) {
- throw new EOFException();
- }
- return (char) (((buffer[0] & 0xff) << 8) + (buffer[1] & 0xff));
+ return (char) readShort();
}
/**
- * Reads a 64-bit double from the current position in this file. Blocks
+ * Reads a big-endian 64-bit double from the current position in this file. Blocks
* until eight bytes have been read, the end of the file is reached or an
* exception is thrown.
*
@@ -425,7 +419,7 @@
}
/**
- * Reads a 32-bit float from the current position in this file. Blocks
+ * Reads a big-endian 32-bit float from the current position in this file. Blocks
* until four bytes have been read, the end of the file is reached or an
* exception is thrown.
*
@@ -441,48 +435,41 @@
}
/**
- * Reads bytes from this file into {@code buffer}. Blocks until {@code
- * buffer.length} number of bytes have been read, the end of the file is
- * reached or an exception is thrown.
- *
- * @param buffer
- * the buffer to read bytes into.
- * @throws EOFException
- * if the end of this file is detected.
- * @throws IOException
- * if this file is closed or another I/O error occurs.
- * @throws NullPointerException
- * if {@code buffer} is {@code null}.
+ * Equivalent to {@code readFully(dst, 0, dst.length);}.
*/
- public final void readFully(byte[] buffer) throws IOException {
- readFully(buffer, 0, buffer.length);
+ public final void readFully(byte[] dst) throws IOException {
+ readFully(dst, 0, dst.length);
}
/**
- * Read bytes from this file into {@code buffer} starting at offset {@code
- * offset}. This method blocks until {@code count} number of bytes have been
- * read.
+ * Reads {@code byteCount} bytes from this stream and stores them in the byte
+ * array {@code dst} starting at {@code offset}. If {@code byteCount} is zero, then this
+ * method returns without reading any bytes. Otherwise, this method blocks until
+ * {@code byteCount} bytes have been read. If insufficient bytes are available,
+ * {@code EOFException} is thrown. If an I/O error occurs, {@code IOException} is
+ * thrown. When an exception is thrown, some bytes may have been consumed from the stream
+ * and written into the array.
*
- * @param buffer
- * the buffer to read bytes into.
+ * @param dst
+ * the byte array into which the data is read.
* @param offset
- * the initial position in {@code buffer} to store the bytes read
- * from this file.
- * @param count
- * the maximum number of bytes to store in {@code buffer}.
+ * the offset in {@code dst} at which to store the bytes.
+ * @param byteCount
+ * the number of bytes to read.
* @throws EOFException
- * if the end of this file is detected.
+ * if the end of the source stream is reached before enough
+ * bytes have been read.
* @throws IndexOutOfBoundsException
- * if {@code offset < 0} or {@code count < 0}, or if {@code
- * offset + count} is greater than the length of {@code buffer}.
+ * if {@code offset < 0} or {@code byteCount < 0}, or
+ * {@code offset + byteCount > dst.length}.
* @throws IOException
- * if this file is closed or another I/O error occurs.
+ * if a problem occurs while reading from this stream.
* @throws NullPointerException
- * if {@code buffer} is {@code null}.
+ * if {@code dst} is null.
*/
- public final void readFully(byte[] buffer, int offset, int count) throws IOException {
- if (buffer == null) {
- throw new NullPointerException("buffer == null");
+ public final void readFully(byte[] dst, int offset, int byteCount) throws IOException {
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
}
// avoid int overflow
// BEGIN android-changed
@@ -490,22 +477,22 @@
// RI, but are spec-compliant.
// removed redundant check, used (offset | count) < 0
// instead of (offset < 0) || (count < 0) to safe one operation
- if ((offset | count) < 0 || count > buffer.length - offset) {
+ if ((offset | byteCount) < 0 || byteCount > dst.length - offset) {
throw new IndexOutOfBoundsException();
}
// END android-changed
- while (count > 0) {
- int result = read(buffer, offset, count);
+ while (byteCount > 0) {
+ int result = read(dst, offset, byteCount);
if (result < 0) {
throw new EOFException();
}
offset += result;
- count -= result;
+ byteCount -= result;
}
}
/**
- * Reads a 32-bit integer from the current position in this file. Blocks
+ * Reads a big-endian 32-bit integer from the current position in this file. Blocks
* until four bytes have been read, the end of the file is reached or an
* exception is thrown.
*
@@ -517,12 +504,8 @@
* @see #writeInt(int)
*/
public final int readInt() throws IOException {
- byte[] buffer = new byte[4];
- if (read(buffer, 0, buffer.length) != buffer.length) {
- throw new EOFException();
- }
- return ((buffer[0] & 0xff) << 24) + ((buffer[1] & 0xff) << 16)
- + ((buffer[2] & 0xff) << 8) + (buffer[3] & 0xff);
+ readFully(scratch, 0, SizeOf.INT);
+ return OSMemory.peekInt(scratch, 0, ByteOrder.BIG_ENDIAN);
}
/**
@@ -570,7 +553,7 @@
}
/**
- * Reads a 64-bit long from the current position in this file. Blocks until
+ * Reads a big-endian 64-bit long from the current position in this file. Blocks until
* eight bytes have been read, the end of the file is reached or an
* exception is thrown.
*
@@ -582,20 +565,12 @@
* @see #writeLong(long)
*/
public final long readLong() throws IOException {
- byte[] buffer = new byte[8];
- if (read(buffer, 0, buffer.length) != buffer.length) {
- throw new EOFException();
- }
- return ((long) (((buffer[0] & 0xff) << 24) + ((buffer[1] & 0xff) << 16)
- + ((buffer[2] & 0xff) << 8) + (buffer[3] & 0xff)) << 32)
- + ((long) (buffer[4] & 0xff) << 24)
- + ((buffer[5] & 0xff) << 16)
- + ((buffer[6] & 0xff) << 8)
- + (buffer[7] & 0xff);
+ readFully(scratch, 0, SizeOf.LONG);
+ return OSMemory.peekLong(scratch, 0, ByteOrder.BIG_ENDIAN);
}
/**
- * Reads a 16-bit short from the current position in this file. Blocks until
+ * Reads a big-endian 16-bit short from the current position in this file. Blocks until
* two bytes have been read, the end of the file is reached or an exception
* is thrown.
*
@@ -607,11 +582,8 @@
* @see #writeShort(int)
*/
public final short readShort() throws IOException {
- byte[] buffer = new byte[2];
- if (read(buffer, 0, buffer.length) != buffer.length) {
- throw new EOFException();
- }
- return (short) (((buffer[0] & 0xff) << 8) + (buffer[1] & 0xff));
+ readFully(scratch, 0, SizeOf.SHORT);
+ return OSMemory.peekShort(scratch, 0, ByteOrder.BIG_ENDIAN);
}
/**
@@ -635,7 +607,7 @@
}
/**
- * Reads an unsigned 16-bit short from the current position in this file and
+ * Reads an unsigned big-endian 16-bit short from the current position in this file and
* returns it as an integer. Blocks until two bytes have been read, the end of
* the file is reached or an exception is thrown.
*
@@ -647,11 +619,7 @@
* @see #writeShort(int)
*/
public final int readUnsignedShort() throws IOException {
- byte[] buffer = new byte[2];
- if (read(buffer, 0, buffer.length) != buffer.length) {
- throw new EOFException();
- }
- return ((buffer[0] & 0xff) << 8) + (buffer[1] & 0xff);
+ return ((int) readShort()) & 0xffff;
}
/**
@@ -702,7 +670,7 @@
throw new IOException("offset < 0");
}
openCheck();
- fileSystem.seek(fd.descriptor, offset, IFileSystem.SEEK_SET);
+ Platform.FILE_SYSTEM.seek(fd.descriptor, offset, IFileSystem.SEEK_SET);
}
/**
@@ -722,9 +690,14 @@
public void setLength(long newLength) throws IOException {
openCheck();
if (newLength < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("newLength < 0");
}
- fileSystem.truncate(fd.descriptor, newLength);
+ Platform.FILE_SYSTEM.truncate(fd.descriptor, newLength);
+
+ long filePointer = getFilePointer();
+ if (filePointer > newLength) {
+ seek(newLength);
+ }
// if we are in "rws" mode, attempt to sync file+metadata
if (syncMetadata) {
@@ -747,8 +720,7 @@
public int skipBytes(int count) throws IOException {
if (count > 0) {
long currentPos = getFilePointer(), eof = length();
- int newCount = (int) ((currentPos + count > eof) ? eof - currentPos
- : count);
+ int newCount = (int) ((currentPos + count > eof) ? eof - currentPos : count);
seek(currentPos + newCount);
return newCount;
}
@@ -763,10 +735,6 @@
* the buffer to write.
* @throws IOException
* if an I/O error occurs while writing to this file.
- * @see #read(byte[])
- * @see #read(byte[],int,int)
- * @see #readFully(byte[])
- * @see #readFully(byte[],int,int)
*/
public void write(byte[] buffer) throws IOException {
write(buffer, 0, buffer.length);
@@ -788,8 +756,6 @@
* offset} is greater than the size of {@code buffer}.
* @throws IOException
* if an I/O error occurs while writing to this file.
- * @see #read(byte[], int, int)
- * @see #readFully(byte[], int, int)
*/
public void write(byte[] buffer, int offset, int count) throws IOException {
// BEGIN android-changed
@@ -809,7 +775,7 @@
return;
}
openCheck();
- fileSystem.write(fd.descriptor, buffer, offset, count);
+ Platform.FILE_SYSTEM.write(fd.descriptor, buffer, offset, count);
// if we are in "rws" mode, attempt to sync file+metadata
if (syncMetadata) {
@@ -829,9 +795,8 @@
*/
public void write(int oneByte) throws IOException {
openCheck();
- byte[] bytes = new byte[1];
- bytes[0] = (byte) (oneByte & 0xff);
- fileSystem.write(fd.descriptor, bytes, 0, 1);
+ scratch[0] = (byte) (oneByte & 0xff);
+ Platform.FILE_SYSTEM.write(fd.descriptor, scratch, 0, 1);
// if we are in "rws" mode, attempt to sync file+metadata
if (syncMetadata) {
@@ -840,7 +805,8 @@
}
/**
- * Writes a boolean to this file, starting at the current file pointer.
+ * Writes a boolean to this file as a single byte (1 for true, 0 for false), starting at the
+ * current file pointer.
*
* @param val
* the boolean to write to this file.
@@ -875,10 +841,6 @@
* the string containing the bytes to write to this file
* @throws IOException
* if an I/O error occurs while writing to this file.
- * @see #read(byte[])
- * @see #read(byte[],int,int)
- * @see #readFully(byte[])
- * @see #readFully(byte[],int,int)
*/
public final void writeBytes(String str) throws IOException {
byte[] bytes = new byte[str.length()];
@@ -889,7 +851,7 @@
}
/**
- * Writes a 16-bit character to this file, starting at the current file
+ * Writes a big-endian 16-bit character to this file, starting at the current file
* pointer. Only the two least significant bytes of the integer {@code val}
* are written, with the high byte first.
*
@@ -900,16 +862,12 @@
* @see #readChar()
*/
public final void writeChar(int val) throws IOException {
- byte[] buffer = new byte[2];
- buffer[0] = (byte) (val >> 8);
- buffer[1] = (byte) val;
- write(buffer, 0, buffer.length);
+ writeShort(val);
}
/**
- * Writes the 16-bit characters from a string to this file, starting at the
- * current file pointer. Each character is written in the same way as with
- * {@link #writeChar(int)}, with its high byte first.
+ * Writes big-endian 16-bit characters from {@code str} to this file, starting at the
+ * current file pointer.
*
* @param str
* the string to write to this file.
@@ -918,19 +876,13 @@
* @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"));
}
/**
- * Writes a 64-bit double to this file, starting at the current file
- * pointer. The eight bytes returned by
- * {@link Double#doubleToLongBits(double)} are written to this file.
+ * Writes a big-endian 64-bit double to this file, starting at the current file
+ * pointer. The bytes are those returned by
+ * {@link Double#doubleToLongBits(double)}, meaning a canonical NaN is used.
*
* @param val
* the double to write to this file.
@@ -943,9 +895,9 @@
}
/**
- * Writes a 32-bit float to this file, starting at the current file pointer.
- * The four bytes returned by {@link Float#floatToIntBits(float)} are
- * written to this file.
+ * Writes a big-endian 32-bit float to this file, starting at the current file pointer.
+ * The bytes are those returned by {@link Float#floatToIntBits(float)}, meaning a canonical NaN
+ * is used.
*
* @param val
* the float to write to this file.
@@ -958,9 +910,8 @@
}
/**
- * Writes a 32-bit integer to this file, starting at the current file
- * pointer. The four bytes of the integer are written with the highest byte
- * first.
+ * Writes a big-endian 32-bit integer to this file, starting at the current file
+ * pointer.
*
* @param val
* the int to write to this file.
@@ -969,18 +920,13 @@
* @see #readInt()
*/
public final void writeInt(int val) throws IOException {
- byte[] buffer = new byte[4];
- buffer[0] = (byte) (val >> 24);
- buffer[1] = (byte) (val >> 16);
- buffer[2] = (byte) (val >> 8);
- buffer[3] = (byte) val;
- write(buffer, 0, buffer.length);
+ OSMemory.pokeInt(scratch, 0, val, ByteOrder.BIG_ENDIAN);
+ write(scratch, 0, SizeOf.INT);
}
/**
- * Writes a 64-bit long to this file, starting at the current file
- * pointer. The eight bytes of the long are written with the highest byte
- * first.
+ * Writes a big-endian 64-bit long to this file, starting at the current file
+ * pointer.
*
* @param val
* the long to write to this file.
@@ -989,23 +935,14 @@
* @see #readLong()
*/
public final void writeLong(long val) throws IOException {
- byte[] buffer = new byte[8];
- int t = (int) (val >> 32);
- buffer[0] = (byte) (t >> 24);
- buffer[1] = (byte) (t >> 16);
- buffer[2] = (byte) (t >> 8);
- buffer[3] = (byte) t;
- buffer[4] = (byte) (val >> 24);
- buffer[5] = (byte) (val >> 16);
- buffer[6] = (byte) (val >> 8);
- buffer[7] = (byte) val;
- write(buffer, 0, buffer.length);
+ OSMemory.pokeLong(scratch, 0, val, ByteOrder.BIG_ENDIAN);
+ write(scratch, 0, SizeOf.LONG);
}
/**
- * Writes a 16-bit short to this file, starting at the current file
+ * Writes a big-endian 16-bit short to this file, starting at the current file
* pointer. Only the two least significant bytes of the integer {@code val}
- * are written, with the high byte first.
+ * are written.
*
* @param val
* the short to write to this file.
@@ -1015,7 +952,8 @@
* @see DataInput#readUnsignedShort()
*/
public final void writeShort(int val) throws IOException {
- writeChar(val);
+ OSMemory.pokeShort(scratch, 0, (short) val, ByteOrder.BIG_ENDIAN);
+ write(scratch, 0, SizeOf.SHORT);
}
/**
@@ -1032,37 +970,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/io/StringBufferInputStream.java b/luni/src/main/java/java/io/StringBufferInputStream.java
index 26482a2..f6acdf8 100644
--- a/luni/src/main/java/java/io/StringBufferInputStream.java
+++ b/luni/src/main/java/java/io/StringBufferInputStream.java
@@ -98,14 +98,6 @@
*/
@Override
public synchronized int read(byte[] buffer, int offset, int length) {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
- // According to 22.7.6 should return -1 before checking other
- // parameters.
- if (pos >= count) {
- return -1;
- }
if (buffer == null) {
throw new NullPointerException("buffer == null");
}
diff --git a/luni/src/main/java/java/lang/AbstractStringBuilder.java b/luni/src/main/java/java/lang/AbstractStringBuilder.java
index ebea88c..2aa0e86 100644
--- a/luni/src/main/java/java/lang/AbstractStringBuilder.java
+++ b/luni/src/main/java/java/lang/AbstractStringBuilder.java
@@ -279,8 +279,8 @@
*/
public void ensureCapacity(int min) {
if (min > value.length) {
- int twice = (value.length << 1) + 2;
- enlargeBuffer(twice > min ? twice : min);
+ int ourMin = value.length*2 + 2;
+ enlargeBuffer(Math.max(ourMin, min));
}
}
@@ -390,14 +390,13 @@
int newCount;
if (value.length - count >= size) {
if (!shared) {
- System.arraycopy(value, index, value, index + size, count
- - index); // index == count case is no-op
+ // index == count case is no-op
+ System.arraycopy(value, index, value, index + size, count - index);
return;
}
newCount = value.length;
} else {
- int a = count + size, b = (value.length << 1) + 2;
- newCount = a > b ? a : b;
+ newCount = Math.max(count + size, value.length*2 + 2);
}
char[] newData = new char[newCount];
diff --git a/luni/src/main/java/java/lang/Byte.java b/luni/src/main/java/java/lang/Byte.java
index 043a9f3..9c16fea 100644
--- a/luni/src/main/java/java/lang/Byte.java
+++ b/luni/src/main/java/java/lang/Byte.java
@@ -74,7 +74,7 @@
* @param string
* the string representation of a single byte value.
* @throws NumberFormatException
- * if {@code string} can not be decoded into a byte value.
+ * if {@code string} cannot be parsed as a byte value.
* @see #parseByte(String)
*/
public Byte(String string) throws NumberFormatException {
@@ -118,7 +118,7 @@
* a string representation of a single byte value.
* @return a {@code Byte} containing the value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} can not be parsed as a byte value.
+ * if {@code string} cannot be parsed as a byte value.
*/
public static Byte decode(String string) throws NumberFormatException {
int intValue = Integer.decode(string).intValue();
@@ -126,7 +126,7 @@
if (result == intValue) {
return valueOf(result);
}
- throw new NumberFormatException();
+ throw new NumberFormatException("Value out of range for byte: \"" + string + "\"");
}
@Override
@@ -178,16 +178,10 @@
* the string representation of a single byte value.
* @return the primitive byte value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a byte value.
+ * if {@code string} 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);
}
/**
@@ -201,19 +195,17 @@
* @return the primitive byte value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as a byte value.
+ * if {@code string} can not be parsed as a byte value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
*/
- 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
@@ -246,8 +238,7 @@
* @return a {@code Byte} instance containing the byte value represented by
* {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a byte value.
+ * if {@code string} can not be parsed as a byte value.
* @see #parseByte(String)
*/
public static Byte valueOf(String string) throws NumberFormatException {
@@ -265,14 +256,12 @@
* @return a {@code Byte} instance containing the byte value represented by
* {@code string} using {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as a byte value.
+ * if {@code string} can not be parsed as a byte value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
* @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/Class.java b/luni/src/main/java/java/lang/Class.java
index 0e4bd11..451da89 100644
--- a/luni/src/main/java/java/lang/Class.java
+++ b/luni/src/main/java/java/lang/Class.java
@@ -1077,7 +1077,7 @@
* defined in the source code. If there is no name (that is, the class is
* anonymous) then an empty string is returned. If the receiver is an array
* then the name of the underlying type with square braces appended (for
- * example {@code "Integer[]"}) is returned.
+ * example {@code "Integer[]"}) is returned.
*
* @return the simple name of the class represented by this {@code Class}.
*/
diff --git a/luni/src/main/java/java/lang/Double.java b/luni/src/main/java/java/lang/Double.java
index 644592b..0edc4d7 100644
--- a/luni/src/main/java/java/lang/Double.java
+++ b/luni/src/main/java/java/lang/Double.java
@@ -130,7 +130,7 @@
* @param string
* the string representation of a double value.
* @throws NumberFormatException
- * if {@code string} can not be decoded into a double value.
+ * if {@code string} cannot be parsed as a double value.
* @see #parseDouble(String)
*/
public Double(String string) throws NumberFormatException {
@@ -311,8 +311,7 @@
* the string representation of a double value.
* @return the primitive double value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a double value.
+ * if {@code string} cannot be parsed as a double value.
*/
public static double parseDouble(String string) throws NumberFormatException {
return org.apache.harmony.luni.util.FloatingPointParser.parseDouble(string);
@@ -348,8 +347,7 @@
* @return a {@code Double} instance containing the double value represented
* by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a double value.
+ * if {@code string} cannot be parsed as a double value.
* @see #parseDouble(String)
*/
public static Double valueOf(String string) throws NumberFormatException {
diff --git a/luni/src/main/java/java/lang/Float.java b/luni/src/main/java/java/lang/Float.java
index 446a346..e641eb6 100644
--- a/luni/src/main/java/java/lang/Float.java
+++ b/luni/src/main/java/java/lang/Float.java
@@ -136,7 +136,7 @@
* @param string
* the string representation of a float value.
* @throws NumberFormatException
- * if {@code string} can not be decoded into a float value.
+ * if {@code string} can not be parsed as a float value.
* @see #parseFloat(String)
*/
public Float(String string) throws NumberFormatException {
@@ -314,8 +314,7 @@
* the string representation of a float value.
* @return the primitive float value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a float value.
+ * if {@code string} can not be parsed as a float value.
* @see #valueOf(String)
* @since 1.2
*/
@@ -354,8 +353,7 @@
* @return a {@code Float} instance containing the float value represented
* by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a float value.
+ * if {@code string} can not be parsed as a float value.
* @see #parseFloat(String)
*/
public static Float valueOf(String string) throws NumberFormatException {
diff --git a/luni/src/main/java/java/lang/Integer.java b/luni/src/main/java/java/lang/Integer.java
index c8ac552..beddc89 100644
--- a/luni/src/main/java/java/lang/Integer.java
+++ b/luni/src/main/java/java/lang/Integer.java
@@ -98,7 +98,7 @@
* @param string
* the string representation of an integer value.
* @throws NumberFormatException
- * if {@code string} can not be decoded into an integer value.
+ * if {@code string} cannot be parsed as an integer value.
* @see #parseInt(String)
*/
public Integer(String string) throws NumberFormatException {
@@ -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
@@ -140,22 +144,18 @@
* @return an {@code Integer} containing the value represented by
* {@code string}.
* @throws NumberFormatException
- * if {@code string} can not be parsed as an integer value.
+ * if {@code string} cannot be parsed as an integer value.
*/
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;
}
@@ -325,8 +321,7 @@
* the string representation of an integer value.
* @return the primitive integer value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as an integer value.
+ * if {@code string} cannot be parsed as an integer value.
*/
public static int parseInt(String string) throws NumberFormatException {
return parseInt(string, 10);
@@ -343,65 +338,50 @@
* @return the primitive integer value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as an integer value.
+ * if {@code string} cannot be parsed as an integer value,
+ * or {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
*/
- 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;
@@ -498,8 +478,7 @@
* @return an {@code Integer} instance containing the integer value
* represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as an integer value.
+ * if {@code string} cannot be parsed as an integer value.
* @see #parseInt(String)
*/
public static Integer valueOf(String string) throws NumberFormatException {
@@ -517,14 +496,12 @@
* @return an {@code Integer} instance containing the integer value
* represented by {@code string} using {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as an integer value.
+ * if {@code string} cannot be parsed as an integer value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
* @see #parseInt(String, int)
*/
- public static Integer valueOf(String string, int radix)
- throws NumberFormatException {
+ public static Integer valueOf(String string, int radix) throws NumberFormatException {
return valueOf(parseInt(string, radix));
}
diff --git a/luni/src/main/java/java/lang/Long.java b/luni/src/main/java/java/lang/Long.java
index 7b7e5f3..fec3352 100644
--- a/luni/src/main/java/java/lang/Long.java
+++ b/luni/src/main/java/java/lang/Long.java
@@ -85,7 +85,7 @@
* @param string
* the string representation of a long value.
* @throws NumberFormatException
- * if {@code string} can not be decoded into a long value.
+ * if {@code string} cannot be parsed as a long value.
* @see #parseLong(String)
*/
public Long(String string) throws NumberFormatException {
@@ -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
@@ -126,18 +130,18 @@
* a string representation of a long value.
* @return a {@code Long} containing the value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} can not be parsed as a long value.
+ * if {@code string} cannot be parsed as a long value.
*/
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;
@@ -304,8 +308,7 @@
* the string representation of a long value.
* @return the primitive long value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a long value.
+ * if {@code string} cannot be parsed as a long value.
*/
public static long parseLong(String string) throws NumberFormatException {
return parseLong(string, 10);
@@ -322,23 +325,24 @@
* @return the primitive long value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as a long value.
+ * if {@code string} cannot be parsed as a long value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
*/
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 +354,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;
@@ -461,8 +465,7 @@
* @return a {@code Long} instance containing the long value represented by
* {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a long value.
+ * if {@code string} cannot be parsed as a long value.
* @see #parseLong(String)
*/
public static Long valueOf(String string) throws NumberFormatException {
@@ -480,10 +483,9 @@
* @return a {@code Long} instance containing the long value represented by
* {@code string} using {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as a long value.
+ * if {@code string} cannot be parsed as a long value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
* @see #parseLong(String, int)
*/
public static Long valueOf(String string, int radix) throws NumberFormatException {
diff --git a/luni/src/main/java/java/lang/Process.java b/luni/src/main/java/java/lang/Process.java
index 5081f0f..13c4ed9 100644
--- a/luni/src/main/java/java/lang/Process.java
+++ b/luni/src/main/java/java/lang/Process.java
@@ -22,17 +22,47 @@
/**
* Represents an external process. Enables writing to, reading from, destroying,
- * and waiting for the external process, as well as querying its exit value.
+ * and waiting for the external process, as well as querying its exit value. Use
+ * {@link ProcessBuilder} to create processes.
*
- * @see Runtime#exec
- * @see ProcessBuilder#start()
+ * <p>The child process writes its output to two streams, {@code out} and
+ * {@code err}. These streams should be read by the parent process using {@link
+ * #getInputStream()} and {@link #getErrorStream()} respectively. If these
+ * streams are not read, the target process may block while it awaits buffer
+ * space. It isn't sufficient to read the streams in sequence; to avoid blocking
+ * each of the two streams must have its own reader thread. If you are not
+ * interested in differentiating the out and err streams, use {@link
+ * ProcessBuilder#redirectErrorStream(boolean) redirectErrorStream(true)} to
+ * merge the two streams. This simplifies your reading code and makes it easier
+ * to avoid blocking the target process.
+ *
+ * <p>Running processes hold resources. When a process is no longer used, the
+ * process should be closed by calling {@link #destroy}. This will kill the
+ * process and release the resources that it holds.
+ *
+ * <p>For example, to run {@code /system/bin/ping} to ping {@code android.com}:
+ * <pre> {@code
+ * Process process = new ProcessBuilder()
+ * .command("/system/bin/ping", "android.com")
+ * .redirectErrorStream(true)
+ * .start();
+ * try {
+ * InputStream in = process.getInputStream();
+ * OutputStream out = process.getOutputStream();
+ *
+ * readStream(in);
+ *
+ * } finally {
+ * process.destroy();
+ * }
+ * }</pre>
*/
public abstract class Process {
/**
* Terminates this process and closes any associated streams.
*/
- abstract public void destroy();
+ public abstract void destroy();
/**
* Returns the exit value of the native process represented by this object.
@@ -42,7 +72,7 @@
* @throws IllegalThreadStateException
* if this process has not terminated.
*/
- abstract public int exitValue();
+ public abstract int exitValue();
/**
* Returns an input stream that is connected to the error stream
@@ -51,7 +81,7 @@
* @return the input stream to read from the error stream associated with
* the native process.
*/
- abstract public InputStream getErrorStream();
+ public abstract InputStream getErrorStream();
/**
* Returns an input stream that is connected to the standard output stream
@@ -60,7 +90,7 @@
* @return the input stream to read from the output stream associated with
* the native process.
*/
- abstract public InputStream getInputStream();
+ public abstract InputStream getInputStream();
/**
* Returns an output stream that is connected to the standard input stream
@@ -69,7 +99,7 @@
* @return the output stream to write to the input stream associated with
* the native process.
*/
- abstract public OutputStream getOutputStream();
+ public abstract OutputStream getOutputStream();
/**
* Causes the calling thread to wait for the native process associated with
@@ -79,5 +109,5 @@
* @throws InterruptedException
* if the calling thread is interrupted.
*/
- abstract public int waitFor() throws InterruptedException;
+ public abstract int waitFor() throws InterruptedException;
}
diff --git a/luni/src/main/java/java/lang/ProcessBuilder.java b/luni/src/main/java/java/lang/ProcessBuilder.java
index 504b79c..5aadade 100644
--- a/luni/src/main/java/java/lang/ProcessBuilder.java
+++ b/luni/src/main/java/java/lang/ProcessBuilder.java
@@ -24,18 +24,14 @@
import java.util.Map;
/**
- * Creates operating system processes.
- *
- * @since 1.5
+ * Creates operating system processes. See {@link Process} for documentation and
+ * example usage.
*/
public final class ProcessBuilder {
private List<String> command;
-
private File directory;
-
private Map<String, String> environment;
-
private boolean redirectErrorStream;
/**
diff --git a/luni/src/main/java/java/lang/ProcessManager.java b/luni/src/main/java/java/lang/ProcessManager.java
index f54640a..2c740a2 100644
--- a/luni/src/main/java/java/lang/ProcessManager.java
+++ b/luni/src/main/java/java/lang/ProcessManager.java
@@ -273,9 +273,12 @@
try {
kill(this.id);
} catch (IOException e) {
- Logger.getLogger(Runtime.class.getName()).log(Level.FINE,
+ Logger.getLogger(Process.class.getName()).log(Level.FINE,
"Failed to destroy process " + id + ".", e);
}
+ IoUtils.closeQuietly(inputStream);
+ IoUtils.closeQuietly(errorStream);
+ IoUtils.closeQuietly(outputStream);
}
public int exitValue() {
diff --git a/luni/src/main/java/java/lang/RealToString.java b/luni/src/main/java/java/lang/RealToString.java
index 9f7c85a..0212cbb 100644
--- a/luni/src/main/java/java/lang/RealToString.java
+++ b/luni/src/main/java/java/lang/RealToString.java
@@ -20,6 +20,12 @@
import libcore.math.MathUtils;
final class RealToString {
+ private static final ThreadLocal<RealToString> INSTANCE = new ThreadLocal<RealToString>() {
+ @Override protected RealToString initialValue() {
+ return new RealToString();
+ }
+ };
+
private final static double invLogOfTenBaseTwo = Math.log(2.0) / Math.log(10.0);
private int firstK;
@@ -34,12 +40,6 @@
*/
private int digitCount;
- private static final ThreadLocal<RealToString> INSTANCE = new ThreadLocal<RealToString>() {
- @Override protected RealToString initialValue() {
- return new RealToString();
- }
- };
-
private RealToString() {
}
diff --git a/luni/src/main/java/java/lang/Runtime.java b/luni/src/main/java/java/lang/Runtime.java
index 835c109..10c7eea 100644
--- a/luni/src/main/java/java/lang/Runtime.java
+++ b/luni/src/main/java/java/lang/Runtime.java
@@ -551,7 +551,10 @@
@Deprecated
public InputStream getLocalizedInputStream(InputStream stream) {
String encoding = System.getProperty("file.encoding", "UTF-8");
- return encoding.equals("UTF-8") ? stream : new ReaderInputStream(stream, encoding);
+ if (!encoding.equals("UTF-8")) {
+ throw new UnsupportedOperationException("Cannot localize " + encoding);
+ }
+ return stream;
}
/**
@@ -568,7 +571,10 @@
@Deprecated
public OutputStream getLocalizedOutputStream(OutputStream stream) {
String encoding = System.getProperty("file.encoding", "UTF-8");
- return encoding.equals("UTF-8") ? stream : new WriterOutputStream(stream, encoding);
+ if (!encoding.equals("UTF-8")) {
+ throw new UnsupportedOperationException("Cannot localize " + encoding);
+ }
+ return stream;
}
/**
@@ -712,124 +718,4 @@
*/
public native long maxMemory();
-}
-
-/*
- * Internal helper class for creating a localized InputStream. A reader
- * wrapped in an InputStream.
- */
-class ReaderInputStream extends InputStream {
-
- private Reader reader;
-
- private Writer writer;
-
- ByteArrayOutputStream out = new ByteArrayOutputStream(256);
-
- private byte[] bytes;
-
- private int nextByte;
-
- private int numBytes;
-
- public ReaderInputStream(InputStream stream, String encoding) {
- try {
- reader = new InputStreamReader(stream, Charsets.UTF_8);
- writer = new OutputStreamWriter(out, encoding);
- } catch (UnsupportedEncodingException e) {
- // Should never happen, since UTF-8 and platform encoding must be
- // supported.
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public int read() throws IOException {
- if (nextByte >= numBytes) {
- readBuffer();
- }
-
- return (numBytes < 0) ? -1 : bytes[nextByte++];
- }
-
- private void readBuffer() throws IOException {
- char[] chars = new char[128];
- int read = reader.read(chars);
- if (read < 0) {
- numBytes = read;
- return;
- }
-
- writer.write(chars, 0, read);
- writer.flush();
- bytes = out.toByteArray();
- numBytes = bytes.length;
- nextByte = 0;
- }
-
-}
-
-/*
- * Internal helper class for creating a localized OutputStream. A writer
- * wrapped in an OutputStream. Bytes are written to characters in big-endian
- * fashion.
- */
-class WriterOutputStream extends OutputStream {
-
- private Reader reader;
-
- private Writer writer;
-
- private PipedOutputStream out;
-
- private PipedInputStream pipe;
-
- private int numBytes;
-
- public WriterOutputStream(OutputStream stream, String encoding) {
- try {
- // sink
- this.writer = new OutputStreamWriter(stream, encoding);
-
- // transcriber
- out = new PipedOutputStream();
- pipe = new PipedInputStream(out);
- this.reader = new InputStreamReader(pipe, Charsets.UTF_8);
-
- } catch (UnsupportedEncodingException e) {
- // Should never happen, since platform encoding must be supported.
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void write(int b) throws IOException {
- out.write(b);
- if( ++numBytes > 256) {
- flush();
- numBytes = 0;
- }
- }
-
- @Override
- public void flush() throws IOException {
- out.flush();
- char[] chars = new char[128];
- if (pipe.available() > 0) {
- int read = reader.read(chars);
- if (read > 0) {
- writer.write(chars, 0, read);
- }
- }
- writer.flush();
- }
-
- @Override
- public void close() throws IOException {
- out.close();
- flush();
- writer.close();
- }
-}
+}
\ No newline at end of file
diff --git a/luni/src/main/java/java/lang/Short.java b/luni/src/main/java/java/lang/Short.java
index fd7bca0..2900d6f 100644
--- a/luni/src/main/java/java/lang/Short.java
+++ b/luni/src/main/java/java/lang/Short.java
@@ -66,7 +66,7 @@
* @param string
* the string representation of a short value.
* @throws NumberFormatException
- * if {@code string} can not be decoded into a short value.
+ * if {@code string} cannot be parsed as a short value.
* @see #parseShort(String)
*/
public Short(String string) throws NumberFormatException {
@@ -118,7 +118,7 @@
* @return a {@code Short} containing the value represented by
* {@code string}.
* @throws NumberFormatException
- * if {@code string} can not be parsed as a short value.
+ * if {@code string} cannot be parsed as a short value.
*/
public static Short decode(String string) throws NumberFormatException {
int intValue = Integer.decode(string).intValue();
@@ -126,7 +126,7 @@
if (result == intValue) {
return valueOf(result);
}
- throw new NumberFormatException();
+ throw new NumberFormatException("Value out of range for short: \"" + string + "\"");
}
@Override
@@ -178,8 +178,7 @@
* the string representation of a short value.
* @return the primitive short value represented by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a short value.
+ * if {@code string} cannot be parsed as a short value.
*/
public static short parseShort(String string) throws NumberFormatException {
return parseShort(string, 10);
@@ -196,19 +195,17 @@
* @return the primitive short value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as a short value.
+ * if {@code string} cannot be parsed as a short value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
*/
- 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 + "\"");
}
/**
@@ -246,8 +243,7 @@
* @return a {@code Short} instance containing the short value represented
* by {@code string}.
* @throws NumberFormatException
- * if {@code string} is {@code null}, has a length of zero or
- * can not be parsed as a short value.
+ * if {@code string} cannot be parsed as a short value.
* @see #parseShort(String)
*/
public static Short valueOf(String string) throws NumberFormatException {
@@ -265,14 +261,12 @@
* @return a {@code Short} instance containing the short value represented
* by {@code string} using {@code radix}.
* @throws NumberFormatException
- * if {@code string} is {@code null} or has a length of zero,
- * {@code radix < Character.MIN_RADIX},
- * {@code radix > Character.MAX_RADIX}, or if {@code string}
- * can not be parsed as a short value.
+ * if {@code string} cannot be parsed as a short value, or
+ * {@code radix < Character.MIN_RADIX ||
+ * radix > Character.MAX_RADIX}.
* @see #parseShort(String, int)
*/
- public static Short valueOf(String string, int radix)
- throws NumberFormatException {
+ public static Short valueOf(String string, int radix) throws NumberFormatException {
return valueOf(parseShort(string, radix));
}
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/lang/ThreadGroup.java b/luni/src/main/java/java/lang/ThreadGroup.java
index ca31d36..93e4a6d 100644
--- a/luni/src/main/java/java/lang/ThreadGroup.java
+++ b/luni/src/main/java/java/lang/ThreadGroup.java
@@ -17,6 +17,12 @@
package java.lang;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import libcore.base.CollectionUtils;
+
/**
* {@code ThreadGroup} is a means of organizing threads into a hierarchical structure.
* This class is obsolete. See <i>Effective Java</i> Item 73, "Avoid thread groups" for details.
@@ -26,38 +32,32 @@
public class ThreadGroup implements Thread.UncaughtExceptionHandler {
// Name of this ThreadGroup
- private String name;
- // BEGIN android-note
// VM needs this field name for debugging.
- // END android-note
+ private String name;
// Maximum priority for Threads inside this ThreadGroup
private int maxPriority = Thread.MAX_PRIORITY;
// The ThreadGroup to which this ThreadGroup belongs
- ThreadGroup parent;
- // BEGIN android-note
// VM needs this field name for debugging.
- // END android-note
+ final ThreadGroup parent;
- int numThreads;
+ /**
+ * Weak references to the threads in this group.
+ * Access is guarded by synchronizing on this field.
+ */
+ private final List<WeakReference<Thread>> threadRefs = new ArrayList<WeakReference<Thread>>(5);
- // The Threads this ThreadGroup contains
- private Thread[] childrenThreads = new Thread[5];
+ /**
+ * View of the threads.
+ * Access is guarded by synchronizing on threadRefs.
+ */
+ private final Iterable<Thread> threads = CollectionUtils.dereferenceIterable(threadRefs, true);
- // The number of children groups
- int numGroups;
-
- // The ThreadGroups this ThreadGroup contains
- private ThreadGroup[] childrenGroups = new ThreadGroup[3];
-
- // Locked when using the childrenGroups field
- private class ChildrenGroupsLock {}
- private Object childrenGroupsLock = new ChildrenGroupsLock();
-
- // Locked when using the childrenThreads field
- private class ChildrenThreadsLock {}
- private Object childrenThreadsLock = new ChildrenThreadsLock();
+ /**
+ * Thread groups. Access is guarded by synchronizing on this field.
+ */
+ private final List<ThreadGroup> groups = new ArrayList<ThreadGroup>(3);
// Whether this ThreadGroup is a daemon ThreadGroup or not
private boolean isDaemon;
@@ -65,21 +65,9 @@
// Whether this ThreadGroup has already been destroyed or not
private boolean isDestroyed;
- // BEGIN android-added
/* the VM uses these directly; do not rename */
- static ThreadGroup mSystem = new ThreadGroup();
- static ThreadGroup mMain = new ThreadGroup(mSystem, "main");
- // END android-added
-
- // BEGIN android-removed
- // /**
- // * Used by the JVM to create the "system" ThreadGroup. Construct a
- // * ThreadGroup instance, and assign the name "system".
- // */
- // private ThreadGroup() {
- // name = "system";
- // }
- // END android-removed
+ static final ThreadGroup mSystem = new ThreadGroup();
+ static final ThreadGroup mMain = new ThreadGroup(mSystem, "main");
/**
* Constructs a new {@code ThreadGroup} with the given name. The new {@code ThreadGroup}
@@ -88,7 +76,7 @@
* @param name the name
* @throws SecurityException if {@code checkAccess()} for the parent
* group fails with a SecurityException
- * @see java.lang.Thread#currentThread
+ * @see Thread#currentThread
*/
public ThreadGroup(String name) {
@@ -108,7 +96,6 @@
* destroyed already
*/
public ThreadGroup(ThreadGroup parent, String name) {
- super();
if (Thread.currentThread() != null) {
// If parent is null we must throw NullPointerException, but that
// will be done "for free" with the message send below
@@ -116,8 +103,9 @@
}
this.name = name;
- this.setParent(parent);
+ this.parent = parent;
if (parent != null) {
+ parent.add(this);
this.setMaxPriority(parent.getMaxPriority());
if (parent.isDaemon()) {
this.setDaemon(true);
@@ -129,9 +117,9 @@
* Initialize the special "system" ThreadGroup. Was "main" in Harmony,
* but we have an additional group above that in Android.
*/
- ThreadGroup() {
+ private ThreadGroup() {
this.name = "system";
- this.setParent(null);
+ this.parent = null;
}
/**
@@ -141,21 +129,17 @@
* @return the number of children
*/
public int activeCount() {
- // BEGIN android-changed
int count = 0;
- // Lock the children thread list
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- if(childrenThreads[i].isAlive()) {
+ synchronized (threadRefs) {
+ for (Thread thread : threads) {
+ if (thread.isAlive()) {
count++;
}
}
}
- // END android-changed
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- count += this.childrenGroups[i].activeCount();
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ count += group.activeCount();
}
}
return count;
@@ -169,39 +153,30 @@
*/
public int activeGroupCount() {
int count = 0;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
// One for this group & the subgroups
- count += 1 + this.childrenGroups[i].activeGroupCount();
+ count += 1 + group.activeGroupCount();
}
}
return count;
}
/**
- * Adds a {@code Thread} to this thread group. This should only be visible to class
- * java.lang.Thread, and should only be called when a new Thread is created
+ * Adds a {@code Thread} to this thread group. This should only be visible
+ * to class Thread, and should only be called when a new Thread is created
* and initialized by the constructor.
*
* @param thread Thread to add
* @throws IllegalThreadStateException if this group has been destroyed already
- * @see #remove(java.lang.Thread)
+ * @see #remove(Thread)
*/
final void add(Thread thread) throws IllegalThreadStateException {
- synchronized (this.childrenThreadsLock) {
- if (!isDestroyed) {
- if (childrenThreads.length == numThreads) {
- Thread[] newThreads = new Thread[childrenThreads.length * 2];
- System.arraycopy(childrenThreads, 0, newThreads, 0, numThreads);
- newThreads[numThreads++] = thread;
- childrenThreads = newThreads;
- } else {
- childrenThreads[numThreads++] = thread;
- }
- } else {
+ synchronized (threadRefs) {
+ if (isDestroyed) {
throw new IllegalThreadStateException();
}
+ threadRefs.add(new WeakReference<Thread>(thread));
}
}
@@ -212,19 +187,11 @@
* @throws IllegalThreadStateException if this group has been destroyed already
*/
private void add(ThreadGroup g) throws IllegalThreadStateException {
- synchronized (this.childrenGroupsLock) {
- if (!isDestroyed) {
- if (childrenGroups.length == numGroups) {
- ThreadGroup[] newGroups = new ThreadGroup[childrenGroups.length * 2];
- System.arraycopy(childrenGroups, 0, newGroups, 0, numGroups);
- newGroups[numGroups++] = g;
- childrenGroups = newGroups;
- } else {
- childrenGroups[numGroups++] = g;
- }
- } else {
+ synchronized (groups) {
+ if (isDestroyed) {
throw new IllegalThreadStateException();
}
+ groups.add(g);
}
}
@@ -272,36 +239,31 @@
public final void destroy() {
checkAccess();
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- synchronized (this.childrenGroupsLock) {
- // BEGIN android-added
- if (this.isDestroyed) {
+ synchronized (threadRefs) {
+ synchronized (groups) {
+ if (isDestroyed) {
throw new IllegalThreadStateException(
"Thread group was already destroyed: "
+ (this.name != null ? this.name : "n/a"));
}
- if (this.numThreads > 0) {
+ if (threads.iterator().hasNext()) {
throw new IllegalThreadStateException(
"Thread group still contains threads: "
+ (this.name != null ? this.name : "n/a"));
}
- // END android-added
- int toDestroy = numGroups;
// Call recursively for subgroups
- for (int i = 0; i < toDestroy; i++) {
+ while (!groups.isEmpty()) {
// We always get the first element - remember, when the
// child dies it removes itself from our collection. See
// below.
- this.childrenGroups[0].destroy();
+ groups.get(0).destroy();
}
if (parent != null) {
parent.remove(this);
}
- // Now that the ThreadGroup is really destroyed it can be tagged
- // as so
+ // Now that the ThreadGroup is really destroyed it can be tagged as so
this.isDestroyed = true;
}
}
@@ -317,10 +279,10 @@
*/
private void destroyIfEmptyDaemon() {
// Has to be non-destroyed daemon to make sense
- synchronized (this.childrenThreadsLock) {
- if (isDaemon && !isDestroyed && numThreads == 0) {
- synchronized (this.childrenGroupsLock) {
- if (numGroups == 0) {
+ synchronized (threadRefs) {
+ if (isDaemon && !isDestroyed && !threads.iterator().hasNext()) {
+ synchronized (groups) {
+ if (groups.isEmpty()) {
destroy();
}
}
@@ -413,28 +375,37 @@
boolean enumeratingThreads) {
checkAccess();
- Object[] immediateCollection = enumeratingThreads ? (Object[]) childrenThreads
- : (Object[]) childrenGroups;
- Object syncLock = enumeratingThreads ? childrenThreadsLock : childrenGroupsLock;
-
- synchronized (syncLock) { // Lock this subpart of the tree as we walk
- for (int i = enumeratingThreads ? numThreads : numGroups; --i >= 0;) {
- if (!enumeratingThreads || ((Thread) immediateCollection[i]).isAlive()) {
+ if (enumeratingThreads) {
+ synchronized (threadRefs) {
+ // walk the references directly so we can iterate in reverse order
+ for (int i = threadRefs.size() - 1; i >= 0; --i) {
+ Thread thread = threadRefs.get(i).get();
+ if (thread != null && thread.isAlive()) {
+ if (enumerationIndex >= enumeration.length) {
+ return enumerationIndex;
+ }
+ enumeration[enumerationIndex++] = thread;
+ }
+ }
+ }
+ } else {
+ synchronized (groups) {
+ for (int i = groups.size() - 1; i >= 0; --i) {
if (enumerationIndex >= enumeration.length) {
return enumerationIndex;
}
- enumeration[enumerationIndex++] = immediateCollection[i];
+ enumeration[enumerationIndex++] = groups.get(i);
}
}
}
- if (recurse) { // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
+ if (recurse) {
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
if (enumerationIndex >= enumeration.length) {
return enumerationIndex;
}
- enumerationIndex = childrenGroups[i].enumerateGeneric(enumeration, recurse,
+ enumerationIndex = group.enumerateGeneric(enumeration, recurse,
enumerationIndex, enumeratingThreads);
}
}
@@ -486,16 +457,14 @@
*/
public final void interrupt() {
checkAccess();
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- this.childrenThreads[i].interrupt();
+ synchronized (threadRefs) {
+ for (Thread thread : threads) {
+ thread.interrupt();
}
}
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].interrupt();
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ group.interrupt();
}
}
}
@@ -543,30 +512,29 @@
* be output.
*/
private void list(int levels) {
- for (int i = 0; i < levels; i++) {
- System.out.print(" "); // 4 spaces for each level
- }
-
- // Print the receiver
+ indent(levels);
System.out.println(this.toString());
- // Print the children threads, with 1 extra indentation
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- // children get an extra indentation, 4 spaces for each level
- for (int j = 0; j <= levels; j++) {
- System.out.print(" ");
- }
- System.out.println(this.childrenThreads[i]);
+ ++levels;
+ synchronized (threadRefs) {
+ for (Thread thread : threads) {
+ indent(levels);
+ System.out.println(thread);
}
}
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].list(levels + 1);
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ group.list(levels);
}
}
}
+ private void indent(int levels) {
+ for (int i = 0; i < levels; i++) {
+ System.out.print(" "); // 4 spaces for each level
+ }
+ }
+
/**
* Checks whether this thread group is a direct or indirect parent group of a
* given {@code ThreadGroup}.
@@ -586,21 +554,17 @@
/**
* Removes a {@code Thread} from this group. This should only be visible to class
- * java.lang.Thread, and should only be called when a Thread dies.
+ * Thread, and should only be called when a Thread dies.
*
* @param thread Thread to remove
*
* @see #add(Thread)
*/
- final void remove(java.lang.Thread thread) {
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- if (childrenThreads[i].equals(thread)) {
- numThreads--;
- System
- .arraycopy(childrenThreads, i + 1, childrenThreads, i, numThreads
- - i);
- childrenThreads[numThreads] = null;
+ final void remove(Thread thread) {
+ synchronized (threadRefs) {
+ for (Iterator<Thread> i = threads.iterator(); i.hasNext(); ) {
+ if (i.next().equals(thread)) {
+ i.remove();
break;
}
}
@@ -617,12 +581,11 @@
* @see #add(ThreadGroup)
*/
private void remove(ThreadGroup g) {
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- if (childrenGroups[i].equals(g)) {
- numGroups--;
- System.arraycopy(childrenGroups, i + 1, childrenGroups, i, numGroups - i);
- childrenGroups[numGroups] = null;
+ synchronized (groups) {
+ for (Iterator<ThreadGroup> i = groups.iterator(); i.hasNext(); ) {
+ ThreadGroup threadGroup = i.next();
+ if (threadGroup.equals(g)) {
+ i.remove();
break;
}
}
@@ -646,16 +609,14 @@
@Deprecated
public final void resume() {
checkAccess();
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- this.childrenThreads[i].resume();
+ synchronized (threadRefs) {
+ for (Thread thread : threads) {
+ thread.resume();
}
}
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].resume();
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ group.resume();
}
}
}
@@ -703,35 +664,15 @@
int parentPriority = parent == null ? newMax : parent.getMaxPriority();
this.maxPriority = parentPriority <= newMax ? parentPriority : newMax;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- // ??? why not maxPriority
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].setMaxPriority(newMax);
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ group.setMaxPriority(newMax);
}
}
}
}
/**
- * Sets the parent {@code ThreadGroup} of this thread group, and adds this
- * thread group to the parent's collection of immediate children (if {@code parent} is
- * not {@code null}).
- *
- * @param parent The parent ThreadGroup, or null to make this thread group
- * the root ThreadGroup
- *
- * @see #getParent
- * @see #parentOf
- */
- private void setParent(ThreadGroup parent) {
- if (parent != null) {
- parent.add(this);
- }
- this.parent = parent;
- }
-
- /**
* Stops every thread in this group and recursively in all its subgroups.
*
* @throws SecurityException if {@code this.checkAccess()} fails with
@@ -751,30 +692,24 @@
}
}
- /**
- * @deprecated Requires deprecated method Thread.suspend().
- */
@SuppressWarnings("deprecation")
- @Deprecated
- private final boolean stopHelper() {
+ private boolean stopHelper() {
checkAccess();
boolean stopCurrent = false;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
+ synchronized (threadRefs) {
Thread current = Thread.currentThread();
- for (int i = 0; i < numThreads; i++) {
- if (this.childrenThreads[i] == current) {
+ for (Thread thread : threads) {
+ if (thread == current) {
stopCurrent = true;
} else {
- this.childrenThreads[i].stop();
+ thread.stop();
}
}
}
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- stopCurrent |= this.childrenGroups[i].stopHelper();
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ stopCurrent |= group.stopHelper();
}
}
return stopCurrent;
@@ -800,30 +735,24 @@
}
}
- /**
- * @deprecated Requires deprecated method Thread.suspend().
- */
@SuppressWarnings("deprecation")
- @Deprecated
- private final boolean suspendHelper() {
+ private boolean suspendHelper() {
checkAccess();
boolean suspendCurrent = false;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
+ synchronized (threadRefs) {
Thread current = Thread.currentThread();
- for (int i = 0; i < numThreads; i++) {
- if (this.childrenThreads[i] == current) {
+ for (Thread thread : threads) {
+ if (thread == current) {
suspendCurrent = true;
} else {
- this.childrenThreads[i].suspend();
+ thread.suspend();
}
}
}
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- suspendCurrent |= this.childrenGroups[i].suspendHelper();
+ synchronized (groups) {
+ for (ThreadGroup group : groups) {
+ suspendCurrent |= group.suspendHelper();
}
}
return suspendCurrent;
@@ -831,8 +760,8 @@
@Override
public String toString() {
- return getClass().getName() + "[name=" + this.getName() + ",maxPriority="
- + this.getMaxPriority() + "]";
+ return getClass().getName() + "[name=" + getName()
+ + ",maxPriority=" + getMaxPriority() + "]";
}
/**
@@ -846,7 +775,6 @@
* @param e the uncaught exception itself
*/
public void uncaughtException(Thread t, Throwable e) {
- // BEGIN android-changed
if (parent != null) {
parent.uncaughtException(t, e);
} else if (Thread.getDefaultUncaughtExceptionHandler() != null) {
@@ -856,10 +784,8 @@
// No parent group, has to be 'system' Thread Group
e.printStackTrace(System.err);
}
- // END android-changed
}
- // BEGIN android-added
/**
* Non-standard method for adding a thread to a group, required by Dalvik.
*
@@ -868,8 +794,8 @@
* @throws IllegalThreadStateException if the thread has been destroyed
* already
*
- * @see #add(java.lang.Thread)
- * @see #removeThread(java.lang.Thread)
+ * @see #add(Thread)
+ * @see #removeThread(Thread)
*/
void addThread(Thread thread) throws IllegalThreadStateException {
add(thread);
@@ -883,11 +809,10 @@
* @throws IllegalThreadStateException if the thread has been destroyed
* already
*
- * @see #remove(java.lang.Thread)
- * @see #addThread(java.lang.Thread)
+ * @see #remove(Thread)
+ * @see #addThread(Thread)
*/
void removeThread(Thread thread) throws IllegalThreadStateException {
remove(thread);
}
- // END android-added
}
diff --git a/luni/src/main/java/java/lang/ThreadLocal.java b/luni/src/main/java/java/lang/ThreadLocal.java
index 61e83b0..f3c07f2 100644
--- a/luni/src/main/java/java/lang/ThreadLocal.java
+++ b/luni/src/main/java/java/lang/ThreadLocal.java
@@ -142,7 +142,7 @@
* We increment by Doug Lea's Magic Number(TM) (*2 since keys are in
* every other bucket) to help prevent clustering.
*/
- private final int hash = hashCounter.getAndAdd(0x61c88647 << 1);
+ private final int hash = hashCounter.getAndAdd(0x61c88647 * 2);
/**
* Per-thread map of ThreadLocal instances to values.
@@ -247,7 +247,7 @@
* Creates a new, empty table with the given capacity.
*/
private void initializeTable(int capacity) {
- this.table = new Object[capacity << 1];
+ this.table = new Object[capacity * 2];
this.mask = table.length - 1;
this.clean = 0;
this.maximumLoad = capacity * 2 / 3; // 2/3
@@ -322,7 +322,7 @@
if (size > (capacity >> 1)) {
// More than 1/2 filled w/ live entries.
// Double size.
- newCapacity = capacity << 1;
+ newCapacity = capacity * 2;
}
Object[] oldTable = this.table;
diff --git a/luni/src/main/java/java/lang/reflect/ParameterizedType.java b/luni/src/main/java/java/lang/reflect/ParameterizedType.java
index e98827b..59b6e35 100644
--- a/luni/src/main/java/java/lang/reflect/ParameterizedType.java
+++ b/luni/src/main/java/java/lang/reflect/ParameterizedType.java
@@ -68,7 +68,7 @@
/**
* Returns the declaring type of this parameterized type.
* <p>
- * The raw type of {@code Set<String> field;} is {@code Set}.
+ * The raw type of {@code Set<String> field;} is {@code Set}.
*
* @return the raw type of this parameterized type
*/
diff --git a/luni/src/main/java/java/lang/reflect/TypeVariable.java b/luni/src/main/java/java/lang/reflect/TypeVariable.java
index 0ba57fb..6ab63db 100644
--- a/luni/src/main/java/java/lang/reflect/TypeVariable.java
+++ b/luni/src/main/java/java/lang/reflect/TypeVariable.java
@@ -18,9 +18,9 @@
/**
* This interface represents a type variables such as {@code 'T'} in {@code
- * 'public interface Comparable<T>'}, the bounded {@code 'T'} in {@code
- * 'public interface A<T extends Number>'} or the multiple bounded {@code
- * 'T'} in {@code 'public interface B<T extends Number & Cloneable>'}.
+ * 'public interface Comparable<T>'}, the bounded {@code 'T'} in {@code
+ * 'public interface A<T extends Number>'} or the multiple bounded {@code
+ * 'T'} in {@code 'public interface B<T extends Number & Cloneable>'}.
*
* @param <D>
* the generic declaration that declares this type variable
diff --git a/luni/src/main/java/java/math/BigDecimal.java b/luni/src/main/java/java/math/BigDecimal.java
index f419897..5e2e220 100644
--- a/luni/src/main/java/java/math/BigDecimal.java
+++ b/luni/src/main/java/java/math/BigDecimal.java
@@ -269,14 +269,10 @@
* first index to be copied.
* @param len
* number of characters to be used.
- * @throws NullPointerException
- * if {@code in == null}.
* @throws NumberFormatException
- * if {@code offset < 0} or {@code len <= 0} or {@code
- * offset+len-1 < 0} or {@code offset+len-1 >= in.length}.
- * @throws NumberFormatException
- * if in does not contain a valid string representation of a big
- * decimal.
+ * if {@code offset < 0 || len <= 0 || offset+len-1 < 0 ||
+ * offset+len-1 >= in.length}, or if {@code in} does not
+ * contain a valid string representation of a big decimal.
*/
public BigDecimal(char[] in, int offset, int len) {
int begin = offset; // first index to be copied
@@ -289,7 +285,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 +298,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++;
@@ -381,14 +377,10 @@
* number of characters to be used.
* @param mc
* rounding mode and precision for the result of this operation.
- * @throws NullPointerException
- * if {@code in == null}.
* @throws NumberFormatException
- * if {@code offset < 0} or {@code len <= 0} or {@code
- * offset+len-1 < 0} or {@code offset+len-1 >= in.length}.
- * @throws NumberFormatException
- * if {@code in} does not contain a valid string representation
- * of a big decimal.
+ * if {@code offset < 0 || len <= 0 || offset+len-1 < 0 ||
+ * offset+len-1 >= in.length}, or if {@code in} does not
+ * contain a valid string representation of a big decimal.
* @throws ArithmeticException
* if {@code mc.precision > 0} and {@code mc.roundingMode ==
* UNNECESSARY} and the new big decimal cannot be represented
@@ -406,8 +398,6 @@
* @param in
* array of characters containing the string representation of
* this {@code BigDecimal}.
- * @throws NullPointerException
- * if {@code in == null}.
* @throws NumberFormatException
* if {@code in} does not contain a valid string representation
* of a big decimal.
@@ -426,8 +416,6 @@
* this {@code BigDecimal}.
* @param mc
* rounding mode and precision for the result of this operation.
- * @throws NullPointerException
- * if {@code in == null}.
* @throws NumberFormatException
* if {@code in} does not contain a valid string representation
* of a big decimal.
@@ -496,7 +484,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 +762,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));
}
@@ -1137,10 +1125,10 @@
}
int sign = scaledDividend.signum() * scaledDivisor.signum();
int compRem; // 'compare to remainder'
- if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after <<1
+ if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after *2
long rem = remainder.longValue();
long divisor = scaledDivisor.longValue();
- compRem = longCompareTo(Math.abs(rem) << 1,Math.abs(divisor));
+ compRem = longCompareTo(Math.abs(rem) * 2,Math.abs(divisor));
// To look if there is a carry
compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
sign * (5 + compRem), roundingMode);
@@ -1169,7 +1157,7 @@
if (remainder != 0) {
// Checking if: remainder * 2 >= scaledDivisor
int compRem; // 'compare to remainder'
- compRem = longCompareTo(Math.abs(remainder) << 1,Math.abs(scaledDivisor));
+ compRem = longCompareTo(Math.abs(remainder) * 2,Math.abs(scaledDivisor));
// To look if there is a carry
quotient += roundingBehavior(((int)quotient) & 1,
sign * (5 + compRem),
@@ -2831,7 +2819,7 @@
// If the discarded fraction is non-zero perform rounding
if (fraction != 0) {
// To check if the discarded fraction >= 0.5
- compRem = longCompareTo(Math.abs(fraction) << 1,sizeOfFraction);
+ compRem = longCompareTo(Math.abs(fraction) * 2, sizeOfFraction);
// To look if there is a carry
integer += roundingBehavior( ((int)integer) & 1,
Long.signum(fraction) * (5 + compRem),
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/math/MathContext.java b/luni/src/main/java/java/math/MathContext.java
index 1e8e430..1231bc6 100644
--- a/luni/src/main/java/java/math/MathContext.java
+++ b/luni/src/main/java/java/math/MathContext.java
@@ -276,9 +276,9 @@
* Returns the string representation for this {@code MathContext} instance.
* The string has the form
* {@code
- * "precision=<precision> roundingMode=<roundingMode>"
- * } where {@code <precision>} is an integer describing the number
- * of digits used for operations and {@code <roundingMode>} is the
+ * "precision=<precision> roundingMode=<roundingMode>"
+ * } where {@code <precision>} is an integer describing the number
+ * of digits used for operations and {@code <roundingMode>} is the
* string representation of the rounding mode.
*
* @return a string representation for this {@code MathContext} instance
diff --git a/luni/src/main/java/java/net/AddressCache.java b/luni/src/main/java/java/net/AddressCache.java
index 063c9e0..cbde9a4 100644
--- a/luni/src/main/java/java/net/AddressCache.java
+++ b/luni/src/main/java/java/net/AddressCache.java
@@ -40,15 +40,13 @@
// Default time-to-live for negative cache entries. 10 seconds.
private static final long DEFAULT_NEGATIVE_TTL_NANOS = 10 * 1000000000L;
- // Failed lookups are represented in the cache my mappings to this empty array.
- private static final InetAddress[] NO_ADDRESSES = new InetAddress[0];
-
// The actual cache.
private final Map<String, AddressCacheEntry> map;
static class AddressCacheEntry {
- // The addresses. May be the empty array for a negative cache entry.
- InetAddress[] addresses;
+ // Either an InetAddress[] for a positive entry,
+ // or a String detail message for a negative entry.
+ final Object value;
/**
* The absolute expiry time in nanoseconds. Nanoseconds from System.nanoTime is ideal
@@ -56,10 +54,10 @@
*
* Unless we need to cope with DNS TTLs of 292 years, we don't need to worry about overflow.
*/
- long expiryNanos;
+ final long expiryNanos;
- AddressCacheEntry(InetAddress[] addresses, long expiryNanos) {
- this.addresses = addresses;
+ AddressCacheEntry(Object value, long expiryNanos) {
+ this.value = value;
this.expiryNanos = expiryNanos;
}
}
@@ -77,17 +75,27 @@
}
/**
- * 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.
+ * Removes all entries from the cache.
*/
- public InetAddress[] get(String hostname) {
+ public void clear() {
+ synchronized (map) {
+ map.clear();
+ }
+ }
+
+ /**
+ * Returns the cached InetAddress[] associated with 'hostname'. Returns null if nothing is known
+ * about 'hostname'. Returns a String suitable for use as an UnknownHostException detail
+ * message if 'hostname' is known not to exist.
+ */
+ public Object get(String hostname) {
AddressCacheEntry entry;
synchronized (map) {
entry = map.get(hostname);
}
// Do we have a valid cache entry?
if (entry != null && entry.expiryNanos >= System.nanoTime()) {
- return entry.addresses;
+ return entry.value;
}
// Either we didn't find anything, or it had expired.
// No need to remove expired entries: the caller will provide a replacement shortly.
@@ -99,8 +107,23 @@
* certain length of time.
*/
public void put(String hostname, InetAddress[] addresses) {
+ put(hostname, addresses, true);
+ }
+
+ /**
+ * Associates the given 'detailMessage' with 'hostname'. The association will expire after a
+ * certain length of time.
+ */
+ public void put(String hostname, String detailMessage) {
+ put(hostname, detailMessage, false);
+ }
+
+ /**
+ * Associates the given 'addresses' with 'hostname'. The association will expire after a
+ * certain length of time.
+ */
+ public void put(String hostname, Object value, boolean isPositive) {
// Calculate the expiry time.
- boolean isPositive = (addresses.length > 0);
String propertyName = isPositive ? "networkaddress.cache.ttl" : "networkaddress.cache.negative.ttl";
long defaultTtlNanos = isPositive ? DEFAULT_POSITIVE_TTL_NANOS : DEFAULT_NEGATIVE_TTL_NANOS;
// Fast-path the default case...
@@ -114,7 +137,7 @@
}
// Update the cache.
synchronized (map) {
- map.put(hostname, new AddressCacheEntry(addresses, expiryNanos));
+ map.put(hostname, new AddressCacheEntry(value, expiryNanos));
}
}
@@ -122,8 +145,8 @@
* Records that 'hostname' is known not to have any associated addresses. (I.e. insert a
* negative cache entry.)
*/
- public void putUnknownHost(String hostname) {
- put(hostname, NO_ADDRESSES);
+ public void putUnknownHost(String hostname, String detailMessage) {
+ put(hostname, detailMessage);
}
private long customTtl(String propertyName, long defaultTtlNanos) {
diff --git a/luni/src/main/java/java/net/DatagramSocket.java b/luni/src/main/java/java/net/DatagramSocket.java
index 532b53d..d1cc593 100644
--- a/luni/src/main/java/java/net/DatagramSocket.java
+++ b/luni/src/main/java/java/net/DatagramSocket.java
@@ -45,10 +45,7 @@
private boolean isClosed = false;
- private static class Lock {
- }
-
- private Object lock = new Lock();
+ private Object lock = new Object();
/**
* Constructs a UDP datagram socket which is bound to any available port on
@@ -821,11 +818,11 @@
}
/**
- * Gets the related DatagramChannel of this socket. This implementation
- * returns always {@code null}.
- *
- * @return the related DatagramChannel or {@code null} if this socket was
- * not created by a {@code DatagramChannel} object.
+ * Returns this socket's {@code DatagramChannel}, if one exists. A channel is
+ * available only if this socket wraps a channel. (That is, you can go from a
+ * channel to a socket and back again, but you can't go from an arbitrary socket to a channel.)
+ * In practice, this means that the socket must have been created by
+ * {@link java.nio.channels.DatagramChannel#open}.
*/
public DatagramChannel getChannel() {
return null;
diff --git a/luni/src/main/java/java/net/DatagramSocketImpl.java b/luni/src/main/java/java/net/DatagramSocketImpl.java
index bc27c96..e92cb72 100644
--- a/luni/src/main/java/java/net/DatagramSocketImpl.java
+++ b/luni/src/main/java/java/net/DatagramSocketImpl.java
@@ -87,7 +87,7 @@
* @return the local address to which the socket is bound.
*/
InetAddress getLocalAddress() {
- return Platform.getNetworkSystem().getSocketLocalAddress(fd);
+ return Platform.NETWORK.getSocketLocalAddress(fd);
}
/**
diff --git a/luni/src/main/java/java/net/HttpCookie.java b/luni/src/main/java/java/net/HttpCookie.java
index 1b333ef..ce4c123 100644
--- a/luni/src/main/java/java/net/HttpCookie.java
+++ b/luni/src/main/java/java/net/HttpCookie.java
@@ -134,7 +134,7 @@
* From the spec: "both host names are IP addresses and their host name strings match
* exactly; or both host names are FQDN strings and their host name strings match exactly"
*/
- if (a.equals(b) && (isFullyQualifiedDomainName(a, 0) || !InetAddress.isHostName(a))) {
+ if (a.equals(b) && (isFullyQualifiedDomainName(a, 0) || InetAddress.isNumeric(a))) {
return true;
}
if (!isFullyQualifiedDomainName(a, 0)) {
diff --git a/luni/src/main/java/java/net/Inet4Address.java b/luni/src/main/java/java/net/Inet4Address.java
index 86e12c1..d5431ac 100644
--- a/luni/src/main/java/java/net/Inet4Address.java
+++ b/luni/src/main/java/java/net/Inet4Address.java
@@ -18,6 +18,8 @@
package java.net;
import java.io.ObjectStreamException;
+import java.nio.ByteOrder;
+import org.apache.harmony.luni.platform.OSMemory;
/**
* An IPv4 address. See {@link InetAddress}.
@@ -28,14 +30,8 @@
private static final int AF_INET = 2;
- final static InetAddress ANY = new Inet4Address(new byte[] { 0, 0, 0, 0 });
- final static InetAddress LOOPBACK = new Inet4Address(
- new byte[] { 127, 0, 0, 1 }, "localhost");
-
- Inet4Address(byte[] address) {
- family = AF_INET;
- ipaddress = address;
- }
+ final static InetAddress ANY = new Inet4Address(new byte[] { 0, 0, 0, 0 }, null);
+ final static InetAddress LOOPBACK = new Inet4Address(new byte[] { 127, 0, 0, 1 }, "localhost");
Inet4Address(byte[] address, String name) {
family = AF_INET;
@@ -136,7 +132,7 @@
return false;
}
- int address = InetAddress.bytesToInt(ipaddress, 0);
+ int address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN);
/*
* Now check the boundaries of the global space if we have an address
* that is prefixed by something less than 111000000000000000000001
@@ -181,7 +177,8 @@
*/
@Override
public boolean isMCLinkLocal() {
- return InetAddress.bytesToInt(ipaddress, 0) >>> 8 == 0xE00000;
+ int address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN);
+ return (address >>> 8) == 0xE00000;
}
/**
@@ -194,7 +191,8 @@
*/
@Override
public boolean isMCSiteLocal() {
- return (InetAddress.bytesToInt(ipaddress, 0) >>> 16) == 0xEFFF;
+ int address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN);
+ return (address >>> 16) == 0xEFFF;
}
/**
@@ -208,7 +206,8 @@
*/
@Override
public boolean isMCOrgLocal() {
- int prefix = InetAddress.bytesToInt(ipaddress, 0) >>> 16;
+ int address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN);
+ int prefix = address >>> 16;
return prefix >= 0xEFC0 && prefix <= 0xEFC3;
}
diff --git a/luni/src/main/java/java/net/Inet6Address.java b/luni/src/main/java/java/net/Inet6Address.java
index 79b39ee..24a069f 100644
--- a/luni/src/main/java/java/net/Inet6Address.java
+++ b/luni/src/main/java/java/net/Inet6Address.java
@@ -21,6 +21,7 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
+import java.util.Arrays;
import java.util.Enumeration;
/**
@@ -32,10 +33,11 @@
private static final int AF_INET6 = 10;
- static final InetAddress ANY = new Inet6Address(new byte[]
- {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
- static final InetAddress LOOPBACK = new Inet6Address(new byte[]
- {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, "localhost");
+ static final InetAddress ANY =
+ new Inet6Address(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, null, 0);
+ static final InetAddress LOOPBACK =
+ new Inet6Address(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
+ "localhost", 0);
int scope_id;
@@ -50,19 +52,6 @@
*/
transient NetworkInterface scopedIf;
- Inet6Address(byte[] address) {
- family = AF_INET6;
- ipaddress = address;
- scope_id = 0;
- }
-
- Inet6Address(byte[] address, String name) {
- family = AF_INET6;
- hostName = name;
- ipaddress = address;
- scope_id = 0;
- }
-
/**
* Constructs an {@code InetAddress} representing the {@code address} and
* {@code name} and {@code scope_id}.
@@ -75,13 +64,11 @@
* the scope id for link- or site-local addresses.
*/
Inet6Address(byte[] address, String name, int scope_id) {
- family = AF_INET6;
- hostName = name;
- ipaddress = address;
+ this.family = AF_INET6;
+ this.hostName = name;
+ this.ipaddress = address;
this.scope_id = scope_id;
- if (scope_id != 0) {
- scope_id_set = true;
- }
+ this.scope_id_set = (scope_id != 0);
}
/**
@@ -98,14 +85,15 @@
* @throws UnknownHostException
* if the address is null or has an invalid length.
*/
- public static Inet6Address getByAddress(String host, byte[] addr,
- int scope_id) throws UnknownHostException {
+ public static Inet6Address getByAddress(String host, byte[] addr, int scope_id)
+ throws UnknownHostException {
if (addr == null || addr.length != 16) {
- throw new UnknownHostException("Illegal IPv6 address");
+ throw new UnknownHostException("Not an IPv6 address: " + Arrays.toString(addr));
}
if (scope_id < 0) {
scope_id = 0;
}
+ // TODO: should we clone 'addr'?
return new Inet6Address(addr, host, scope_id);
}
@@ -158,7 +146,7 @@
// if no address matches the type of addr, throws an
// UnknownHostException.
if (!address.scope_id_set) {
- throw new UnknownHostException("Scope id not found for the given address");
+ throw new UnknownHostException("Scope id not found for address: " + Arrays.toString(addr));
}
return address;
}
@@ -186,23 +174,6 @@
}
/**
- * Constructs an {@code InetAddress} representing the {@code address} and
- * {@code scope_id}.
- *
- * @param address
- * the network address.
- * @param scope_id
- * the scope id for link- or site-local addresses.
- */
- Inet6Address(byte[] address, int scope_id) {
- ipaddress = address;
- this.scope_id = scope_id;
- if (scope_id != 0) {
- scope_id_set = true;
- }
- }
-
- /**
* Returns whether this address is an IP multicast address or not. Valid
* IPv6 multicast addresses are binary prefixed with 11111111 or FF (hex).
*
@@ -359,11 +330,6 @@
return (ipaddress[0] == -1) && (ipaddress[1] & 15) == 8;
}
- // BEGIN android-removed
- // public String getHostAddress() {
- // }
- // END android-removed
-
/**
* Gets the scope id as a number if this address is linked to an interface.
* Otherwise returns {@code 0}.
@@ -391,14 +357,6 @@
return null;
}
- // BEGIN android-removed
- // public int hashCode() {}
- // END android-removed
-
- // BEGIN android-removed
- // public boolean equals(Object obj) {}
- // END android-removed
-
/**
* Returns whether this address is IPv4 compatible or not. An IPv4
* compatible address is prefixed with 96 bits of 0's. The last 32-bits are
diff --git a/luni/src/main/java/java/net/InetAddress.java b/luni/src/main/java/java/net/InetAddress.java
index 2f283bb..22c1702 100644
--- a/luni/src/main/java/java/net/InetAddress.java
+++ b/luni/src/main/java/java/net/InetAddress.java
@@ -25,13 +25,14 @@
import java.io.ObjectStreamException;
import java.io.ObjectStreamField;
import java.io.Serializable;
+import java.nio.ByteOrder;
import java.security.AccessController;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
-import org.apache.harmony.luni.platform.INetworkSystem;
+import org.apache.harmony.luni.platform.OSMemory;
import org.apache.harmony.luni.platform.Platform;
import org.apache.harmony.luni.util.PriviAction;
@@ -118,6 +119,9 @@
* See <a href="https://www.ietf.org/rfc/rfc4007.txt">RFC 4007</a> for more on IPv6's scoped
* address architecture.
*
+ * <p>Additionally, for backwards compatibility, IPv6 addresses may be surrounded by square
+ * brackets.
+ *
* <h4>DNS caching</h4>
* <p>On Android, addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are
* cached for 10 seconds. The underlying C library or OS may cache for longer, but you can control
@@ -136,8 +140,6 @@
/** Our Java-side DNS cache. */
private static final AddressCache addressCache = new AddressCache();
- private final static INetworkSystem NETIMPL = Platform.getNetworkSystem();
-
private static final String ERRMSG_CONNECTION_REFUSED = "Connection refused";
private static final long serialVersionUID = 3286316764910316507L;
@@ -214,8 +216,9 @@
* @param hostName the hostname corresponding to the IP address.
* @return the corresponding InetAddresses, appropriately sorted.
*/
- static InetAddress[] bytesToInetAddresses(byte[][] rawAddresses, String hostName) {
- // If we prefer IPv4, ignore the RFC3484 ordering we get from getaddrinfo
+ static InetAddress[] bytesToInetAddresses(byte[][] rawAddresses, String hostName)
+ throws UnknownHostException {
+ // If we prefer IPv4, ignore the RFC3484 ordering we get from getaddrinfo(3)
// and always put IPv4 addresses first. Arrays.sort() is stable, so the
// internal ordering will not be changed.
if (!preferIPv6Addresses()) {
@@ -225,17 +228,7 @@
// Convert the byte arrays to InetAddresses.
InetAddress[] returnedAddresses = new InetAddress[rawAddresses.length];
for (int i = 0; i < rawAddresses.length; i++) {
- byte[] rawAddress = rawAddresses[i];
- if (rawAddress.length == 16) {
- returnedAddresses[i] = new Inet6Address(rawAddress, hostName);
- } else if (rawAddress.length == 4) {
- returnedAddresses[i] = new Inet4Address(rawAddress, hostName);
- } else {
- // Cannot happen, because the underlying code only returns
- // addresses that are 4 or 16 bytes long.
- throw new AssertionError("Impossible address length " +
- rawAddress.length);
- }
+ returnedAddresses[i] = makeInetAddress(rawAddresses[i], hostName);
}
return returnedAddresses;
}
@@ -274,16 +267,10 @@
return new InetAddress[] { Inet4Address.ANY };
}
- try {
- byte[] hBytes = ipStringToByteArray(host);
- if (hBytes.length == 4) {
- return (new InetAddress[] { new Inet4Address(hBytes) });
- } else if (hBytes.length == 16) {
- return (new InetAddress[] { new Inet6Address(hBytes) });
- } else {
- throw new UnknownHostException(wrongAddressLength());
- }
- } catch (UnknownHostException e) {
+ // Is it a numeric address?
+ byte[] bytes = ipStringToByteArray(host);
+ if (bytes != null) {
+ return new InetAddress[] { makeInetAddress(bytes, null) };
}
SecurityManager security = System.getSecurityManager();
@@ -294,13 +281,19 @@
return lookupHostByName(host);
}
+ private static InetAddress makeInetAddress(byte[] bytes, String hostname) throws UnknownHostException {
+ if (bytes.length == 4) {
+ return new Inet4Address(bytes, hostname);
+ } else if (bytes.length == 16) {
+ return new Inet6Address(bytes, hostname, 0);
+ } else {
+ throw badAddressLength(bytes);
+ }
+ }
+
private static native String byteArrayToIpString(byte[] address);
- static native byte[] ipStringToByteArray(String address) throws UnknownHostException;
-
- private static String wrongAddressLength() {
- return "Invalid IP Address is neither 4 or 16 bytes";
- }
+ static native byte[] ipStringToByteArray(String address);
static boolean preferIPv6Addresses() {
String propertyName = "java.net.preferIPv6Addresses";
@@ -346,7 +339,7 @@
if (hostName == null) {
int address = 0;
if (ipaddress.length == 4) {
- address = bytesToInt(ipaddress, 0);
+ address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN);
if (address == 0) {
return hostName = byteArrayToIpString(ipaddress);
}
@@ -363,7 +356,7 @@
SecurityManager security = System.getSecurityManager();
try {
// Only check host names, not addresses
- if (security != null && isHostName(hostName)) {
+ if (security != null && !isNumeric(hostName)) {
security.checkConnect(hostName, -1);
}
} catch (SecurityException e) {
@@ -385,7 +378,7 @@
try {
int address = 0;
if (ipaddress.length == 4) {
- address = bytesToInt(ipaddress, 0);
+ address = OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN);
if (address == 0) {
return byteArrayToIpString(ipaddress);
}
@@ -397,7 +390,7 @@
SecurityManager security = System.getSecurityManager();
try {
// Only check host names, not addresses
- if (security != null && isHostName(canonicalName)) {
+ if (security != null && !isNumeric(canonicalName)) {
security.checkConnect(canonicalName, -1);
}
} catch (SecurityException e) {
@@ -487,14 +480,14 @@
private static InetAddress[] lookupHostByName(String host) throws UnknownHostException {
BlockGuard.getThreadPolicy().onNetwork();
// Do we have a result cached?
- InetAddress[] cachedResult = addressCache.get(host);
+ Object cachedResult = addressCache.get(host);
if (cachedResult != null) {
- if (cachedResult.length > 0) {
+ if (cachedResult instanceof InetAddress[]) {
// A cached positive result.
- return cachedResult;
+ return (InetAddress[]) cachedResult;
} else {
// A cached negative result.
- throw new UnknownHostException(host);
+ throw new UnknownHostException((String) cachedResult);
}
}
try {
@@ -502,13 +495,23 @@
addressCache.put(host, addresses);
return addresses;
} catch (UnknownHostException e) {
- addressCache.putUnknownHost(host);
- throw new UnknownHostException(host);
+ String detailMessage = e.getMessage();
+ addressCache.putUnknownHost(host, detailMessage);
+ throw new UnknownHostException(detailMessage);
}
}
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
@@ -516,16 +519,9 @@
* @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));
- } else if (addr.length == 16) {
- return new Inet6Address(addr, getnameinfo(addr));
- } else {
- throw new UnknownHostException(wrongAddressLength());
- }
+ return makeInetAddress(addr, getnameinfo(addr));
}
/**
@@ -537,7 +533,7 @@
if (host == null || 0 == host.length()) {
return Inet4Address.LOOPBACK.getHostAddress();
}
- if (isHostName(host)) {
+ if (!isNumeric(host)) {
if (isCheck) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
@@ -561,15 +557,14 @@
}
/**
- * Returns true if the string is a host name, false if it is an IP Address.
+ * Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1").
+ * This copes with all forms of address that Java supports, detailed in the {@link InetAddress}
+ * class documentation.
+ *
+ * @hide - used by frameworks/base to ensure that a getAllByName won't cause a DNS lookup.
*/
- static boolean isHostName(String value) {
- try {
- ipStringToByteArray(value);
- return false;
- } catch (UnknownHostException e) {
- return true;
- }
+ public static boolean isNumeric(String address) {
+ return ipStringToByteArray(address) != null;
}
/**
@@ -863,12 +858,12 @@
throws IOException {
FileDescriptor fd = new FileDescriptor();
boolean reached = false;
- NETIMPL.socket(fd, true);
+ Platform.NETWORK.socket(fd, true);
try {
if (null != source) {
- NETIMPL.bind(fd, source, 0);
+ Platform.NETWORK.bind(fd, source, 0);
}
- NETIMPL.connect(fd, destination, 7, timeout);
+ Platform.NETWORK.connect(fd, destination, 7, timeout);
reached = true;
} catch (IOException e) {
if (ERRMSG_CONNECTION_REFUSED.equals(e.getMessage())) {
@@ -877,7 +872,7 @@
}
}
- NETIMPL.close(fd);
+ Platform.NETWORK.close(fd);
return reached;
}
@@ -998,60 +993,29 @@
* @return the InetAddress
* @throws UnknownHostException
*/
- static InetAddress getByAddressInternal(String hostName, byte[] ipAddress,
- int scope_id) throws UnknownHostException {
+ static InetAddress getByAddressInternal(String hostName, byte[] ipAddress, int scope_id)
+ throws UnknownHostException {
if (ipAddress == null) {
throw new UnknownHostException("ipAddress == null");
}
- switch (ipAddress.length) {
- case 4:
- return new Inet4Address(ipAddress.clone());
- case 16:
- // First check to see if the address is an IPv6-mapped
- // IPv4 address. If it is, then we can make it a IPv4
- // address, otherwise, we'll create an IPv6 address.
- if (isIPv4MappedAddress(ipAddress)) {
- return new Inet4Address(ipv4MappedToIPv4(ipAddress));
- } else {
- return new Inet6Address(ipAddress.clone(), scope_id);
- }
- default:
- throw new UnknownHostException(
- "Invalid IP Address is neither 4 or 16 bytes: " + hostName);
+ if (ipAddress.length == 4) {
+ return new Inet4Address(ipAddress.clone(), null);
+ } else if (ipAddress.length == 16) {
+ // First check to see if the address is an IPv6-mapped
+ // IPv4 address. If it is, then we can make it a IPv4
+ // address, otherwise, we'll create an IPv6 address.
+ if (isIPv4MappedAddress(ipAddress)) {
+ return new Inet4Address(ipv4MappedToIPv4(ipAddress), null);
+ } else {
+ return new Inet6Address(ipAddress.clone(), null, scope_id);
+ }
+ } else {
+ throw badAddressLength(ipAddress);
}
}
- /**
- * Takes the integer and chops it into 4 bytes, putting it into the byte
- * array starting with the high order byte at the index start. This method
- * makes no checks on the validity of the parameters.
- */
- static void intToBytes(int value, byte[] bytes, int start) {
- // Shift the int so the current byte is right-most
- // Use a byte mask of 255 to single out the last byte.
- bytes[start] = (byte) ((value >> 24) & 255);
- bytes[start + 1] = (byte) ((value >> 16) & 255);
- bytes[start + 2] = (byte) ((value >> 8) & 255);
- bytes[start + 3] = (byte) (value & 255);
- }
-
- /**
- * Takes the byte array and creates an integer out of four bytes starting at
- * start as the high-order byte. This method makes no checks on the validity
- * of the parameters.
- */
- static int bytesToInt(byte[] bytes, int start) {
- // First mask the byte with 255, as when a negative
- // signed byte converts to an integer, it has bits
- // on in the first 3 bytes, we are only concerned
- // about the right-most 8 bits.
- // Then shift the rightmost byte to align with its
- // position in the integer.
- int value = ((bytes[start + 3] & 255))
- | ((bytes[start + 2] & 255) << 8)
- | ((bytes[start + 1] & 255) << 16)
- | ((bytes[start] & 255) << 24);
- return value;
+ private static UnknownHostException badAddressLength(byte[] bytes) throws UnknownHostException {
+ throw new UnknownHostException("Address is neither 4 or 16 bytes: " + Arrays.toString(bytes));
}
private static final ObjectStreamField[] serialPersistentFields = {
@@ -1064,7 +1028,7 @@
if (ipaddress == null) {
fields.put("address", 0);
} else {
- fields.put("address", bytesToInt(ipaddress, 0));
+ fields.put("address", OSMemory.peekInt(ipaddress, 0, ByteOrder.BIG_ENDIAN));
}
fields.put("family", family);
fields.put("hostName", hostName);
@@ -1072,12 +1036,11 @@
stream.writeFields();
}
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
int addr = fields.get("address", 0);
ipaddress = new byte[4];
- intToBytes(addr, ipaddress, 0);
+ OSMemory.pokeInt(ipaddress, 0, addr, ByteOrder.BIG_ENDIAN);
hostName = (String) fields.get("hostName", null);
family = fields.get("family", 2);
}
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/InterfaceAddress.java b/luni/src/main/java/java/net/InterfaceAddress.java
index 45fc236..2f8029e 100644
--- a/luni/src/main/java/java/net/InterfaceAddress.java
+++ b/luni/src/main/java/java/net/InterfaceAddress.java
@@ -69,7 +69,7 @@
broadcast[i] = (byte) (addrBytes[i] | ~maskBytes[i]);
}
}
- return new Inet4Address(broadcast);
+ return new Inet4Address(broadcast, null);
}
private static short countPrefixLength(InetAddress mask) {
diff --git a/luni/src/main/java/java/net/NetworkInterface.java b/luni/src/main/java/java/net/NetworkInterface.java
index 115e98a..457b0e6 100644
--- a/luni/src/main/java/java/net/NetworkInterface.java
+++ b/luni/src/main/java/java/net/NetworkInterface.java
@@ -53,10 +53,6 @@
private final List<NetworkInterface> children = new LinkedList<NetworkInterface>();
- // BEGIN android-changed: we pay this extra complexity on the Java side
- // in return for vastly simpler native code.
- private static native InterfaceAddress[] getAllInterfaceAddressesImpl() throws SocketException;
-
private static NetworkInterface[] getNetworkInterfacesImpl() throws SocketException {
Map<String, NetworkInterface> networkInterfaces = new LinkedHashMap<String, NetworkInterface>();
for (InterfaceAddress ia : getAllInterfaceAddressesImpl()) {
@@ -75,7 +71,7 @@
}
return networkInterfaces.values().toArray(new NetworkInterface[networkInterfaces.size()]);
}
- // END android-changed
+ private static native InterfaceAddress[] getAllInterfaceAddressesImpl() throws SocketException;
/**
* This constructor is used by the native method in order to construct the
@@ -332,10 +328,8 @@
string.append(name);
string.append("][");
string.append(displayName);
- // BEGIN android-added: the RI shows this, and it's useful for IPv6 users.
string.append("][");
string.append(interfaceIndex);
- // END android-added
string.append("]");
/*
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/ResponseCache.java b/luni/src/main/java/java/net/ResponseCache.java
index b92e6db..5eeb551 100644
--- a/luni/src/main/java/java/net/ResponseCache.java
+++ b/luni/src/main/java/java/net/ResponseCache.java
@@ -80,7 +80,7 @@
*
* @param uri
* the reference to the requested resource.
- * @param conn
+ * @param connection
* the connection to fetch the response.
* @return a CacheRequest object with a WriteableByteChannel if the resource
* has to be cached, {@code null} otherwise.
@@ -89,5 +89,5 @@
* @throws IllegalArgumentException
* if any one of the parameters is set to {@code null}.
*/
- public abstract CacheRequest put(URI uri, URLConnection conn) throws IOException;
+ public abstract CacheRequest put(URI uri, URLConnection connection) throws IOException;
}
diff --git a/luni/src/main/java/java/net/ServerSocket.java b/luni/src/main/java/java/net/ServerSocket.java
index e7e7f9f..24aab75 100644
--- a/luni/src/main/java/java/net/ServerSocket.java
+++ b/luni/src/main/java/java/net/ServerSocket.java
@@ -518,11 +518,11 @@
}
/**
- * Gets the related channel if this instance was created by a
- * {@code ServerSocketChannel}. The current implementation returns always {@code
- * null}.
- *
- * @return the related {@code ServerSocketChannel} if any.
+ * Returns this socket's {@code ServerSocketChannel}, if one exists. A channel is
+ * available only if this socket wraps a channel. (That is, you can go from a
+ * channel to a socket and back again, but you can't go from an arbitrary socket to a channel.)
+ * In practice, this means that the socket must have been created by
+ * {@link java.nio.channels.ServerSocketChannel#open}.
*/
public ServerSocketChannel getChannel() {
return null;
diff --git a/luni/src/main/java/java/net/Socket.java b/luni/src/main/java/java/net/Socket.java
index f578a25..c18bba8 100644
--- a/luni/src/main/java/java/net/Socket.java
+++ b/luni/src/main/java/java/net/Socket.java
@@ -42,10 +42,7 @@
private InetAddress localAddress = Inet4Address.ANY;
- private static class ConnectLock {
- }
-
- private final Object connectLock = new ConnectLock();
+ private final Object connectLock = new Object();
/**
* Creates a new unconnected socket. When a SocketImplFactory is defined it
@@ -102,7 +99,6 @@
this.impl = factory != null ? factory.createSocketImpl() : new PlainSocketImpl(proxy);
}
- // BEGIN android-added
/**
* Tries to connect a socket to all IP addresses of the given hostname.
*
@@ -149,7 +145,6 @@
checkDestination(dstAddress, dstPort);
startupSocket(dstAddress, dstPort, localAddress, localPort, streaming);
}
- // END android-added
/**
* Creates a new streaming socket connected to the target host specified by
@@ -1120,14 +1115,16 @@
}
private void cacheLocalAddress() {
- this.localAddress = Platform.getNetworkSystem().getSocketLocalAddress(impl.fd);
+ this.localAddress = Platform.NETWORK.getSocketLocalAddress(impl.fd);
}
/**
- * Gets the SocketChannel of this socket, if one is available. The current
- * implementation of this method returns always {@code null}.
- *
- * @return the related SocketChannel or {@code null} if no channel exists.
+ * Returns this socket's {@code SocketChannel}, if one exists. A channel is
+ * available only if this socket wraps a channel. (That is, you can go from a
+ * channel to a socket and back again, but you can't go from an arbitrary socket to a channel.)
+ * In practice, this means that the socket must have been created by
+ * {@link java.nio.channels.ServerSocketChannel#accept} or
+ * {@link java.nio.channels.SocketChannel#open}.
*/
public SocketChannel getChannel() {
return null;
diff --git a/luni/src/main/java/java/net/SocketImpl.java b/luni/src/main/java/java/net/SocketImpl.java
index 8eec68b..e3d9c04 100644
--- a/luni/src/main/java/java/net/SocketImpl.java
+++ b/luni/src/main/java/java/net/SocketImpl.java
@@ -21,7 +21,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import org.apache.harmony.luni.platform.INetworkSystem;
import org.apache.harmony.luni.platform.Platform;
/**
@@ -55,8 +54,6 @@
*/
protected int localport;
- INetworkSystem netImpl = Platform.getNetworkSystem();
-
boolean streaming = true;
/**
@@ -239,9 +236,9 @@
*/
int write(byte[] buffer, int offset, int count) throws IOException {
if (streaming) {
- return this.netImpl.write(fd, buffer, offset, count);
+ return Platform.NETWORK.write(fd, buffer, offset, count);
} else {
- return this.netImpl.send(fd, buffer, offset, count, port, address);
+ return Platform.NETWORK.send(fd, buffer, offset, count, port, address);
}
}
diff --git a/luni/src/main/java/java/net/SocketPermission.java b/luni/src/main/java/java/net/SocketPermission.java
index d09ae4c..977e310 100644
--- a/luni/src/main/java/java/net/SocketPermission.java
+++ b/luni/src/main/java/java/net/SocketPermission.java
@@ -53,7 +53,7 @@
* lowest or highest possible value respectively. For example:
*
* <pre>
- * {@code SocketPermission("www.company.com:7000-", "connect,accept")}
+ * {@code SocketPermission("www.company.com:7000-", "connect,accept")}
* </pre>
*
* represents the permission to connect to and accept connections from {@code
diff --git a/luni/src/main/java/java/net/URI.java b/luni/src/main/java/java/net/URI.java
index 9626847..2d3b1d4 100644
--- a/luni/src/main/java/java/net/URI.java
+++ b/luni/src/main/java/java/net/URI.java
@@ -31,8 +31,6 @@
*/
public final class URI implements Comparable<URI>, Serializable {
- private final static INetworkSystem NETWORK_SYSTEM = Platform.getNetworkSystem();
-
private static final long serialVersionUID = -6052424284110960213l;
static final String UNRESERVED = "_-!.~\'()*";
@@ -545,17 +543,14 @@
throw new URISyntaxException(host,
"Expected a closing square bracket for IPv6 address", 0);
}
- try {
- byte[] bytes = InetAddress.ipStringToByteArray(host);
- /*
- * The native IP parser may return 4 bytes for addresses like
- * "[::FFFF:127.0.0.1]". This is allowed, but we must not accept
- * IPv4-formatted addresses in square braces like "[127.0.0.1]".
- */
- if (bytes.length == 16 || bytes.length == 4 && host.contains(":")) {
- return true;
- }
- } catch (UnknownHostException e) {
+ byte[] bytes = InetAddress.ipStringToByteArray(host);
+ /*
+ * The native IP parser may return 4 bytes for addresses like
+ * "[::FFFF:127.0.0.1]". This is allowed, but we must not accept
+ * IPv4-formatted addresses in square braces like "[127.0.0.1]".
+ */
+ if (bytes != null && (bytes.length == 16 || bytes.length == 4 && host.contains(":"))) {
+ return true;
}
throw new URISyntaxException(host, "Malformed IPv6 address");
}
@@ -580,11 +575,9 @@
}
// IPv4 address
- try {
- if (InetAddress.ipStringToByteArray(host).length == 4) {
- return true;
- }
- } catch (UnknownHostException e) {
+ byte[] bytes = InetAddress.ipStringToByteArray(host);
+ if (bytes != null && bytes.length == 4) {
+ return true;
}
if (forceServer) {
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/net/UnknownHostException.java b/luni/src/main/java/java/net/UnknownHostException.java
index 325d36d..876593b 100644
--- a/luni/src/main/java/java/net/UnknownHostException.java
+++ b/luni/src/main/java/java/net/UnknownHostException.java
@@ -20,23 +20,24 @@
import java.io.IOException;
/**
- * Is thrown when a hostname can not be resolved.
+ * Thrown when a hostname can not be resolved.
*/
public class UnknownHostException extends IOException {
private static final long serialVersionUID = -4639126076052875403L;
/**
- * Constructs a new {@code UnknownHostException} instance with its walkback
- * filled in.
+ * Constructs a new {@code UnknownHostException} instance with no detail message.
+ * Callers should usually supply a detail message.
*/
public UnknownHostException() {
super();
}
/**
- * Constructs a new {@code UnknownHostException} instance with its walkback
- * and message filled in.
+ * Constructs a new {@code UnknownHostException} instance with the given detail message.
+ * The detail message should generally contain the hostname and a reason for the failure,
+ * if known.
*
* @param detailMessage
* the detail message for this exception.
diff --git a/luni/src/main/java/java/nio/BaseByteBuffer.java b/luni/src/main/java/java/nio/BaseByteBuffer.java
index ba086a8..d6cfb93 100644
--- a/luni/src/main/java/java/nio/BaseByteBuffer.java
+++ b/luni/src/main/java/java/nio/BaseByteBuffer.java
@@ -22,57 +22,57 @@
*/
abstract class BaseByteBuffer extends ByteBuffer {
- protected BaseByteBuffer(int capacity) {
- super(capacity);
+ protected BaseByteBuffer(int capacity, MemoryBlock block) {
+ super(capacity, block);
}
@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
- public final char getChar() {
+ public char getChar() {
return (char) getShort();
}
@Override
- public final char getChar(int index) {
+ public char getChar(int index) {
return (char) getShort(index);
}
@Override
- public final ByteBuffer putChar(char value) {
+ public ByteBuffer putChar(char value) {
return putShort((short) value);
}
@Override
- public final ByteBuffer putChar(int index, char value) {
+ public ByteBuffer putChar(int index, char value) {
return putShort(index, (short) value);
}
}
diff --git a/luni/src/main/java/java/nio/Buffer.java b/luni/src/main/java/java/nio/Buffer.java
index e141ea0..f2e6da0 100644
--- a/luni/src/main/java/java/nio/Buffer.java
+++ b/luni/src/main/java/java/nio/Buffer.java
@@ -45,11 +45,10 @@
* synchronization issues.
*/
public abstract class Buffer {
-
/**
* <code>UNSET_MARK</code> means the mark has not been set.
*/
- final static int UNSET_MARK = -1;
+ static final int UNSET_MARK = -1;
/**
* The capacity of this buffer, which never changes.
@@ -75,38 +74,33 @@
*/
int position = 0;
- // BEGIN android-added
/**
* The log base 2 of the element size of this buffer. Each typed subclass
* (ByteBuffer, CharBuffer, etc.) is responsible for initializing this
* value. The value is used by JNI code in frameworks/base/ to avoid the
* need for costly 'instanceof' tests.
*/
- int _elementSizeShift;
+ final int _elementSizeShift;
/**
- * For direct buffers, the effective address of the data. This is set
- * on first use. If the field is zero, this is either not a direct
- * buffer or the field has not been initialized, and you need to issue
- * the getEffectiveAddress() call and use the result of that.
- *
- * This is an optimization used by the GetDirectBufferAddress JNI call.
+ * For direct buffers, the effective address of the data; zero otherwise.
+ * This is set in the constructor.
+ * TODO: make this final at the cost of loads of extra constructors? [how many?]
*/
- int effectiveDirectAddress = 0;
- // END android-added
+ int effectiveDirectAddress;
/**
- * Construct a buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of this buffer
+ * For direct buffers, the underlying MemoryBlock; null otherwise.
*/
- Buffer(int capacity) {
- super();
+ final MemoryBlock block;
+
+ Buffer(int elementSizeShift, int capacity, MemoryBlock block) {
+ this._elementSizeShift = elementSizeShift;
if (capacity < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("capacity < 0: " + capacity);
}
this.capacity = this.limit = capacity;
+ this.block = block;
}
/**
@@ -154,6 +148,31 @@
return capacity;
}
+ int checkGetBounds(int bytesPerElement, int length, int offset, int count) {
+ int byteCount = bytesPerElement * count;
+ if (offset < 0 || count < 0 || (long) offset + (long) count > length) {
+ throw new IndexOutOfBoundsException();
+ }
+ if (byteCount > remaining()) {
+ throw new BufferUnderflowException();
+ }
+ return byteCount;
+ }
+
+ int checkPutBounds(int bytesPerElement, int length, int offset, int count) {
+ int byteCount = bytesPerElement * count;
+ if (offset < 0 || count < 0 || (long) offset + (long) count > length) {
+ throw new IndexOutOfBoundsException();
+ }
+ if (byteCount > remaining()) {
+ throw new BufferOverflowException();
+ }
+ if (isReadOnly()) {
+ throw new ReadOnlyBufferException();
+ }
+ return byteCount;
+ }
+
/**
* Clears this buffer.
* <p>
@@ -247,6 +266,14 @@
* if <code>newLimit</code> is invalid.
*/
public final Buffer limit(int newLimit) {
+ limitImpl(newLimit);
+ return this;
+ }
+
+ /**
+ * Subverts the fact that limit(int) is final, for the benefit of MappedByteBufferAdapter.
+ */
+ void limitImpl(int newLimit) {
if (newLimit < 0 || newLimit > capacity) {
throw new IllegalArgumentException();
}
@@ -258,7 +285,6 @@
if ((mark != UNSET_MARK) && (mark > newLimit)) {
mark = UNSET_MARK;
}
- return this;
}
/**
@@ -295,6 +321,11 @@
* if <code>newPosition</code> is invalid.
*/
public final Buffer position(int newPosition) {
+ positionImpl(newPosition);
+ return this;
+ }
+
+ void positionImpl(int newPosition) {
if (newPosition < 0 || newPosition > limit) {
throw new IllegalArgumentException();
}
@@ -303,7 +334,6 @@
if ((mark != UNSET_MARK) && (mark > position)) {
mark = UNSET_MARK;
}
- return this;
}
/**
@@ -344,4 +374,16 @@
mark = UNSET_MARK;
return this;
}
+
+ @Override public String toString() {
+ StringBuilder buf = new StringBuilder();
+ buf.append(getClass().getName());
+ buf.append(", status: capacity=");
+ buf.append(capacity);
+ buf.append(" position=");
+ buf.append(position);
+ buf.append(" limit=");
+ buf.append(limit);
+ return buf.toString();
+ }
}
diff --git a/luni/src/main/java/java/nio/BufferFactory.java b/luni/src/main/java/java/nio/BufferFactory.java
deleted file mode 100644
index 6783d63..0000000
--- a/luni/src/main/java/java/nio/BufferFactory.java
+++ /dev/null
@@ -1,206 +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 java.nio;
-
-/**
- * Provide factory service of buffer classes.
- * <p>
- * Since all buffer impl classes are package private (except DirectByteBuffer),
- * this factory is the only entrance to access buffer functions from outside of
- * the impl package.
- * </p>
- */
-final class BufferFactory {
-
- /**
- * Returns a new byte buffer based on the specified byte array.
- *
- * @param array
- * The byte array
- * @return A new byte buffer based on the specified byte array.
- */
- public static ByteBuffer newByteBuffer(byte[] array) {
- return new ReadWriteHeapByteBuffer(array);
- }
-
- /**
- * Returns a new array based byte buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based byte buffer with the specified capacity.
- */
- public static ByteBuffer newByteBuffer(int capacity) {
- return new ReadWriteHeapByteBuffer(capacity);
- }
-
- /**
- * Returns a new char buffer based on the specified char array.
- *
- * @param array
- * The char array
- * @return A new char buffer based on the specified char array.
- */
- public static CharBuffer newCharBuffer(char[] array) {
- return new ReadWriteCharArrayBuffer(array);
- }
-
- /**
- * Returns a new readonly char buffer based on the specified char sequence.
- *
- * @param chseq
- * The char sequence
- * @return A new readonly char buffer based on the specified char sequence.
- */
- public static CharBuffer newCharBuffer(CharSequence chseq) {
- return new CharSequenceAdapter(chseq);
- }
-
- /**
- * Returns a new array based char buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based char buffer with the specified capacity.
- */
- public static CharBuffer newCharBuffer(int capacity) {
- return new ReadWriteCharArrayBuffer(capacity);
- }
-
- /**
- * Returns a new direct byte buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new direct byte buffer with the specified capacity.
- */
- public static ByteBuffer newDirectByteBuffer(int capacity) {
- return new ReadWriteDirectByteBuffer(capacity);
- }
-
- /**
- * Returns a new double buffer based on the specified double array.
- *
- * @param array
- * The double array
- * @return A new double buffer based on the specified double array.
- */
- public static DoubleBuffer newDoubleBuffer(double[] array) {
- return new ReadWriteDoubleArrayBuffer(array);
- }
-
- /**
- * Returns a new array based double buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based double buffer with the specified capacity.
- */
- public static DoubleBuffer newDoubleBuffer(int capacity) {
- return new ReadWriteDoubleArrayBuffer(capacity);
- }
-
- /**
- * Returns a new float buffer based on the specified float array.
- *
- * @param array
- * The float array
- * @return A new float buffer based on the specified float array.
- */
- public static FloatBuffer newFloatBuffer(float[] array) {
- return new ReadWriteFloatArrayBuffer(array);
- }
-
- /**
- * Returns a new array based float buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based float buffer with the specified capacity.
- */
- public static FloatBuffer newFloatBuffer(int capacity) {
- return new ReadWriteFloatArrayBuffer(capacity);
- }
-
- /**
- * Returns a new array based int buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based int buffer with the specified capacity.
- */
- public static IntBuffer newIntBuffer(int capacity) {
- return new ReadWriteIntArrayBuffer(capacity);
- }
-
- /**
- * Returns a new int buffer based on the specified int array.
- *
- * @param array
- * The int array
- * @return A new int buffer based on the specified int array.
- */
- public static IntBuffer newIntBuffer(int[] array) {
- return new ReadWriteIntArrayBuffer(array);
- }
-
- /**
- * Returns a new array based long buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based long buffer with the specified capacity.
- */
- public static LongBuffer newLongBuffer(int capacity) {
- return new ReadWriteLongArrayBuffer(capacity);
- }
-
- /**
- * Returns a new long buffer based on the specified long array.
- *
- * @param array
- * The long array
- * @return A new long buffer based on the specified long array.
- */
- public static LongBuffer newLongBuffer(long[] array) {
- return new ReadWriteLongArrayBuffer(array);
- }
-
- /**
- * Returns a new array based short buffer with the specified capacity.
- *
- * @param capacity
- * The capacity of the new buffer
- * @return A new array based short buffer with the specified capacity.
- */
- public static ShortBuffer newShortBuffer(int capacity) {
- return new ReadWriteShortArrayBuffer(capacity);
- }
-
- /**
- * Returns a new short buffer based on the specified short array.
- *
- * @param array
- * The short array
- * @return A new short buffer based on the specified short array.
- */
- public static ShortBuffer newShortBuffer(short[] array) {
- return new ReadWriteShortArrayBuffer(array);
- }
-
-}
diff --git a/luni/src/main/java/java/nio/ByteBuffer.java b/luni/src/main/java/java/nio/ByteBuffer.java
index e83a709..1258ac6 100644
--- a/luni/src/main/java/java/nio/ByteBuffer.java
+++ b/luni/src/main/java/java/nio/ByteBuffer.java
@@ -46,7 +46,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newByteBuffer(capacity);
+ return new ReadWriteHeapByteBuffer(capacity);
}
/**
@@ -62,7 +62,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newDirectByteBuffer(capacity);
+ return new ReadWriteDirectByteBuffer(capacity);
}
/**
@@ -76,37 +76,35 @@
* @return the created byte buffer.
*/
public static ByteBuffer wrap(byte[] array) {
- return BufferFactory.newByteBuffer(array);
+ return new ReadWriteHeapByteBuffer(array);
}
/**
* Creates a new byte buffer by wrapping the given byte array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + byteCount}, capacity will be the length of the array.
*
* @param array
* the byte array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}.
- * @param len
+ * @param byteCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created byte buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code byteCount} is invalid.
*/
- public static ByteBuffer wrap(byte[] array, int start, int len) {
+ public static ByteBuffer wrap(byte[] array, int start, int byteCount) {
int length = array.length;
- if ((start < 0) || (len < 0) || ((long) start + (long) len > length)) {
+ if (start < 0 || byteCount < 0 || (long) start + (long) byteCount > length) {
throw new IndexOutOfBoundsException();
}
-
- ByteBuffer buf = BufferFactory.newByteBuffer(array);
+ ByteBuffer buf = new ReadWriteHeapByteBuffer(array);
buf.position = start;
- buf.limit = start + len;
-
+ buf.limit = start + byteCount;
return buf;
}
@@ -115,15 +113,8 @@
*/
ByteOrder order = ByteOrder.BIG_ENDIAN;
- /**
- * Constructs a {@code ByteBuffer} with given capacity.
- *
- * @param capacity
- * the capacity of the buffer.
- */
- ByteBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 0;
+ ByteBuffer(int capacity, MemoryBlock block) {
+ super(0, capacity, block);
}
/**
@@ -282,7 +273,7 @@
* {@code remaining()}; the limit is set to capacity; the mark is
* cleared.
*
- * @return this buffer.
+ * @return {@code this}
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
@@ -385,7 +376,7 @@
*
* @param dst
* the destination byte array.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferUnderflowException
* if {@code dst.length} is greater than {@code remaining()}.
*/
@@ -400,28 +391,25 @@
*
* @param dst
* the target byte array.
- * @param off
+ * @param dstOffset
* the offset of the byte array, must not be negative and
* not greater than {@code dst.length}.
- * @param len
+ * @param byteCount
* the number of bytes to read, must not be negative and not
- * greater than {@code dst.length - off}
- * @return this buffer.
- * @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
- * @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * greater than {@code dst.length - dstOffset}
+ * @return {@code this}
+ * @exception IndexOutOfBoundsException if {@code dstOffset < 0 || byteCount < 0}
+ * @exception BufferUnderflowException if {@code byteCount > remaining()}
*/
- public ByteBuffer get(byte[] dst, int off, int len) {
+ public ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
int length = dst.length;
- if ((off < 0) || (len < 0) || ((long) off + (long) len > length)) {
+ if (dstOffset < 0 || byteCount < 0 || (long) dstOffset + (long) byteCount > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (byteCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + byteCount; ++i) {
dst[i] = get();
}
return this;
@@ -655,19 +643,22 @@
* @param byteOrder
* the byte order to set. If {@code null} then the order
* will be {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN}.
- * @return this buffer.
+ * @return {@code this}
* @see ByteOrder
*/
public final ByteBuffer order(ByteOrder byteOrder) {
- return orderImpl(byteOrder);
+ orderImpl(byteOrder);
+ return this;
}
- ByteBuffer orderImpl(ByteOrder byteOrder) {
+ /**
+ * Subverts the fact that order(ByteOrder) is final, for the benefit of MappedByteBufferAdapter.
+ */
+ void orderImpl(ByteOrder byteOrder) {
if (byteOrder == null) {
byteOrder = ByteOrder.LITTLE_ENDIAN;
}
order = byteOrder;
- return this;
}
/**
@@ -697,7 +688,7 @@
*
* @param b
* the byte to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is equal or greater than limit.
* @exception ReadOnlyBufferException
@@ -714,7 +705,7 @@
*
* @param src
* the source byte array.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if {@code remaining()} is less than {@code src.length}.
* @exception ReadOnlyBufferException
@@ -731,30 +722,29 @@
*
* @param src
* the source byte array.
- * @param off
+ * @param srcOffset
* the offset of byte array, must not be negative and not greater
* than {@code src.length}.
- * @param len
+ * @param byteCount
* the number of bytes to write, must not be negative and not
- * greater than {@code src.length - off}.
- * @return this buffer.
+ * greater than {@code src.length - srcOffset}.
+ * @return {@code this}
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code byteCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code byteCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public ByteBuffer put(byte[] src, int off, int len) {
+ public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
int length = src.length;
- if ((off < 0 ) || (len < 0) || ((long)off + (long)len > length)) {
+ if (srcOffset < 0 || byteCount < 0 || (long) srcOffset + (long) byteCount > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (byteCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + byteCount; ++i) {
put(src[i]);
}
return this;
@@ -767,7 +757,7 @@
*
* @param src
* the source byte buffer.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if {@code src.remaining()} is greater than this buffer's
* {@code remaining()}.
@@ -797,7 +787,7 @@
* the index, must not be negative and less than the limit.
* @param b
* the byte to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -813,7 +803,7 @@
*
* @param value
* the char to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is greater than {@code limit - 2}.
* @exception ReadOnlyBufferException
@@ -832,7 +822,7 @@
* {@code limit - 2}.
* @param value
* the char to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -848,7 +838,7 @@
*
* @param value
* the double to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is greater than {@code limit - 8}.
* @exception ReadOnlyBufferException
@@ -867,7 +857,7 @@
* {@code limit - 8}.
* @param value
* the double to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -883,7 +873,7 @@
*
* @param value
* the float to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is greater than {@code limit - 4}.
* @exception ReadOnlyBufferException
@@ -902,7 +892,7 @@
* {@code limit - 4}.
* @param value
* the float to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -918,7 +908,7 @@
*
* @param value
* the int to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is greater than {@code limit - 4}.
* @exception ReadOnlyBufferException
@@ -937,7 +927,7 @@
* {@code limit - 4}.
* @param value
* the int to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -953,7 +943,7 @@
*
* @param value
* the long to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is greater than {@code limit - 8}.
* @exception ReadOnlyBufferException
@@ -972,7 +962,7 @@
* {@code limit - 8}.
* @param value
* the long to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -988,7 +978,7 @@
*
* @param value
* the short to write.
- * @return this buffer.
+ * @return {@code this}
* @exception BufferOverflowException
* if position is greater than {@code limit - 2}.
* @exception ReadOnlyBufferException
@@ -1007,7 +997,7 @@
* {@code limit - 2}.
* @param value
* the short to write.
- * @return this buffer.
+ * @return {@code this}
* @exception IndexOutOfBoundsException
* if {@code index} is invalid.
* @exception ReadOnlyBufferException
@@ -1031,22 +1021,4 @@
* @return a sliced buffer that shares its content with this buffer.
*/
public abstract ByteBuffer slice();
-
- /**
- * Returns a string representing the state of this byte buffer.
- *
- * @return a string representing the state of this byte buffer.
- */
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append(getClass().getName());
- buf.append(", status: capacity=");
- buf.append(capacity());
- buf.append(" position=");
- buf.append(position());
- buf.append(" limit=");
- buf.append(limit());
- return buf.toString();
- }
}
diff --git a/luni/src/main/java/java/nio/ByteOrder.java b/luni/src/main/java/java/nio/ByteOrder.java
index 5e9a19a..286c970 100644
--- a/luni/src/main/java/java/nio/ByteOrder.java
+++ b/luni/src/main/java/java/nio/ByteOrder.java
@@ -20,24 +20,40 @@
* Defines byte order constants.
*/
public final class ByteOrder {
+ private static final ByteOrder NATIVE_ORDER;
+
/**
* This constant represents big endian.
*/
- public static final ByteOrder BIG_ENDIAN = new ByteOrder("BIG_ENDIAN");
+ public static final ByteOrder BIG_ENDIAN;
/**
* This constant represents little endian.
*/
- public static final ByteOrder LITTLE_ENDIAN = new ByteOrder("LITTLE_ENDIAN");
-
- private static final ByteOrder NATIVE_ORDER = isLittleEndian() ? LITTLE_ENDIAN : BIG_ENDIAN;
+ public static final ByteOrder LITTLE_ENDIAN;
private static native boolean isLittleEndian();
+ static {
+ boolean isLittleEndian = isLittleEndian();
+ BIG_ENDIAN = new ByteOrder("BIG_ENDIAN", isLittleEndian);
+ LITTLE_ENDIAN = new ByteOrder("LITTLE_ENDIAN", !isLittleEndian);
+ NATIVE_ORDER = isLittleEndian ? LITTLE_ENDIAN : BIG_ENDIAN;
+ }
+
private final String name;
- private ByteOrder(String name) {
+ /**
+ * 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.
+ */
+ public final boolean needsSwap;
+
+ private ByteOrder(String name, boolean needsSwap) {
this.name = name;
+ this.needsSwap = needsSwap;
}
/**
diff --git a/luni/src/main/java/java/nio/CharArrayBuffer.java b/luni/src/main/java/java/nio/CharArrayBuffer.java
index d7b2267..4a7c149 100644
--- a/luni/src/main/java/java/nio/CharArrayBuffer.java
+++ b/luni/src/main/java/java/nio/CharArrayBuffer.java
@@ -66,16 +66,16 @@
}
@Override
- public final CharBuffer get(char[] dst, int off, int len) {
+ public final CharBuffer get(char[] dst, int srcOffset, int charCount) {
int length = dst.length;
- if ((off < 0) || (len < 0) || (long) off + (long) len > length) {
+ if (srcOffset < 0 || charCount < 0 || (long) srcOffset + (long) charCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (charCount > remaining()) {
throw new BufferUnderflowException();
}
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ System.arraycopy(backingArray, offset + position, dst, srcOffset, charCount);
+ position += charCount;
return this;
}
diff --git a/luni/src/main/java/java/nio/CharBuffer.java b/luni/src/main/java/java/nio/CharBuffer.java
index 467e08f..bc7a935 100644
--- a/luni/src/main/java/java/nio/CharBuffer.java
+++ b/luni/src/main/java/java/nio/CharBuffer.java
@@ -50,7 +50,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newCharBuffer(capacity);
+ return new ReadWriteCharArrayBuffer(capacity);
}
/**
@@ -71,30 +71,28 @@
* Creates a new char buffer by wrapping the given char array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + charCount}, capacity will be the length of the array.
*
* @param array
* the char array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}.
- * @param len
+ * @param charCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created char buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code charCount} is invalid.
*/
- public static CharBuffer wrap(char[] array, int start, int len) {
+ public static CharBuffer wrap(char[] array, int start, int charCount) {
int length = array.length;
- if ((start < 0) || (len < 0) || (long) start + (long) len > length) {
+ if (start < 0 || charCount < 0 || (long) start + (long) charCount > length) {
throw new IndexOutOfBoundsException();
}
-
- CharBuffer buf = BufferFactory.newCharBuffer(array);
+ CharBuffer buf = new ReadWriteCharArrayBuffer(array);
buf.position = start;
- buf.limit = start + len;
-
+ buf.limit = start + charCount;
return buf;
}
@@ -109,7 +107,7 @@
* @return the created char buffer.
*/
public static CharBuffer wrap(CharSequence chseq) {
- return BufferFactory.newCharBuffer(chseq);
+ return new CharSequenceAdapter(chseq);
}
/**
@@ -139,21 +137,14 @@
throw new IndexOutOfBoundsException();
}
- CharBuffer result = BufferFactory.newCharBuffer(chseq);
+ CharBuffer result = new CharSequenceAdapter(chseq);
result.position = start;
result.limit = end;
return result;
}
- /**
- * Constructs a {@code CharBuffer} with given capacity.
- *
- * @param capacity
- * the capacity of the buffer.
- */
CharBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 1;
+ super(1, capacity, null);
}
public final char[] array() {
@@ -324,28 +315,27 @@
*
* @param dst
* the target char array.
- * @param off
+ * @param dstOffset
* the offset of the char array, must not be negative and not
* greater than {@code dst.length}.
- * @param len
+ * @param charCount
* The number of chars to read, must be no less than zero and no
- * greater than {@code dst.length - off}.
+ * greater than {@code dst.length - dstOffset}.
* @return this buffer.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code dstOffset} or {@code charCount} is invalid.
* @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * if {@code charCount} is greater than {@code remaining()}.
*/
- public CharBuffer get(char[] dst, int off, int len) {
+ public CharBuffer get(char[] dst, int dstOffset, int charCount) {
int length = dst.length;
- if ((off < 0) || (len < 0) || (long) off + (long) len > length) {
+ if (dstOffset < 0 || charCount < 0 || (long) dstOffset + (long) charCount > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (charCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + charCount; ++i) {
dst[i] = get();
}
return this;
@@ -476,30 +466,30 @@
*
* @param src
* the source char array.
- * @param off
+ * @param srcOffset
* the offset of char array, must not be negative and not greater
* than {@code src.length}.
- * @param len
+ * @param charCount
* the number of chars to write, must be no less than zero and no
- * greater than {@code src.length - off}.
+ * greater than {@code src.length - srcOffset}.
* @return this buffer.
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code charCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code charCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public CharBuffer put(char[] src, int off, int len) {
+ public CharBuffer put(char[] src, int srcOffset, int charCount) {
int length = src.length;
- if ((off < 0) || (len < 0) || (long) off + (long) len > length) {
+ if (srcOffset < 0 || charCount < 0 || (long) srcOffset + (long) charCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (charCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + charCount; ++i) {
put(src[i]);
}
return this;
diff --git a/luni/src/main/java/java/nio/CharSequenceAdapter.java b/luni/src/main/java/java/nio/CharSequenceAdapter.java
index 5ea0657..6287d47 100644
--- a/luni/src/main/java/java/nio/CharSequenceAdapter.java
+++ b/luni/src/main/java/java/nio/CharSequenceAdapter.java
@@ -76,16 +76,16 @@
}
@Override
- public final CharBuffer get(char[] dst, int off, int len) {
+ public final CharBuffer get(char[] dst, int dstOffset, int charCount) {
int length = dst.length;
- if ((off < 0) || (len < 0) || (long) off + (long) len > length) {
+ if (dstOffset < 0 || charCount < 0 || (long) dstOffset + (long) charCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (charCount > remaining()) {
throw new BufferUnderflowException();
}
- int newPosition = position + len;
- sequence.toString().getChars(position, newPosition, dst, off);
+ int newPosition = position + charCount;
+ sequence.toString().getChars(position, newPosition, dst, dstOffset);
position = newPosition;
return this;
}
@@ -131,12 +131,12 @@
}
@Override
- public final CharBuffer put(char[] src, int off, int len) {
- if ((off < 0) || (len < 0) || (long) off + (long) len > src.length) {
+ public final CharBuffer put(char[] src, int srcOffset, int charCount) {
+ if (srcOffset < 0 || charCount < 0 || (long) srcOffset + (long) charCount > src.length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (charCount > remaining()) {
throw new BufferOverflowException();
}
@@ -145,8 +145,7 @@
@Override
public CharBuffer put(String src, int start, int end) {
- if ((start < 0) || (end < 0)
- || (long) start + (long) end > src.length()) {
+ if (start < 0 || end < 0 || (long) start + (long) end > src.length()) {
throw new IndexOutOfBoundsException();
}
throw new ReadOnlyBufferException();
diff --git a/luni/src/main/java/java/nio/CharToByteBufferAdapter.java b/luni/src/main/java/java/nio/CharToByteBufferAdapter.java
index f38215a..4a6d920 100644
--- a/luni/src/main/java/java/nio/CharToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/CharToByteBufferAdapter.java
@@ -16,8 +16,7 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a char buffer.
@@ -32,76 +31,26 @@
* </p>
*
*/
-final class CharToByteBufferAdapter extends CharBuffer implements DirectBuffer {
-
- static CharBuffer wrap(ByteBuffer byteBuffer) {
- return new CharToByteBufferAdapter(byteBuffer.slice());
- }
+final class CharToByteBufferAdapter extends CharBuffer {
private final ByteBuffer byteBuffer;
- CharToByteBufferAdapter(ByteBuffer byteBuffer) {
- super((byteBuffer.capacity() >> 1));
+ 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();
- }
-
- public int getByteCapacity() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getByteCapacity();
- }
- assert false : byteBuffer;
- return -1;
- }
-
- public PlatformAddress getEffectiveAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer)byteBuffer).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
- assert false : byteBuffer;
- return null;
- }
-
- public PlatformAddress getBaseAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getBaseAddress();
- }
- assert false : byteBuffer;
- return null;
- }
-
- public boolean isAddressValid() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).isAddressValid();
- }
- assert false : byteBuffer;
- return false;
- }
-
- public void addressValidityCheck() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).addressValidityCheck();
- } else {
- assert false : byteBuffer;
- }
- }
-
- public void free() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).free();
- } else {
- assert false : byteBuffer;
- }
+ this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public CharBuffer asReadOnlyBuffer() {
- CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer
- .asReadOnlyBuffer());
+ CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -113,8 +62,8 @@
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- byteBuffer.limit(limit << 1);
- byteBuffer.position(position << 1);
+ byteBuffer.limit(limit * SizeOf.CHAR);
+ byteBuffer.position(position * SizeOf.CHAR);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
@@ -125,8 +74,7 @@
@Override
public CharBuffer duplicate() {
- CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer
- .duplicate());
+ CharToByteBufferAdapter buf = new CharToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -138,7 +86,7 @@
if (position == limit) {
throw new BufferUnderflowException();
}
- return byteBuffer.getChar(position++ << 1);
+ return byteBuffer.getChar(position++ * SizeOf.CHAR);
}
@Override
@@ -146,7 +94,20 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return byteBuffer.getChar(index << 1);
+ 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);
+ if (byteBuffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, charCount);
+ } else {
+ ((HeapByteBuffer) byteBuffer).get(dst, dstOffset, charCount);
+ }
+ this.position += charCount;
+ return this;
}
@Override
@@ -184,7 +145,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- byteBuffer.putChar(position++ << 1, c);
+ byteBuffer.putChar(position++ * SizeOf.CHAR, c);
return this;
}
@@ -193,14 +154,27 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- byteBuffer.putChar(index << 1, 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);
+ if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
+ ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, charCount);
+ } else {
+ ((ReadWriteHeapByteBuffer) byteBuffer).put(src, srcOffset, charCount);
+ }
+ this.position += charCount;
return this;
}
@Override
public CharBuffer slice() {
- byteBuffer.limit(limit << 1);
- byteBuffer.position(position << 1);
+ 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/org/apache/harmony/nio/internal/DatagramChannelImpl.java b/luni/src/main/java/java/nio/DatagramChannelImpl.java
similarity index 91%
rename from luni/src/main/java/org/apache/harmony/nio/internal/DatagramChannelImpl.java
rename to luni/src/main/java/java/nio/DatagramChannelImpl.java
index 093551a..7750830 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/DatagramChannelImpl.java
+++ b/luni/src/main/java/java/nio/DatagramChannelImpl.java
@@ -15,11 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
-
-// BEGIN android-note
-// In this class the address length was changed from long to int.
-// END android-note
+package java.nio;
import java.io.FileDescriptor;
import java.io.IOException;
@@ -32,7 +28,6 @@
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
-import java.nio.ByteBuffer;
import java.nio.channels.AlreadyConnectedException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
@@ -43,20 +38,15 @@
import org.apache.harmony.luni.platform.FileDescriptorHandler;
import org.apache.harmony.luni.platform.INetworkSystem;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.nio.AddressUtil;
/*
* The default implementation class of java.nio.channels.DatagramChannel.
*/
class DatagramChannelImpl extends DatagramChannel implements FileDescriptorHandler {
-
- // The singleton to do the native network operation.
- private static final INetworkSystem networkSystem = Platform.getNetworkSystem();
-
private static final byte[] stubArray = new byte[0];
// The fd to interact with native code
- private FileDescriptor fd;
+ private final FileDescriptor fd;
// Our internal DatagramSocket.
private DatagramSocket socket = null;
@@ -73,11 +63,8 @@
// whether the socket is bound
boolean isBound = false;
- private static class ReadLock {}
- private final Object readLock = new ReadLock();
-
- private static class WriteLock {}
- private final Object writeLock = new WriteLock();
+ private final Object readLock = new Object();
+ private final Object writeLock = new Object();
/*
* Constructor
@@ -85,7 +72,7 @@
protected DatagramChannelImpl(SelectorProvider selectorProvider) throws IOException {
super(selectorProvider);
fd = new FileDescriptor();
- networkSystem.socket(fd, false);
+ Platform.NETWORK.socket(fd, false);
}
/*
@@ -118,7 +105,7 @@
* @see DatagramSocket
*/
InetAddress getLocalAddress() {
- return networkSystem.getSocketLocalAddress(fd);
+ return Platform.NETWORK.getSocketLocalAddress(fd);
}
/**
@@ -157,7 +144,7 @@
try {
begin();
- networkSystem.connect(fd,
+ Platform.NETWORK.connect(fd,
inetSocketAddress.getAddress(), inetSocketAddress.getPort(), 0);
} catch (ConnectException e) {
// ConnectException means connect fail, not exception
@@ -182,7 +169,7 @@
}
connected = false;
connectAddress = null;
- networkSystem.disconnectDatagram(fd);
+ Platform.NETWORK.disconnectDatagram(fd);
if (null != socket) {
socket.disconnect();
}
@@ -234,7 +221,7 @@
target.remaining());
}
do {
- received = networkSystem.recv(fd, receivePacket,
+ received = Platform.NETWORK.recv(fd, receivePacket,
receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength(),
false, isConnected());
@@ -272,8 +259,8 @@
int oldposition = target.position();
int received = 0;
do {
- int address = AddressUtil.getDirectBufferAddress(target);
- received = networkSystem.recvDirect(fd, receivePacket, address,
+ int address = NioUtils.getDirectBufferAddress(target);
+ received = Platform.NETWORK.recvDirect(fd, receivePacket, address,
target.position(), target.remaining(), false, isConnected());
// security check
@@ -342,8 +329,8 @@
int start = oldposition;
if (source.isDirect()) {
synchronized (writeLock) {
- int data_address = AddressUtil.getDirectBufferAddress(source);
- sendCount = networkSystem.sendDirect(fd, data_address, start, length,
+ int data_address = NioUtils.getDirectBufferAddress(source);
+ sendCount = Platform.NETWORK.sendDirect(fd, data_address, start, length,
isa.getPort(), isa.getAddress());
}
} else {
@@ -356,7 +343,7 @@
start = 0;
}
synchronized (writeLock) {
- sendCount = networkSystem.send(fd, array, start, length,
+ sendCount = Platform.NETWORK.send(fd, array, start, length,
isa.getPort(), isa.getAddress());
}
}
@@ -436,14 +423,14 @@
int start = readBuffer.position();
int length = readBuffer.remaining();
if (readBuffer.isDirect()) {
- int address = AddressUtil.getDirectBufferAddress(readBuffer);
- readCount = networkSystem.recvDirect(fd, null, address, start, length,
+ int address = NioUtils.getDirectBufferAddress(readBuffer);
+ readCount = Platform.NETWORK.recvDirect(fd, null, address, start, length,
false, isConnected());
} else {
// the target is assured to have array.
byte[] target = readBuffer.array();
start += readBuffer.arrayOffset();
- readCount = networkSystem.recv(fd, null, target, start, length, false,
+ readCount = Platform.NETWORK.recv(fd, null, target, start, length, false,
isConnected());
}
return readCount;
@@ -538,12 +525,12 @@
int start = buf.position();
if (buf.isDirect()) {
- int address = AddressUtil.getDirectBufferAddress(buf);
- result = networkSystem.sendDirect(fd, address, start, length, 0, null);
+ int address = NioUtils.getDirectBufferAddress(buf);
+ result = Platform.NETWORK.sendDirect(fd, address, start, length, 0, null);
} else {
// buf is assured to have array.
start += buf.arrayOffset();
- result = networkSystem.send(fd, buf.array(), start, length, 0, null);
+ result = Platform.NETWORK.send(fd, buf.array(), start, length, 0, null);
}
return result;
} finally {
@@ -556,12 +543,12 @@
* Do really closing action here.
*/
@Override
- synchronized protected void implCloseSelectableChannel() throws IOException {
+ protected synchronized void implCloseSelectableChannel() throws IOException {
connected = false;
- if (null != socket && !socket.isClosed()) {
+ if (socket != null && !socket.isClosed()) {
socket.close();
} else {
- networkSystem.close(fd);
+ Platform.NETWORK.close(fd);
}
}
diff --git a/luni/src/main/java/java/nio/DirectByteBuffer.java b/luni/src/main/java/java/nio/DirectByteBuffer.java
index 95fe90f..f9097c1 100644
--- a/luni/src/main/java/java/nio/DirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/DirectByteBuffer.java
@@ -17,99 +17,75 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.luni.platform.PlatformAddressFactory;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
-/**
- * DirectByteBuffer, ReadWriteDirectByteBuffer and ReadOnlyDirectByteBuffer
- * compose the implementation of platform memory based byte buffers.
- * <p>
- * DirectByteBuffer implements all the shared readonly methods and is extended
- * by the other two classes.
- * </p>
- * <p>
- * All methods are marked final for runtime performance.
- * </p>
- *
- */
-abstract class DirectByteBuffer extends BaseByteBuffer implements DirectBuffer {
-
- // This class will help us track whether the address is valid or not.
- static final class SafeAddress {
- protected volatile boolean isValid = true;
-
- protected final PlatformAddress address;
-
- protected SafeAddress(PlatformAddress address) {
- super();
- this.address = address;
- }
- }
-
- // This is a wrapped reference to the base address of the buffer memory.
- protected final SafeAddress safeAddress;
-
- // This is the offset from the base address at which this buffer logically
- // starts.
+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?
protected final int offset;
- /*
- * Constructs a new direct byte buffer of the given capacity on newly
- * allocated OS memory. The memory will have been zeroed. When the instance
- * is discarded the OS memory will be freed if it has not already been done
- * so by an explicit call to #free(). Callers are encouraged to explicitly
- * free the memory where possible.
- */
- DirectByteBuffer(int capacity) {
- this(new SafeAddress(PlatformAddressFactory.alloc(capacity, (byte) 0)),
- capacity, 0);
- safeAddress.address.autoFree();
- }
+ protected DirectByteBuffer(MemoryBlock block, int capacity, int offset) {
+ super(capacity, block);
- DirectByteBuffer(SafeAddress address, int capacity, int offset) {
- super(capacity);
-
- // BEGIN android-added
- PlatformAddress baseAddress = address.address;
- long baseSize = baseAddress.getSize();
-
- if ((baseSize >= 0) && ((offset + capacity) > baseSize)) {
- throw new IllegalArgumentException("slice out of range");
+ long baseSize = block.getSize();
+ if (baseSize >= 0 && (capacity + offset) > baseSize) {
+ throw new IllegalArgumentException("capacity + offset > baseSize");
}
- // END android-added
- this.safeAddress = address;
this.offset = offset;
+ this.effectiveDirectAddress = block.toInt() + offset;
}
- /*
- * Override ByteBuffer.get(byte[], int, int) to improve performance.
- *
- * (non-Javadoc)
- *
- * @see java.nio.ByteBuffer#get(byte[], int, int)
- */
@Override
- public final ByteBuffer get(byte[] dst, int off, int len) {
- int length = dst.length;
- if ((off < 0) || (len < 0) || (long) off + (long) len > length) {
- throw new IndexOutOfBoundsException();
- }
- if (len > remaining()) {
- throw new BufferUnderflowException();
- }
- getBaseAddress().getByteArray(offset + position, dst, off, len);
- position += len;
+ public final ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
+ checkGetBounds(1, dst.length, dstOffset, byteCount);
+ this.block.peekByteArray(offset + position, dst, dstOffset, byteCount);
+ position += byteCount;
return this;
}
+ final void get(char[] dst, int dstOffset, int 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ this.block.peekShortArray(offset + position, dst, dstOffset, shortCount, order.needsSwap);
+ position += byteCount;
+ }
+
@Override
public final byte get() {
if (position == limit) {
throw new BufferUnderflowException();
}
- return getBaseAddress().getByte(offset + position++);
+ return this.block.peekByte(offset + position++);
}
@Override
@@ -117,102 +93,121 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return getBaseAddress().getByte(offset + index);
+ return this.block.peekByte(offset + index);
+ }
+
+ @Override
+ public final char getChar() {
+ int newPosition = position + SizeOf.CHAR;
+ if (newPosition > limit) {
+ throw new BufferUnderflowException();
+ }
+ char result = (char) this.block.peekShort(offset + position, order);
+ position = newPosition;
+ return result;
+ }
+
+ @Override
+ public final char getChar(int index) {
+ if (index < 0 || (long) index + SizeOf.CHAR > limit) {
+ throw new IndexOutOfBoundsException();
+ }
+ return (char) this.block.peekShort(offset + index, order);
}
@Override
public final double getDouble() {
- int newPosition = position + 8;
+ int newPosition = position + SizeOf.DOUBLE;
if (newPosition > limit) {
throw new BufferUnderflowException();
}
- double result = getBaseAddress().getDouble(offset + position, order);
+ double result = Double.longBitsToDouble(this.block.peekLong(offset + position, order));
position = newPosition;
return result;
}
@Override
public final double getDouble(int index) {
- if (index < 0 || (long) index + 8 > limit) {
+ if (index < 0 || (long) index + SizeOf.DOUBLE > limit) {
throw new IndexOutOfBoundsException();
}
- return getBaseAddress().getDouble(offset + index, order);
+ return Double.longBitsToDouble(this.block.peekLong(offset + index, order));
}
@Override
public final float getFloat() {
- int newPosition = position + 4;
+ int newPosition = position + SizeOf.FLOAT;
if (newPosition > limit) {
throw new BufferUnderflowException();
}
- float result = getBaseAddress().getFloat(offset + position, order);
+ float result = Float.intBitsToFloat(this.block.peekInt(offset + position, order));
position = newPosition;
return result;
}
@Override
public final float getFloat(int index) {
- if (index < 0 || (long) index + 4 > limit) {
+ if (index < 0 || (long) index + SizeOf.FLOAT > limit) {
throw new IndexOutOfBoundsException();
}
- return getBaseAddress().getFloat(offset + index, order);
+ return Float.intBitsToFloat(this.block.peekInt(offset + index, order));
}
@Override
public final int getInt() {
- int newPosition = position + 4;
+ int newPosition = position + SizeOf.INT;
if (newPosition > limit) {
throw new BufferUnderflowException();
}
- int result = getBaseAddress().getInt(offset + position, order);
+ int result = this.block.peekInt(offset + position, order);
position = newPosition;
return result;
}
@Override
public final int getInt(int index) {
- if (index < 0 || (long) index + 4 > limit) {
+ if (index < 0 || (long) index + SizeOf.INT > limit) {
throw new IndexOutOfBoundsException();
}
- return getBaseAddress().getInt(offset + index, order);
+ return this.block.peekInt(offset + index, order);
}
@Override
public final long getLong() {
- int newPosition = position + 8;
+ int newPosition = position + SizeOf.LONG;
if (newPosition > limit) {
throw new BufferUnderflowException();
}
- long result = getBaseAddress().getLong(offset + position, order);
+ long result = this.block.peekLong(offset + position, order);
position = newPosition;
return result;
}
@Override
public final long getLong(int index) {
- if (index < 0 || (long) index + 8 > limit) {
+ if (index < 0 || (long) index + SizeOf.LONG > limit) {
throw new IndexOutOfBoundsException();
}
- return getBaseAddress().getLong(offset + index, order);
+ return this.block.peekLong(offset + index, order);
}
@Override
public final short getShort() {
- int newPosition = position + 2;
+ int newPosition = position + SizeOf.SHORT;
if (newPosition > limit) {
throw new BufferUnderflowException();
}
- short result = getBaseAddress().getShort(offset + position, order);
+ short result = this.block.peekShort(offset + position, order);
position = newPosition;
return result;
}
@Override
public final short getShort(int index) {
- if (index < 0 || (long) index + 2 > limit) {
+ if (index < 0 || (long) index + SizeOf.SHORT > limit) {
throw new IndexOutOfBoundsException();
}
- return getBaseAddress().getShort(offset + index, order);
+ return this.block.peekShort(offset + index, order);
}
@Override
@@ -220,68 +215,8 @@
return true;
}
- public final boolean isAddressValid() {
- return safeAddress.isValid;
- }
-
- public final void addressValidityCheck() {
- if (!isAddressValid()) {
- throw new IllegalStateException("Cannot use a direct byte buffer after it has been explicitly freed");
- }
- }
-
- private void markAddressInvalid() {
- safeAddress.isValid = false;
- }
-
- /*
- * Returns the base address of the buffer (i.e. before offset).
- */
- public final PlatformAddress getBaseAddress() {
- addressValidityCheck();
- return safeAddress.address;
- }
-
- /**
- * Returns the platform address of the start of this buffer instance.
- * <em>You must not attempt to free the returned address!!</em> It may not
- * be an address that was explicitly malloc'ed (i.e. if this buffer is the
- * result of a split); and it may be memory shared by multiple buffers.
- * <p>
- * If you can guarantee that you want to free the underlying memory call the
- * #free() method on this instance -- generally applications will rely on
- * the garbage collector to autofree this memory.
- * </p>
- *
- * @return the effective address of the start of the buffer.
- * @throws IllegalStateException
- * if this buffer address is known to have been freed
- * previously.
- */
- public final PlatformAddress getEffectiveAddress() {
- // BEGIN android-changed
- PlatformAddress addr = getBaseAddress().offsetBytes(offset);
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
-
- /**
- * Explicitly free the memory used by this direct byte buffer. If the memory
- * has already been freed then this is a no-op. Once the memory has been
- * freed then operations requiring access to the memory will throw an
- * <code>IllegalStateException</code>.
- * <p>
- * Note this is is possible that the memory is freed by code that reaches
- * into the address and explicitly frees it 'beneith' us -- this is bad
- * form.
- * </p>
- */
public final void free() {
- if (isAddressValid()) {
- markAddressInvalid();
- safeAddress.address.free();
- }
+ block.free();
}
@Override
@@ -298,8 +233,4 @@
final protected boolean protectedHasArray() {
return false;
}
-
- public final int getByteCapacity() {
- return capacity;
- }
}
diff --git a/luni/src/main/java/java/nio/DirectByteBuffers.java b/luni/src/main/java/java/nio/DirectByteBuffers.java
deleted file mode 100644
index 84a51ac..0000000
--- a/luni/src/main/java/java/nio/DirectByteBuffers.java
+++ /dev/null
@@ -1,81 +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 java.nio;
-
-import org.apache.harmony.luni.platform.PlatformAddress;
-
-/**
- * Helper class for operations on direct ByteBuffer
- *
- * @see java.nio.ByteBuffer
- */
-class DirectByteBuffers {
-
- /**
- * Explicitly frees the memory used by the given direct byte buffer.
- * <p>
- * If the memory is known to already have been freed then this is a no-op.
- * Once the memory has been freed then operations requiring access to the
- * memory will throw an <code>IllegalStateException</code>.
- * <p>
- * Note this is is possible that the memory is freed by code that reaches
- * into the address and explicitly frees it 'beneith' us -- this is bad
- * form.
- *
- * @param directBuffer
- * the direct byte buffer memory to free
- * @throws IllegalArgumentException
- * if the buffer is <code>null</code> or is not a
- * <em>direct</em> byte buffer.
- */
- public static void free(ByteBuffer directBuffer) {
- if ((directBuffer == null) || (!directBuffer.isDirect())) {
- throw new IllegalArgumentException();
- }
- DirectByteBuffer buf = (DirectByteBuffer) directBuffer;
- buf.free();
- }
-
- /**
- * Returns the platform address of the start of this buffer instance.
- * <em>You must not attempt to free the returned address!!</em> It may not
- * be an address that was explicitly malloc'ed (i.e. if this buffer is the
- * result of a split); and it may be memory shared by multiple buffers.
- * <p>
- * If you can guarantee that you want to free the underlying memory call the
- * #free() method on this instance -- generally applications will rely on
- * the garbage collector to autofree this memory.
- *
- * @param directBuffer
- * the direct byte buffer
- * @return the effective address of the start of the buffer.
- * @throws IllegalStateException
- * if this buffer address is known to have been freed
- * previously.
- */
- public static PlatformAddress getEffectiveAddress(ByteBuffer directBuffer) {
- return toDirectBuffer(directBuffer).getEffectiveAddress();
- }
-
- private static DirectByteBuffer toDirectBuffer(ByteBuffer directBuffer) {
- if ((directBuffer == null) || (!directBuffer.isDirect())) {
- throw new IllegalArgumentException();
- }
- return (DirectByteBuffer) directBuffer;
- }
-
-}
diff --git a/luni/src/main/java/java/nio/DoubleArrayBuffer.java b/luni/src/main/java/java/nio/DoubleArrayBuffer.java
index 4c7b86e..fcdf287 100644
--- a/luni/src/main/java/java/nio/DoubleArrayBuffer.java
+++ b/luni/src/main/java/java/nio/DoubleArrayBuffer.java
@@ -66,16 +66,16 @@
}
@Override
- public final DoubleBuffer get(double[] dst, int off, int len) {
+ public final DoubleBuffer get(double[] dst, int dstOffset, int doubleCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (dstOffset < 0 || doubleCount < 0 || (long) dstOffset + (long) doubleCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (doubleCount > remaining()) {
throw new BufferUnderflowException();
}
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ System.arraycopy(backingArray, offset + position, dst, dstOffset, doubleCount);
+ position += doubleCount;
return this;
}
diff --git a/luni/src/main/java/java/nio/DoubleBuffer.java b/luni/src/main/java/java/nio/DoubleBuffer.java
index 93f2b87..67713e8 100644
--- a/luni/src/main/java/java/nio/DoubleBuffer.java
+++ b/luni/src/main/java/java/nio/DoubleBuffer.java
@@ -47,7 +47,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newDoubleBuffer(capacity);
+ return new ReadWriteDoubleArrayBuffer(capacity);
}
/**
@@ -68,42 +68,35 @@
* Creates a new double buffer by wrapping the given double array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + doubleCount}, capacity will be the length of the array.
*
* @param array
* the double array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}.
- * @param len
+ * @param doubleCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created double buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code doubleCount} is invalid.
*/
- public static DoubleBuffer wrap(double[] array, int start, int len) {
+ public static DoubleBuffer wrap(double[] array, int start, int doubleCount) {
int length = array.length;
- if (start < 0 || len < 0 || (long) start + (long) len > length) {
+ if (start < 0 || doubleCount < 0 || (long) start + (long) doubleCount > length) {
throw new IndexOutOfBoundsException();
}
- DoubleBuffer buf = BufferFactory.newDoubleBuffer(array);
+ DoubleBuffer buf = new ReadWriteDoubleArrayBuffer(array);
buf.position = start;
- buf.limit = start + len;
+ buf.limit = start + doubleCount;
return buf;
}
- /**
- * Constructs a {@code DoubleBuffer} with given capacity.
- *
- * @param capacity
- * the capacity of the buffer.
- */
DoubleBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 3;
+ super(3, capacity, null);
}
public final double[] array() {
@@ -264,28 +257,28 @@
*
* @param dst
* the target double array.
- * @param off
+ * @param dstOffset
* the offset of the double array, must not be negative and not
* greater than {@code dst.length}.
- * @param len
+ * @param doubleCount
* the number of doubles to read, must be no less than zero and
- * not greater than {@code dst.length - off}.
+ * not greater than {@code dst.length - dstOffset}.
* @return this buffer.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code dstOffset} or {@code doubleCount} is invalid.
* @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * if {@code doubleCount} is greater than {@code remaining()}.
*/
- public DoubleBuffer get(double[] dst, int off, int len) {
+ public DoubleBuffer get(double[] dst, int dstOffset, int doubleCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (dstOffset < 0 || doubleCount < 0 || (long) dstOffset + (long) doubleCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (doubleCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + doubleCount; ++i) {
dst[i] = get();
}
return this;
@@ -409,30 +402,29 @@
*
* @param src
* the source double array.
- * @param off
+ * @param srcOffset
* the offset of double array, must not be negative and not
* greater than {@code src.length}.
- * @param len
+ * @param doubleCount
* the number of doubles to write, must be no less than zero and
- * not greater than {@code src.length - off}.
+ * not greater than {@code src.length - srcOffset}.
* @return this buffer.
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code doubleCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code doubleCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public DoubleBuffer put(double[] src, int off, int len) {
+ public DoubleBuffer put(double[] src, int srcOffset, int doubleCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || doubleCount < 0 || (long) srcOffset + (long) doubleCount > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (doubleCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + doubleCount; ++i) {
put(src[i]);
}
return this;
@@ -499,22 +491,4 @@
* @return a sliced buffer that shares its content with this buffer.
*/
public abstract DoubleBuffer slice();
-
- /**
- * Returns a string representing the state of this double buffer.
- *
- * @return A string representing the state of this double buffer.
- */
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append(getClass().getName());
- buf.append(", status: capacity=");
- buf.append(capacity());
- buf.append(" position=");
- buf.append(position());
- buf.append(" limit=");
- buf.append(limit());
- return buf.toString();
- }
}
diff --git a/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java b/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java
index a368dac..b5380ba 100644
--- a/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java
@@ -16,8 +16,7 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a double buffer.
@@ -32,77 +31,26 @@
* </p>
*
*/
-final class DoubleToByteBufferAdapter extends DoubleBuffer implements
- DirectBuffer {
-
- static DoubleBuffer wrap(ByteBuffer byteBuffer) {
- return new DoubleToByteBufferAdapter(byteBuffer.slice());
- }
+final class DoubleToByteBufferAdapter extends DoubleBuffer {
private final ByteBuffer byteBuffer;
- DoubleToByteBufferAdapter(ByteBuffer byteBuffer) {
- super((byteBuffer.capacity() >> 3));
+ 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();
- }
-
- public int getByteCapacity() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getByteCapacity();
- }
- assert false : byteBuffer;
- return -1;
- }
-
- public PlatformAddress getEffectiveAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer)byteBuffer).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
- assert false : byteBuffer;
- return null;
- }
-
- public PlatformAddress getBaseAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getBaseAddress();
- }
- assert false : byteBuffer;
- return null;
- }
-
- public boolean isAddressValid() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).isAddressValid();
- }
- assert false : byteBuffer;
- return false;
- }
-
- public void addressValidityCheck() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).addressValidityCheck();
- } else {
- assert false : byteBuffer;
- }
- }
-
- public void free() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).free();
- } else {
- assert false : byteBuffer;
- }
+ this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public DoubleBuffer asReadOnlyBuffer() {
- DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(
- byteBuffer.asReadOnlyBuffer());
+ DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -114,8 +62,8 @@
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- byteBuffer.limit(limit << 3);
- byteBuffer.position(position << 3);
+ byteBuffer.limit(limit * SizeOf.DOUBLE);
+ byteBuffer.position(position * SizeOf.DOUBLE);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
@@ -126,8 +74,7 @@
@Override
public DoubleBuffer duplicate() {
- DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(
- byteBuffer.duplicate());
+ DoubleToByteBufferAdapter buf = new DoubleToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -139,7 +86,7 @@
if (position == limit) {
throw new BufferUnderflowException();
}
- return byteBuffer.getDouble(position++ << 3);
+ return byteBuffer.getDouble(position++ * SizeOf.DOUBLE);
}
@Override
@@ -147,7 +94,20 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return byteBuffer.getDouble(index << 3);
+ 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);
+ if (byteBuffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, doubleCount);
+ } else {
+ ((HeapByteBuffer) byteBuffer).get(dst, dstOffset, doubleCount);
+ }
+ this.position += doubleCount;
+ return this;
}
@Override
@@ -185,7 +145,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- byteBuffer.putDouble(position++ << 3, c);
+ byteBuffer.putDouble(position++ * SizeOf.DOUBLE, c);
return this;
}
@@ -194,14 +154,27 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- byteBuffer.putDouble(index << 3, 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);
+ if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
+ ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, doubleCount);
+ } else {
+ ((ReadWriteHeapByteBuffer) byteBuffer).put(src, srcOffset, doubleCount);
+ }
+ this.position += doubleCount;
return this;
}
@Override
public DoubleBuffer slice() {
- byteBuffer.limit(limit << 3);
- byteBuffer.position(position << 3);
+ 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/org/apache/harmony/nio/internal/FileChannelImpl.java b/luni/src/main/java/java/nio/FileChannelImpl.java
similarity index 78%
rename from luni/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java
rename to luni/src/main/java/java/nio/FileChannelImpl.java
index 880c4f1..d7baefd 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java
+++ b/luni/src/main/java/java/nio/FileChannelImpl.java
@@ -15,32 +15,23 @@
* limitations under the License.
*/
-/*
- * Android Notice
- * In this class the address length was changed from long to int.
- * This is due to performance optimizations for the device.
- *
- * Also this class was copied from a newer version of harmony.
- */
-
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.Closeable;
import java.io.FileDescriptor;
import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.MappedByteBuffer;
-import java.nio.MappedByteBufferAdapter;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.NonWritableChannelException;
+import java.nio.channels.OverlappingFileLockException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
+import java.util.Comparator;
+import java.util.SortedSet;
+import java.util.TreeSet;
import org.apache.harmony.luni.platform.IFileSystem;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.luni.platform.PlatformAddressFactory;
/*
* The file channel impl class is the bridge between the logical channels
@@ -49,44 +40,37 @@
*
* This class is non-API, but implements the API of the FileChannel interface.
*/
-public abstract class FileChannelImpl extends FileChannel {
+abstract class FileChannelImpl extends FileChannel {
+ private static final int ALLOC_GRANULARITY = Platform.FILE_SYSTEM.getAllocGranularity();
- // Reference to the portable file system code.
- private static final IFileSystem fileSystem = Platform.getFileSystem();
-
- private static final int ALLOC_GRANULARITY;
-
- static {
- try {
- ALLOC_GRANULARITY = fileSystem.getAllocGranularity();
- } catch (IOException e) {
- throw new Error(e);
+ private static final Comparator<FileLock> LOCK_COMPARATOR = new Comparator<FileLock>() {
+ public int compare(FileLock lock1, FileLock lock2) {
+ long position1 = lock1.position();
+ long position2 = lock2.position();
+ return position1 > position2 ? 1 : (position1 < position2 ? -1 : 0);
}
- }
+ };
// Handle to the open file
private final int handle;
- // The object that will track all outstanding locks on this channel.
- private final LockManager lockManager = new LockManager();
+ // The set of acquired and pending locks.
+ private final SortedSet<FileLock> locks = new TreeSet<FileLock>(LOCK_COMPARATOR);
- private static class RepositioningLock {}
- private final Object repositioningLock = new RepositioningLock();
+ private final Object repositioningLock = new Object();
private final Object stream;
- /*
+ /**
* Create a new file channel implementation class that wraps the given file
* handle and operates in the specified mode.
- *
*/
public FileChannelImpl(Object stream, int handle) {
- super();
this.handle = handle;
this.stream = stream;
}
- /*
+ /**
* Helper method to throw an exception if the channel is already closed.
* Note that we don't bother to synchronize on this test since the file may
* be closed by operations beyond our control anyways.
@@ -97,11 +81,6 @@
}
}
- /*
- * (non-Javadoc)
- *
- * @see java.nio.channels.spi.AbstractInterruptibleChannel#implCloseChannel()
- */
protected void implCloseChannel() throws IOException {
if (stream instanceof Closeable) {
((Closeable) stream).close();
@@ -115,25 +94,40 @@
}
int lockType = shared ? IFileSystem.SHARED_LOCK_TYPE : IFileSystem.EXCLUSIVE_LOCK_TYPE;
FileLock pendingLock = new FileLockImpl(this, position, size, shared);
- lockManager.addLock(pendingLock);
+ addLock(pendingLock);
- if (fileSystem.lock(handle, position, size, lockType, wait)) {
+ if (Platform.FILE_SYSTEM.lock(handle, position, size, lockType, wait)) {
return pendingLock;
}
// Lock acquisition failed
- lockManager.removeLock(pendingLock);
+ removeLock(pendingLock);
return null;
}
- /*
- * Acquire a lock on the receiver, blocks if the lock cannot be obtained
- * immediately.
- *
- * @see java.nio.channels.FileChannel#lock(long, long, boolean)
- */
- public final FileLock lock(long position, long size, boolean shared)
- throws IOException {
+ private static final class FileLockImpl extends FileLock {
+ private boolean isReleased = false;
+
+ public FileLockImpl(FileChannel channel, long position, long size, boolean shared) {
+ super(channel, position, size, shared);
+ }
+
+ @Override public boolean isValid() {
+ return !isReleased && channel().isOpen();
+ }
+
+ @Override public void release() throws IOException {
+ if (!channel().isOpen()) {
+ throw new ClosedChannelException();
+ }
+ if (!isReleased) {
+ ((FileChannelImpl) channel()).release(this);
+ isReleased = true;
+ }
+ }
+ }
+
+ public final FileLock lock(long position, long size, boolean shared) throws IOException {
openCheck();
FileLock resultLock = null;
{
@@ -149,56 +143,47 @@
return resultLock;
}
- /*
- * Attempts to acquire the given lock, but does not block. If the lock
- * cannot be acquired the method returns null.
- *
- * @see java.nio.channels.FileChannel#tryLock(long, long, boolean)
- */
- public final FileLock tryLock(long position, long size, boolean shared)
- throws IOException {
+ public final FileLock tryLock(long position, long size, boolean shared) throws IOException {
openCheck();
return basicLock(position, size, shared, false);
}
- /*
+ /**
* Non-API method to release a given lock on a file channel. Assumes that
* the lock will mark itself invalid after successful unlocking.
*/
void release(FileLock lock) throws IOException {
openCheck();
- fileSystem.unlock(handle, lock.position(), lock.size());
- lockManager.removeLock(lock);
+ Platform.FILE_SYSTEM.unlock(handle, lock.position(), lock.size());
+ removeLock(lock);
}
@Override public void force(boolean metadata) throws IOException {
openCheck();
- fileSystem.fsync(handle, metadata);
+ Platform.FILE_SYSTEM.fsync(handle, metadata);
}
public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException;
- protected final MappedByteBuffer mapImpl(MapMode mapMode, long position, long size)
- throws IOException {
+ protected final MappedByteBuffer mapImpl(MapMode mapMode, long position, long size) throws IOException {
if (position + size > size()) {
- fileSystem.truncate(handle, position + size);
+ Platform.FILE_SYSTEM.truncate(handle, position + size);
}
long alignment = position - position % ALLOC_GRANULARITY;
int offset = (int) (position - alignment);
- PlatformAddress address = PlatformAddressFactory.allocMap(handle,
- alignment, size + offset, mapMode);
- return new MappedByteBufferAdapter(address, (int) size, offset, mapMode);
+ MemoryBlock block = MemoryBlock.mmap(handle, alignment, size + offset, mapMode);
+ return new MappedByteBufferAdapter(block, (int) size, offset, mapMode);
}
- /*
+ /**
* Returns the current file position.
*/
public long position() throws IOException {
openCheck();
- return fileSystem.seek(handle, 0L, IFileSystem.SEEK_CUR);
+ return Platform.FILE_SYSTEM.seek(handle, 0L, IFileSystem.SEEK_CUR);
}
- /*
+ /**
* Sets the file pointer.
*/
public FileChannel position(long newPosition) throws IOException {
@@ -208,7 +193,7 @@
}
synchronized (repositioningLock) {
- fileSystem.seek(handle, newPosition, IFileSystem.SEEK_SET);
+ Platform.FILE_SYSTEM.seek(handle, newPosition, IFileSystem.SEEK_SET);
}
return this;
}
@@ -245,14 +230,13 @@
int bytesRead = 0;
synchronized (repositioningLock) {
if (buffer.isDirect()) {
- DirectBuffer directBuffer = (DirectBuffer) buffer;
- int address = directBuffer.getEffectiveAddress().toInt();
try {
begin();
/*
* if (bytesRead <= EOF) dealt by read completed = false;
*/
- bytesRead = (int) fileSystem.readDirect(handle, address,
+ int address = NioUtils.getDirectBufferAddress(buffer);
+ bytesRead = (int) Platform.FILE_SYSTEM.readDirect(handle, address,
buffer.position(), buffer.remaining());
completed = true;
} finally {
@@ -264,7 +248,7 @@
/*
* if (bytesRead <= EOF) dealt by read completed = false;
*/
- bytesRead = (int) fileSystem.read(handle, buffer.array(),
+ bytesRead = (int) Platform.FILE_SYSTEM.read(handle, buffer.array(),
buffer.arrayOffset() + buffer.position(), buffer
.remaining());
completed = true;
@@ -301,7 +285,7 @@
} else {
offsets[i] = buffer.position();
}
- handles[i] = ((DirectBuffer) buffer).getEffectiveAddress().toInt();
+ handles[i] = NioUtils.getDirectBufferAddress(buffer);
lengths[i] = buffer.remaining();
}
long bytesRead = 0;
@@ -310,7 +294,7 @@
try {
begin();
synchronized (repositioningLock) {
- bytesRead = fileSystem.readv(handle, handles, offsets,
+ bytesRead = Platform.FILE_SYSTEM.readv(handle, handles, offsets,
lengths, length);
}
@@ -352,12 +336,12 @@
return bytesRead;
}
- /*
+ /**
* Returns the current file size, as an integer number of bytes.
*/
public long size() throws IOException {
openCheck();
- return fileSystem.length(handle);
+ return Platform.FILE_SYSTEM.length(handle);
}
public long transferFrom(ReadableByteChannel src, long position, long count)
@@ -390,12 +374,7 @@
}
return write(buffer, position);
} finally {
- // unmap the buffer
- if (buffer != null) {
- // all children of FileChannelImpl currently returns
- // an instance of DirectBuffer from map() method
- ((DirectBuffer) buffer).free();
- }
+ NioUtils.freeDirectBuffer(buffer);
}
}
@@ -427,12 +406,7 @@
buffer = map(MapMode.READ_ONLY, position, count);
return target.write(buffer);
} finally {
- // unmap the buffer
- if (buffer != null) {
- // all children of FileChannelImpl currently returns
- // an instance of DirectBuffer from map() method
- ((DirectBuffer) buffer).free();
- }
+ NioUtils.freeDirectBuffer(buffer);
}
}
@@ -441,7 +415,7 @@
boolean completed = false;
try {
begin();
- long ret = fileSystem.transfer(l, fd, position, count);
+ long ret = Platform.FILE_SYSTEM.transfer(l, fd, position, count);
completed = true;
return ret;
} finally {
@@ -457,7 +431,7 @@
if (size < size()) {
synchronized (repositioningLock) {
long position = position();
- fileSystem.truncate(handle, size);
+ Platform.FILE_SYSTEM.truncate(handle, size);
/*
* FIXME: currently the port library always modifies the
* position to given size. not sure it is a bug or intended
@@ -470,12 +444,6 @@
return this;
}
- /*
- * (non-Javadoc)
- *
- * @see java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer)
- */
-
public int write(ByteBuffer buffer, long position) throws IOException {
if (null == buffer) {
throw new NullPointerException();
@@ -510,11 +478,10 @@
boolean completed = false;
synchronized (repositioningLock) {
if (buffer.isDirect()) {
- DirectBuffer directBuffer = (DirectBuffer) buffer;
- int address = directBuffer.getEffectiveAddress().toInt();
try {
begin();
- bytesWritten = (int) fileSystem.writeDirect(handle,
+ int address = NioUtils.getDirectBufferAddress(buffer);
+ bytesWritten = (int) Platform.FILE_SYSTEM.writeDirect(handle,
address, buffer.position(), buffer.remaining());
completed = true;
} finally {
@@ -523,7 +490,7 @@
} else {
try {
begin();
- bytesWritten = (int) fileSystem.write(handle, buffer
+ bytesWritten = (int) Platform.FILE_SYSTEM.write(handle, buffer
.array(), buffer.arrayOffset() + buffer.position(),
buffer.remaining());
completed = true;
@@ -552,7 +519,7 @@
int[] lengths = new int[length];
// BEGIN android-changed
// list of allocated direct ByteBuffers to prevent them from being GC-ed
- DirectBuffer[] allocatedBufs = new DirectBuffer[length];
+ ByteBuffer[] allocatedBufs = new ByteBuffer[length];
for (int i = 0; i < length; i++) {
ByteBuffer buffer = buffers[i + offset];
@@ -561,13 +528,13 @@
directBuffer.put(buffer);
directBuffer.flip();
buffer = directBuffer;
- allocatedBufs[i] = (DirectBuffer) directBuffer;
+ allocatedBufs[i] = directBuffer;
offsets[i] = 0;
} else {
offsets[i] = buffer.position();
allocatedBufs[i] = null;
}
- handles[i] = ((DirectBuffer) buffer).getEffectiveAddress().toInt();
+ handles[i] = NioUtils.getDirectBufferAddress(buffer);
lengths[i] = buffer.remaining();
}
// END android-changed
@@ -577,19 +544,14 @@
synchronized (repositioningLock) {
try {
begin();
- bytesWritten = fileSystem.writev(handle, handles, offsets,
+ bytesWritten = Platform.FILE_SYSTEM.writev(handle, handles, offsets,
lengths, length);
completed = true;
} finally {
end(completed);
- // BEGIN android-added
- // free temporary direct buffers
- for (int i = 0; i < length; ++i) {
- if (allocatedBufs[i] != null) {
- allocatedBufs[i].free();
- }
+ for (ByteBuffer buffer : allocatedBufs) {
+ NioUtils.freeDirectBuffer(buffer);
}
- // END android-added
}
}
@@ -633,4 +595,32 @@
public int getHandle() {
return handle;
}
+
+ /**
+ * Add a new pending lock to the manager. Throws an exception if the lock
+ * would overlap an existing lock. Once the lock is acquired it remains in
+ * this set as an acquired lock.
+ */
+ private synchronized void addLock(FileLock lock) throws OverlappingFileLockException {
+ long lockEnd = lock.position() + lock.size();
+ for (FileLock existingLock : locks) {
+ if (existingLock.position() > lockEnd) {
+ // This, and all remaining locks, start beyond our end (so
+ // cannot overlap).
+ break;
+ }
+ if (existingLock.overlaps(lock.position(), lock.size())) {
+ throw new OverlappingFileLockException();
+ }
+ }
+ locks.add(lock);
+ }
+
+ /**
+ * Removes an acquired lock from the lock manager. If the lock did not exist
+ * in the lock manager the operation is a no-op.
+ */
+ private synchronized void removeLock(FileLock lock) {
+ locks.remove(lock);
+ }
}
diff --git a/luni/src/main/java/java/nio/FloatArrayBuffer.java b/luni/src/main/java/java/nio/FloatArrayBuffer.java
index f25ce24..0e2af91 100644
--- a/luni/src/main/java/java/nio/FloatArrayBuffer.java
+++ b/luni/src/main/java/java/nio/FloatArrayBuffer.java
@@ -66,16 +66,16 @@
}
@Override
- public final FloatBuffer get(float[] dst, int off, int len) {
+ public final FloatBuffer get(float[] dst, int dstOffset, int floatCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (dstOffset < 0 || floatCount < 0 || (long) dstOffset + (long) floatCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (floatCount > remaining()) {
throw new BufferUnderflowException();
}
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ System.arraycopy(backingArray, offset + position, dst, dstOffset, floatCount);
+ position += floatCount;
return this;
}
diff --git a/luni/src/main/java/java/nio/FloatBuffer.java b/luni/src/main/java/java/nio/FloatBuffer.java
index 9044911..b2446bd 100644
--- a/luni/src/main/java/java/nio/FloatBuffer.java
+++ b/luni/src/main/java/java/nio/FloatBuffer.java
@@ -46,7 +46,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newFloatBuffer(capacity);
+ return new ReadWriteFloatArrayBuffer(capacity);
}
/**
@@ -67,45 +67,39 @@
* Creates a new float buffer by wrapping the given float array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + floatCount}, capacity will be the length of the array.
*
* @param array
* the float array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}.
- * @param len
+ * @param floatCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created float buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code floatCount} is invalid.
* @exception NullPointerException
* if {@code array} is null.
*/
- public static FloatBuffer wrap(float[] array, int start, int len) {
+ public static FloatBuffer wrap(float[] array, int start, int floatCount) {
if (array == null) {
throw new NullPointerException();
}
- if (start < 0 || len < 0 || (long) start + (long) len > array.length) {
+ if (start < 0 || floatCount < 0 || (long) start + (long) floatCount > array.length) {
throw new IndexOutOfBoundsException();
}
- FloatBuffer buf = BufferFactory.newFloatBuffer(array);
+ FloatBuffer buf = new ReadWriteFloatArrayBuffer(array);
buf.position = start;
- buf.limit = start + len;
+ buf.limit = start + floatCount;
return buf;
}
- /**
- * Constructs a {@code FloatBuffer} with given capacity.
- *
- * @param capacity The capacity of the buffer
- */
FloatBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 2;
+ super(2, capacity, null);
}
public final float[] array() {
@@ -266,28 +260,28 @@
*
* @param dst
* the target float array.
- * @param off
+ * @param dstOffset
* the offset of the float array, must not be negative and no
* greater than {@code dst.length}.
- * @param len
+ * @param floatCount
* the number of floats to read, must be no less than zero and no
- * greater than {@code dst.length - off}.
+ * greater than {@code dst.length - dstOffset}.
* @return this buffer.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code dstOffset} or {@code floatCount} is invalid.
* @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * if {@code floatCount} is greater than {@code remaining()}.
*/
- public FloatBuffer get(float[] dst, int off, int len) {
+ public FloatBuffer get(float[] dst, int dstOffset, int floatCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (dstOffset < 0 || floatCount < 0 || (long) dstOffset + (long) floatCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (floatCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + floatCount; ++i) {
dst[i] = get();
}
return this;
@@ -409,30 +403,29 @@
*
* @param src
* the source float array.
- * @param off
+ * @param srcOffset
* the offset of float array, must not be negative and not
* greater than {@code src.length}.
- * @param len
+ * @param floatCount
* the number of floats to write, must be no less than zero and
- * no greater than {@code src.length - off}.
+ * no greater than {@code src.length - srcOffset}.
* @return this buffer.
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code floatCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code floatCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public FloatBuffer put(float[] src, int off, int len) {
+ public FloatBuffer put(float[] src, int srcOffset, int floatCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long)off + (long)len > length) {
+ if (srcOffset < 0 || floatCount < 0 || (long) srcOffset + (long) floatCount > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (floatCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + floatCount; ++i) {
put(src[i]);
}
return this;
@@ -499,22 +492,4 @@
* @return a sliced buffer that shares its content with this buffer.
*/
public abstract FloatBuffer slice();
-
- /**
- * Returns a string representing the state of this float buffer.
- *
- * @return a string representing the state of this float buffer.
- */
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append(getClass().getName());
- buf.append(", status: capacity=");
- buf.append(capacity());
- buf.append(" position=");
- buf.append(position());
- buf.append(" limit=");
- buf.append(limit());
- return buf.toString();
- }
}
diff --git a/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java b/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java
index 079f7f8..c1e4ee1 100644
--- a/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java
@@ -16,8 +16,7 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a float buffer.
@@ -31,77 +30,26 @@
* </ul>
* </p>
*/
-final class FloatToByteBufferAdapter extends FloatBuffer implements
- DirectBuffer {
-
- static FloatBuffer wrap(ByteBuffer byteBuffer) {
- return new FloatToByteBufferAdapter(byteBuffer.slice());
- }
+final class FloatToByteBufferAdapter extends FloatBuffer {
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() >> 2));
+ super(byteBuffer.capacity() / SizeOf.FLOAT);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
- }
-
- public int getByteCapacity() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getByteCapacity();
- }
- assert false : byteBuffer;
- return -1;
- }
-
- public PlatformAddress getEffectiveAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer)byteBuffer).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
- assert false : byteBuffer;
- return null;
- }
-
- public PlatformAddress getBaseAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getBaseAddress();
- }
- assert false : byteBuffer;
- return null;
- }
-
- public boolean isAddressValid() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).isAddressValid();
- }
- assert false : byteBuffer;
- return false;
- }
-
- public void addressValidityCheck() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).addressValidityCheck();
- } else {
- assert false : byteBuffer;
- }
- }
-
- public void free() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).free();
- } else {
- assert false : byteBuffer;
- }
+ this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public FloatBuffer asReadOnlyBuffer() {
- FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer
- .asReadOnlyBuffer());
+ FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -113,8 +61,8 @@
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- byteBuffer.limit(limit << 2);
- byteBuffer.position(position << 2);
+ byteBuffer.limit(limit * SizeOf.FLOAT);
+ byteBuffer.position(position * SizeOf.FLOAT);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
@@ -125,8 +73,7 @@
@Override
public FloatBuffer duplicate() {
- FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer
- .duplicate());
+ FloatToByteBufferAdapter buf = new FloatToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -138,7 +85,7 @@
if (position == limit) {
throw new BufferUnderflowException();
}
- return byteBuffer.getFloat(position++ << 2);
+ return byteBuffer.getFloat(position++ * SizeOf.FLOAT);
}
@Override
@@ -146,7 +93,20 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return byteBuffer.getFloat(index << 2);
+ 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);
+ if (byteBuffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, floatCount);
+ } else {
+ ((HeapByteBuffer) byteBuffer).get(dst, dstOffset, floatCount);
+ }
+ this.position += floatCount;
+ return this;
}
@Override
@@ -184,7 +144,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- byteBuffer.putFloat(position++ << 2, c);
+ byteBuffer.putFloat(position++ * SizeOf.FLOAT, c);
return this;
}
@@ -193,30 +153,27 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- byteBuffer.putFloat(index << 2, c);
+ byteBuffer.putFloat(index * SizeOf.FLOAT, c);
return this;
}
- // BEGIN android-added
@Override
- public FloatBuffer put(float[] c, int off, int len) {
+ public FloatBuffer put(float[] src, int srcOffset, int floatCount) {
+ byteBuffer.limit(limit * SizeOf.FLOAT);
+ byteBuffer.position(position * SizeOf.FLOAT);
if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
- byteBuffer.limit(limit << 2);
- byteBuffer.position(position << 2);
- ((ReadWriteDirectByteBuffer) byteBuffer).put(c, off, len);
- this.position += len;
- return this;
+ ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, floatCount);
} else {
- return super.put(c, off, len);
+ ((ReadWriteHeapByteBuffer) byteBuffer).put(src, srcOffset, floatCount);
}
+ this.position += floatCount;
+ return this;
}
- // END android-added
-
@Override
public FloatBuffer slice() {
- byteBuffer.limit(limit << 2);
- byteBuffer.position(position << 2);
+ 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 b246dc2..c19e11b 100644
--- a/luni/src/main/java/java/nio/HeapByteBuffer.java
+++ b/luni/src/main/java/java/nio/HeapByteBuffer.java
@@ -17,6 +17,9 @@
package java.nio;
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
+
/**
* HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose
* the implementation of array based byte buffers.
@@ -44,7 +47,7 @@
}
HeapByteBuffer(byte[] backingArray, int capacity, int offset) {
- super(capacity);
+ super(capacity, null);
this.backingArray = backingArray;
this.offset = offset;
@@ -53,27 +56,50 @@
}
}
- /*
- * Override ByteBuffer.get(byte[], int, int) to improve performance.
- *
- * (non-Javadoc)
- *
- * @see java.nio.ByteBuffer#get(byte[], int, int)
- */
@Override
- public final ByteBuffer get(byte[] dst, int off, int len) {
- int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
- throw new IndexOutOfBoundsException();
- }
- if (len > remaining()) {
- throw new BufferUnderflowException();
- }
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ public final ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
+ checkGetBounds(1, dst.length, dstOffset, byteCount);
+ System.arraycopy(backingArray, offset + position, dst, dstOffset, byteCount);
+ position += byteCount;
return this;
}
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ position += byteCount;
+ }
+
@Override
public final byte get() {
if (position == limit) {
@@ -91,6 +117,25 @@
}
@Override
+ public final char getChar() {
+ int newPosition = position + SizeOf.CHAR;
+ if (newPosition > limit) {
+ throw new BufferUnderflowException();
+ }
+ 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) {
+ throw new IndexOutOfBoundsException();
+ }
+ return (char) OSMemory.peekShort(backingArray, offset + index, order);
+ }
+
+ @Override
public final double getDouble() {
return Double.longBitsToDouble(getLong());
}
@@ -112,151 +157,63 @@
@Override
public final int getInt() {
- int newPosition = position + 4;
+ 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 + 4 > 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 + 8;
+ 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 + 8 > 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 + 2;
+ 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 + 2 > 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;
}
-
- protected final int loadInt(int index) {
- int baseOffset = offset + index;
- int bytes = 0;
- if (order == ByteOrder.BIG_ENDIAN) {
- for (int i = 0; i < 4; i++) {
- bytes = bytes << 8;
- bytes = bytes | (backingArray[baseOffset + i] & 0xFF);
- }
- } else {
- for (int i = 3; i >= 0; i--) {
- bytes = bytes << 8;
- bytes = bytes | (backingArray[baseOffset + i] & 0xFF);
- }
- }
- return bytes;
- }
-
- protected final long loadLong(int index) {
- int baseOffset = offset + index;
- long bytes = 0;
- if (order == ByteOrder.BIG_ENDIAN) {
- for (int i = 0; i < 8; i++) {
- bytes = bytes << 8;
- bytes = bytes | (backingArray[baseOffset + i] & 0xFF);
- }
- } else {
- for (int i = 7; i >= 0; i--) {
- bytes = bytes << 8;
- bytes = bytes | (backingArray[baseOffset + i] & 0xFF);
- }
- }
- return bytes;
- }
-
- protected final short loadShort(int index) {
- int baseOffset = offset + index;
- short bytes = 0;
- if (order == ByteOrder.BIG_ENDIAN) {
- bytes = (short) (backingArray[baseOffset] << 8);
- bytes |= (backingArray[baseOffset + 1] & 0xFF);
- } else {
- bytes = (short) (backingArray[baseOffset + 1] << 8);
- bytes |= (backingArray[baseOffset] & 0xFF);
- }
- return bytes;
- }
-
- protected final void store(int index, int value) {
- int baseOffset = offset + index;
- if (order == ByteOrder.BIG_ENDIAN) {
- for (int i = 3; i >= 0; i--) {
- backingArray[baseOffset + i] = (byte) (value & 0xFF);
- value = value >> 8;
- }
- } else {
- for (int i = 0; i <= 3; i++) {
- backingArray[baseOffset + i] = (byte) (value & 0xFF);
- value = value >> 8;
- }
- }
- }
-
- protected final void store(int index, long value) {
- int baseOffset = offset + index;
- if (order == ByteOrder.BIG_ENDIAN) {
- for (int i = 7; i >= 0; i--) {
- backingArray[baseOffset + i] = (byte) (value & 0xFF);
- value = value >> 8;
- }
- } else {
- for (int i = 0; i <= 7; i++) {
- backingArray[baseOffset + i] = (byte) (value & 0xFF);
- value = value >> 8;
- }
- }
- }
-
- protected final void store(int index, short value) {
- int baseOffset = offset + index;
- if (order == ByteOrder.BIG_ENDIAN) {
- backingArray[baseOffset] = (byte) ((value >> 8) & 0xFF);
- backingArray[baseOffset + 1] = (byte) (value & 0xFF);
- } else {
- backingArray[baseOffset + 1] = (byte) ((value >> 8) & 0xFF);
- backingArray[baseOffset] = (byte) (value & 0xFF);
- }
- }
}
diff --git a/luni/src/main/java/java/nio/IntArrayBuffer.java b/luni/src/main/java/java/nio/IntArrayBuffer.java
index a1ee158..c0cbebc 100644
--- a/luni/src/main/java/java/nio/IntArrayBuffer.java
+++ b/luni/src/main/java/java/nio/IntArrayBuffer.java
@@ -66,16 +66,16 @@
}
@Override
- public final IntBuffer get(int[] dst, int off, int len) {
+ public final IntBuffer get(int[] dst, int dstOffset, int intCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (dstOffset < 0 || intCount < 0 || (long) intCount + (long) dstOffset > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (intCount > remaining()) {
throw new BufferUnderflowException();
}
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ System.arraycopy(backingArray, offset + position, dst, dstOffset, intCount);
+ position += intCount;
return this;
}
diff --git a/luni/src/main/java/java/nio/IntBuffer.java b/luni/src/main/java/java/nio/IntBuffer.java
index 6f362ec..b2d7df2 100644
--- a/luni/src/main/java/java/nio/IntBuffer.java
+++ b/luni/src/main/java/java/nio/IntBuffer.java
@@ -44,7 +44,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newIntBuffer(capacity);
+ return new ReadWriteIntArrayBuffer(capacity);
}
/**
@@ -65,44 +65,37 @@
* Creates a new int buffer by wrapping the given int array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + intCount}, capacity will be the length of the array.
*
* @param array
* the int array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}
- * @param len
+ * @param intCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created int buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code intCount} is invalid.
*/
- public static IntBuffer wrap(int[] array, int start, int len) {
+ public static IntBuffer wrap(int[] array, int start, int intCount) {
if (array == null) {
throw new NullPointerException();
}
- if (start < 0 || len < 0 || (long) len + (long) start > array.length) {
+ if (start < 0 || intCount < 0 || (long) intCount + (long) start > array.length) {
throw new IndexOutOfBoundsException();
}
- IntBuffer buf = BufferFactory.newIntBuffer(array);
+ IntBuffer buf = new ReadWriteIntArrayBuffer(array);
buf.position = start;
- buf.limit = start + len;
+ buf.limit = start + intCount;
return buf;
}
- /**
- * Constructs a {@code IntBuffer} with given capacity.
- *
- * @param capacity
- * the capacity of the buffer.
- */
IntBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 2;
+ super(2, capacity, null);
}
public final int[] array() {
@@ -255,27 +248,27 @@
*
* @param dst
* the target int array.
- * @param off
+ * @param dstOffset
* the offset of the int array, must not be negative and not
* greater than {@code dst.length}.
- * @param len
+ * @param intCount
* the number of ints to read, must be no less than zero and not
- * greater than {@code dst.length - off}.
+ * greater than {@code dst.length - dstOffset}.
* @return this buffer.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code dstOffset} or {@code intCount} is invalid.
* @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * if {@code intCount} is greater than {@code remaining()}.
*/
- public IntBuffer get(int[] dst, int off, int len) {
+ public IntBuffer get(int[] dst, int dstOffset, int intCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (dstOffset < 0 || intCount < 0 || (long) intCount + (long) dstOffset > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (intCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + intCount; ++i) {
dst[i] = get();
}
return this;
@@ -397,30 +390,29 @@
*
* @param src
* the source int array.
- * @param off
+ * @param srcOffset
* the offset of int array, must not be negative and not greater
* than {@code src.length}.
- * @param len
+ * @param intCount
* the number of ints to write, must be no less than zero and not
- * greater than {@code src.length - off}.
+ * greater than {@code src.length - srcOffset}.
* @return this buffer.
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code intCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code intCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public IntBuffer put(int[] src, int off, int len) {
+ public IntBuffer put(int[] src, int srcOffset, int intCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (srcOffset < 0 || intCount < 0 || (long) intCount + (long) srcOffset > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (intCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + intCount; ++i) {
put(src[i]);
}
return this;
@@ -487,22 +479,4 @@
* @return a sliced buffer that shares its content with this buffer.
*/
public abstract IntBuffer slice();
-
- /**
- * Returns a string represents of the state of this int buffer.
- *
- * @return a string represents of the state of this int buffer.
- */
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append(getClass().getName());
- buf.append(", status: capacity=");
- buf.append(capacity());
- buf.append(" position=");
- buf.append(position());
- buf.append(" limit=");
- buf.append(limit());
- return buf.toString();
- }
}
diff --git a/luni/src/main/java/java/nio/IntToByteBufferAdapter.java b/luni/src/main/java/java/nio/IntToByteBufferAdapter.java
index 03ac9f9..14d6ca9 100644
--- a/luni/src/main/java/java/nio/IntToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/IntToByteBufferAdapter.java
@@ -16,8 +16,7 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a int buffer.
@@ -32,76 +31,26 @@
* </p>
*
*/
-final class IntToByteBufferAdapter extends IntBuffer implements DirectBuffer {
-
- static IntBuffer wrap(ByteBuffer byteBuffer) {
- return new IntToByteBufferAdapter(byteBuffer.slice());
- }
+final class IntToByteBufferAdapter extends IntBuffer {
private final ByteBuffer byteBuffer;
- IntToByteBufferAdapter(ByteBuffer byteBuffer) {
- super((byteBuffer.capacity() >> 2));
+ 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();
- }
-
- public int getByteCapacity() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getByteCapacity();
- }
- assert false : byteBuffer;
- return -1;
- }
-
- public PlatformAddress getEffectiveAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer)byteBuffer).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
- assert false : byteBuffer;
- return null;
- }
-
- public PlatformAddress getBaseAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getBaseAddress();
- }
- assert false : byteBuffer;
- return null;
- }
-
- public boolean isAddressValid() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).isAddressValid();
- }
- assert false : byteBuffer;
- return false;
- }
-
- public void addressValidityCheck() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).addressValidityCheck();
- } else {
- assert false : byteBuffer;
- }
- }
-
- public void free() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).free();
- } else {
- assert false : byteBuffer;
- }
+ this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public IntBuffer asReadOnlyBuffer() {
- IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer
- .asReadOnlyBuffer());
+ IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -113,8 +62,8 @@
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- byteBuffer.limit(limit << 2);
- byteBuffer.position(position << 2);
+ byteBuffer.limit(limit * SizeOf.INT);
+ byteBuffer.position(position * SizeOf.INT);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
@@ -125,8 +74,7 @@
@Override
public IntBuffer duplicate() {
- IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer
- .duplicate());
+ IntToByteBufferAdapter buf = new IntToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -138,7 +86,7 @@
if (position == limit) {
throw new BufferUnderflowException();
}
- return byteBuffer.getInt(position++ << 2);
+ return byteBuffer.getInt(position++ * SizeOf.INT);
}
@Override
@@ -146,7 +94,20 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return byteBuffer.getInt(index << 2);
+ 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);
+ if (byteBuffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, intCount);
+ } else {
+ ((HeapByteBuffer) byteBuffer).get(dst, dstOffset, intCount);
+ }
+ this.position += intCount;
+ return this;
}
@Override
@@ -184,7 +145,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- byteBuffer.putInt(position++ << 2, c);
+ byteBuffer.putInt(position++ * SizeOf.INT, c);
return this;
}
@@ -193,29 +154,27 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- byteBuffer.putInt(index << 2, c);
+ byteBuffer.putInt(index * SizeOf.INT, c);
return this;
}
- // BEGIN android-added
@Override
- public IntBuffer put(int[] i, int off, int len) {
+ public IntBuffer put(int[] src, int srcOffset, int intCount) {
+ byteBuffer.limit(limit * SizeOf.INT);
+ byteBuffer.position(position * SizeOf.INT);
if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
- byteBuffer.limit(limit << 2);
- byteBuffer.position(position << 2);
- ((ReadWriteDirectByteBuffer) byteBuffer).put(i, off, len);
- this.position += len;
- return this;
+ ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, intCount);
} else {
- return super.put(i, off, len);
+ ((ReadWriteHeapByteBuffer) byteBuffer).put(src, srcOffset, intCount);
}
+ this.position += intCount;
+ return this;
}
- // END android-added
@Override
public IntBuffer slice() {
- byteBuffer.limit(limit << 2);
- byteBuffer.position(position << 2);
+ 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/LongArrayBuffer.java b/luni/src/main/java/java/nio/LongArrayBuffer.java
index 39f66e7..9c05809 100644
--- a/luni/src/main/java/java/nio/LongArrayBuffer.java
+++ b/luni/src/main/java/java/nio/LongArrayBuffer.java
@@ -66,16 +66,16 @@
}
@Override
- public final LongBuffer get(long[] dst, int off, int len) {
+ public final LongBuffer get(long[] dst, int dstOffset, int longCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (dstOffset < 0 || longCount < 0 || (long) longCount + (long) dstOffset > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (longCount > remaining()) {
throw new BufferUnderflowException();
}
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ System.arraycopy(backingArray, offset + position, dst, dstOffset, longCount);
+ position += longCount;
return this;
}
diff --git a/luni/src/main/java/java/nio/LongBuffer.java b/luni/src/main/java/java/nio/LongBuffer.java
index b07185d..df9f6ca 100644
--- a/luni/src/main/java/java/nio/LongBuffer.java
+++ b/luni/src/main/java/java/nio/LongBuffer.java
@@ -46,7 +46,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newLongBuffer(capacity);
+ return new ReadWriteLongArrayBuffer(capacity);
}
/**
@@ -67,44 +67,37 @@
* Creates a new long buffer by wrapping the given long array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + longCount}, capacity will be the length of the array.
*
* @param array
* the long array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}.
- * @param len
+ * @param longCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created long buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code longCount} is invalid.
*/
- public static LongBuffer wrap(long[] array, int start, int len) {
+ public static LongBuffer wrap(long[] array, int start, int longCount) {
if (array == null) {
throw new NullPointerException();
}
- if (start < 0 || len < 0 || (long) len + (long) start > array.length) {
+ if (start < 0 || longCount < 0 || (long) longCount + (long) start > array.length) {
throw new IndexOutOfBoundsException();
}
- LongBuffer buf = BufferFactory.newLongBuffer(array);
+ LongBuffer buf = new ReadWriteLongArrayBuffer(array);
buf.position = start;
- buf.limit = start + len;
+ buf.limit = start + longCount;
return buf;
}
- /**
- * Constructs a {@code LongBuffer} with given capacity.
- *
- * @param capacity
- * The capacity of the buffer
- */
LongBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 3;
+ super(3, capacity, null);
}
public final long[] array() {
@@ -257,28 +250,27 @@
*
* @param dst
* the target long array.
- * @param off
+ * @param dstOffset
* the offset of the long array, must not be negative and not
* greater than {@code dst.length}.
- * @param len
+ * @param longCount
* the number of longs to read, must be no less than zero and not
- * greater than {@code dst.length - off}.
+ * greater than {@code dst.length - dstOffset}.
* @return this buffer.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code dstOffset} or {@code longCount} is invalid.
* @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * if {@code longCount} is greater than {@code remaining()}.
*/
- public LongBuffer get(long[] dst, int off, int len) {
+ public LongBuffer get(long[] dst, int dstOffset, int longCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (dstOffset < 0 || longCount < 0 || (long) longCount + (long) dstOffset > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (longCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + longCount; ++i) {
dst[i] = get();
}
return this;
@@ -402,30 +394,29 @@
*
* @param src
* the source long array.
- * @param off
+ * @param srcOffset
* the offset of long array, must not be negative and not greater
* than {@code src.length}.
- * @param len
+ * @param longCount
* the number of longs to write, must be no less than zero and
- * not greater than {@code src.length - off}.
+ * not greater than {@code src.length - srcOffset}.
* @return this buffer.
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code longCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code longCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public LongBuffer put(long[] src, int off, int len) {
+ public LongBuffer put(long[] src, int srcOffset, int longCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (srcOffset < 0 || longCount < 0 || (long) longCount + (long) srcOffset > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (longCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + longCount; ++i) {
put(src[i]);
}
return this;
@@ -492,22 +483,4 @@
* @return a sliced buffer that shares its content with this buffer.
*/
public abstract LongBuffer slice();
-
- /**
- * Returns a string representing the state of this long buffer.
- *
- * @return a string representing the state of this long buffer.
- */
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append(getClass().getName());
- buf.append(", status: capacity=");
- buf.append(capacity());
- buf.append(" position=");
- buf.append(position());
- buf.append(" limit=");
- buf.append(limit());
- return buf.toString();
- }
}
diff --git a/luni/src/main/java/java/nio/LongToByteBufferAdapter.java b/luni/src/main/java/java/nio/LongToByteBufferAdapter.java
index ca40c5f..80e9a51 100644
--- a/luni/src/main/java/java/nio/LongToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/LongToByteBufferAdapter.java
@@ -16,8 +16,7 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a long buffer.
@@ -32,76 +31,26 @@
* </p>
*
*/
-final class LongToByteBufferAdapter extends LongBuffer implements DirectBuffer {
-
- static LongBuffer wrap(ByteBuffer byteBuffer) {
- return new LongToByteBufferAdapter(byteBuffer.slice());
- }
+final class LongToByteBufferAdapter extends LongBuffer {
private final ByteBuffer byteBuffer;
- LongToByteBufferAdapter(ByteBuffer byteBuffer) {
- super((byteBuffer.capacity() >> 3));
+ 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();
- }
-
- public int getByteCapacity() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getByteCapacity();
- }
- assert false : byteBuffer;
- return -1;
- }
-
- public PlatformAddress getEffectiveAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer)byteBuffer).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
- assert false : byteBuffer;
- return null;
- }
-
- public PlatformAddress getBaseAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getBaseAddress();
- }
- assert false : byteBuffer;
- return null;
- }
-
- public boolean isAddressValid() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).isAddressValid();
- }
- assert false : byteBuffer;
- return false;
- }
-
- public void addressValidityCheck() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).addressValidityCheck();
- } else {
- assert false : byteBuffer;
- }
- }
-
- public void free() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).free();
- } else {
- assert false : byteBuffer;
- }
+ this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public LongBuffer asReadOnlyBuffer() {
- LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer
- .asReadOnlyBuffer());
+ LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -113,8 +62,8 @@
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- byteBuffer.limit(limit << 3);
- byteBuffer.position(position << 3);
+ byteBuffer.limit(limit * SizeOf.LONG);
+ byteBuffer.position(position * SizeOf.LONG);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
@@ -125,8 +74,7 @@
@Override
public LongBuffer duplicate() {
- LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer
- .duplicate());
+ LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -138,7 +86,7 @@
if (position == limit) {
throw new BufferUnderflowException();
}
- return byteBuffer.getLong(position++ << 3);
+ return byteBuffer.getLong(position++ * SizeOf.LONG);
}
@Override
@@ -146,7 +94,20 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return byteBuffer.getLong(index << 3);
+ 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);
+ if (byteBuffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, longCount);
+ } else {
+ ((HeapByteBuffer) byteBuffer).get(dst, dstOffset, longCount);
+ }
+ this.position += longCount;
+ return this;
}
@Override
@@ -184,7 +145,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- byteBuffer.putLong(position++ << 3, c);
+ byteBuffer.putLong(position++ * SizeOf.LONG, c);
return this;
}
@@ -193,14 +154,27 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- byteBuffer.putLong(index << 3, 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);
+ if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
+ ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, longCount);
+ } else {
+ ((ReadWriteHeapByteBuffer) byteBuffer).put(src, srcOffset, longCount);
+ }
+ this.position += longCount;
return this;
}
@Override
public LongBuffer slice() {
- byteBuffer.limit(limit << 3);
- byteBuffer.position(position << 3);
+ 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/MappedByteBuffer.java b/luni/src/main/java/java/nio/MappedByteBuffer.java
index 4c7902d..9a99781 100644
--- a/luni/src/main/java/java/nio/MappedByteBuffer.java
+++ b/luni/src/main/java/java/nio/MappedByteBuffer.java
@@ -17,9 +17,7 @@
package java.nio;
import java.nio.channels.FileChannel.MapMode;
-import org.apache.harmony.luni.platform.MappedPlatformAddress;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import org.apache.harmony.luni.platform.OSMemory;
/**
* {@code MappedByteBuffer} is a special kind of direct byte buffer which maps a
@@ -42,7 +40,7 @@
private final MapMode mapMode;
MappedByteBuffer(ByteBuffer directBuffer) {
- super(directBuffer.capacity);
+ super(directBuffer.capacity, directBuffer.block);
if (!directBuffer.isDirect()) {
throw new IllegalArgumentException();
}
@@ -50,15 +48,14 @@
this.mapMode = null;
}
- MappedByteBuffer(PlatformAddress addr, int capacity, int offset, MapMode mapMode) {
- super(capacity);
+ MappedByteBuffer(MemoryBlock block, int capacity, int offset, MapMode mapMode) {
+ super(capacity, block);
this.mapMode = mapMode;
if (mapMode == MapMode.READ_ONLY) {
- wrapped = new ReadOnlyDirectByteBuffer(addr, capacity, offset);
+ wrapped = new ReadOnlyDirectByteBuffer(block, capacity, offset);
} else {
- wrapped = new ReadWriteDirectByteBuffer(addr, capacity, offset);
+ wrapped = new ReadWriteDirectByteBuffer(block, capacity, offset);
}
- addr.autoFree();
}
/**
@@ -70,7 +67,7 @@
* otherwise.
*/
public final boolean isLoaded() {
- return ((MappedPlatformAddress) ((DirectBuffer) wrapped).getBaseAddress()).mmapIsLoaded();
+ return OSMemory.isLoaded(block.toInt(), block.getSize());
}
/**
@@ -80,7 +77,7 @@
* @return this buffer.
*/
public final MappedByteBuffer load() {
- ((MappedPlatformAddress) ((DirectBuffer) wrapped).getBaseAddress()).mmapLoad();
+ OSMemory.load(block.toInt(), block.getSize());
return this;
}
@@ -94,7 +91,7 @@
*/
public final MappedByteBuffer force() {
if (mapMode == MapMode.READ_WRITE) {
- ((MappedPlatformAddress) ((DirectBuffer) wrapped).getBaseAddress()).mmapFlush();
+ OSMemory.msync(block.toInt(), block.getSize());
}
return this;
}
diff --git a/luni/src/main/java/java/nio/MappedByteBufferAdapter.java b/luni/src/main/java/java/nio/MappedByteBufferAdapter.java
index a66c4b7..1682a1f 100644
--- a/luni/src/main/java/java/nio/MappedByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/MappedByteBufferAdapter.java
@@ -15,224 +15,201 @@
* limitations under the License.
*/
-// BEGIN android-note
-// added some missing updates on position and limit
-// END android-note
-
package java.nio;
import java.nio.channels.FileChannel.MapMode;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
- * @hide
+ * Rather than duplicate all the code from ReadOnlyDirectByteBuffer and
+ * ReadWriteDirectByteBuffer (and their superclasses), we delegate to one or the other.
+ * The tricky part is that we need to keep our fields in sync with our delegate's fields.
+ * There are lots of methods that access the fields directly.
+ *
+ * The main consequence of our implementation is that we need to explicitly call
+ * wrapped.position(int) before any operation on our delegate that makes use of the
+ * implicit position. This means that, even more than usual, the implicit iteration
+ * operations are more expensive than the indexed operations.
+ *
+ * But we save a ton of code, for classes that no-one really uses because the API's broken
+ * by design (disallowing munmap(2) calls). Internally, we can use libcore.io.MemoryMappedFile
+ * as a high-performance and more usable replacement for MappedByteBuffer.
*/
-public final class MappedByteBufferAdapter extends MappedByteBuffer implements DirectBuffer {
-
- private static final int CHAR_SIZE = 2;
-
- private static final int SHORT_SIZE = 2;
-
- private static final int INTEGER_SIZE = 4;
-
- private static final int LONG_SIZE = 8;
-
- private static final int FLOAT_SIZE = 4;
-
- private static final int DOUBLE_SIZE = 8;
-
- public MappedByteBufferAdapter(ByteBuffer buffer) {
+final class MappedByteBufferAdapter extends MappedByteBuffer {
+ private MappedByteBufferAdapter(ByteBuffer buffer) {
super(buffer);
+ effectiveDirectAddress = wrapped.effectiveDirectAddress;
}
- public MappedByteBufferAdapter(PlatformAddress addr, int capa, int offset, MapMode mode) {
- super(addr, capa, offset, mode);
+ public MappedByteBufferAdapter(MemoryBlock block, int capacity, int offset, MapMode mode) {
+ super(block, capacity, offset, mode);
+ effectiveDirectAddress = wrapped.effectiveDirectAddress;
+ }
+
+ @Override void limitImpl(int newLimit) {
+ super.limitImpl(newLimit);
+ wrapped.limit(newLimit);
+ }
+
+ @Override void positionImpl(int newPosition) {
+ super.positionImpl(newPosition);
+ wrapped.position(newPosition);
}
@Override
public CharBuffer asCharBuffer() {
- return this.wrapped.asCharBuffer();
+ return wrapped.asCharBuffer();
}
@Override
public DoubleBuffer asDoubleBuffer() {
- return this.wrapped.asDoubleBuffer();
+ return wrapped.asDoubleBuffer();
}
@Override
public FloatBuffer asFloatBuffer() {
- return this.wrapped.asFloatBuffer();
+ return wrapped.asFloatBuffer();
}
@Override
public IntBuffer asIntBuffer() {
- return this.wrapped.asIntBuffer();
+ return wrapped.asIntBuffer();
}
@Override
public LongBuffer asLongBuffer() {
- return this.wrapped.asLongBuffer();
+ return wrapped.asLongBuffer();
}
@Override
public ByteBuffer asReadOnlyBuffer() {
- MappedByteBufferAdapter buf = new MappedByteBufferAdapter(this.wrapped
- .asReadOnlyBuffer());
- buf.limit = this.limit;
- buf.position = this.position;
- buf.mark = this.mark;
- return buf;
+ MappedByteBufferAdapter result = new MappedByteBufferAdapter(wrapped.asReadOnlyBuffer());
+ result.limit(limit);
+ result.position(position);
+ result.mark = mark;
+ return result;
}
@Override
public ShortBuffer asShortBuffer() {
- return this.wrapped.asShortBuffer();
+ return wrapped.asShortBuffer();
}
@Override
public ByteBuffer compact() {
- if (this.wrapped.isReadOnly()) {
+ if (wrapped.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.compact();
- this.wrapped.clear();
- this.position = this.limit - this.position;
- this.limit = this.capacity;
+ wrapped.compact();
+ limit(capacity);
+ position(wrapped.position());
this.mark = UNSET_MARK;
return this;
}
@Override
public ByteBuffer duplicate() {
- MappedByteBufferAdapter buf = new MappedByteBufferAdapter(this.wrapped
- .duplicate());
- buf.limit = this.limit;
- buf.position = this.position;
- buf.mark = this.mark;
- return buf;
+ MappedByteBufferAdapter result = new MappedByteBufferAdapter(wrapped.duplicate());
+ result.limit(limit);
+ result.position(position);
+ result.mark = mark;
+ return result;
}
@Override
public byte get() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- byte result = this.wrapped.get();
- this.position++;
+ wrapped.position(position);
+ byte result = wrapped.get();
+ ++position;
return result;
}
@Override
public byte get(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.get(index);
+ return wrapped.get(index);
+ }
+
+ @Override
+ public ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
+ return wrapped.get(dst, dstOffset, byteCount);
}
@Override
public char getChar() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- char result = this.wrapped.getChar();
- this.position += CHAR_SIZE;
+ wrapped.position(position);
+ char result = wrapped.getChar();
+ position += SizeOf.CHAR;
return result;
}
@Override
public char getChar(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.getChar(index);
+ return wrapped.getChar(index);
}
@Override
public double getDouble() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- double result = this.wrapped.getDouble();
- this.position += DOUBLE_SIZE;
+ wrapped.position(position);
+ double result = wrapped.getDouble();
+ position += SizeOf.DOUBLE;
return result;
}
@Override
public double getDouble(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.getDouble(index);
- }
-
- public PlatformAddress getEffectiveAddress() {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer) this.wrapped).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
+ return wrapped.getDouble(index);
}
@Override
public float getFloat() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- float result = this.wrapped.getFloat();
- this.position += FLOAT_SIZE;
+ wrapped.position(position);
+ float result = wrapped.getFloat();
+ position += SizeOf.FLOAT;
return result;
}
@Override
public float getFloat(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.getFloat(index);
+ return wrapped.getFloat(index);
}
@Override
public int getInt() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- int result = this.wrapped.getInt();
- this.position += INTEGER_SIZE;
+ wrapped.position(position);
+ int result = wrapped.getInt();
+ position += SizeOf.INT;
return result;
}
@Override
public int getInt(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.getInt(index);
+ return wrapped.getInt(index);
}
@Override
public long getLong() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- long result = this.wrapped.getLong();
- this.position += LONG_SIZE;
+ wrapped.position(position);
+ long result = wrapped.getLong();
+ position += SizeOf.LONG;
return result;
}
@Override
public long getLong(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.getLong(index);
+ return wrapped.getLong(index);
}
@Override
public short getShort() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- short result = this.wrapped.getShort();
- this.position += SHORT_SIZE;
+ wrapped.position(position);
+ short result = wrapped.getShort();
+ position += SizeOf.SHORT;
return result;
}
@Override
public short getShort(int index) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- return this.wrapped.getShort(index);
+ return wrapped.getShort(index);
}
@Override
@@ -242,185 +219,151 @@
@Override
public boolean isReadOnly() {
- return this.wrapped.isReadOnly();
+ return wrapped.isReadOnly();
}
- @Override
- ByteBuffer orderImpl(ByteOrder byteOrder) {
+ @Override void orderImpl(ByteOrder byteOrder) {
super.orderImpl(byteOrder);
- return this.wrapped.order(byteOrder);
+ wrapped.order(byteOrder);
}
@Override
public ByteBuffer put(byte b) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.put(b);
+ wrapped.position(this.position);
+ wrapped.put(b);
this.position++;
return this;
}
@Override
- public ByteBuffer put(byte[] src, int off, int len) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.put(src, off, len);
- this.position += len;
+ public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
+ wrapped.position(this.position);
+ wrapped.put(src, srcOffset, byteCount);
+ this.position += byteCount;
return this;
}
@Override
public ByteBuffer put(int index, byte b) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.put(index, b);
+ wrapped.position(this.position);
+ wrapped.put(index, b);
return this;
}
@Override
public ByteBuffer putChar(char value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putChar(value);
- this.position += CHAR_SIZE;
+ wrapped.position(this.position);
+ wrapped.putChar(value);
+ this.position += SizeOf.CHAR;
return this;
}
@Override
public ByteBuffer putChar(int index, char value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putChar(index, value);
+ wrapped.position(this.position);
+ wrapped.putChar(index, value);
return this;
}
@Override
public ByteBuffer putDouble(double value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putDouble(value);
- this.position += DOUBLE_SIZE;
+ wrapped.position(this.position);
+ wrapped.putDouble(value);
+ this.position += SizeOf.DOUBLE;
return this;
}
@Override
public ByteBuffer putDouble(int index, double value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putDouble(index, value);
+ wrapped.position(this.position);
+ wrapped.putDouble(index, value);
return this;
}
@Override
public ByteBuffer putFloat(float value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putFloat(value);
- this.position += FLOAT_SIZE;
+ wrapped.position(this.position);
+ wrapped.putFloat(value);
+ this.position += SizeOf.FLOAT;
return this;
}
@Override
public ByteBuffer putFloat(int index, float value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putFloat(index, value);
+ wrapped.position(this.position);
+ wrapped.putFloat(index, value);
return this;
}
@Override
public ByteBuffer putInt(int index, int value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putInt(index, value);
+ wrapped.position(this.position);
+ wrapped.putInt(index, value);
return this;
}
@Override
public ByteBuffer putInt(int value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putInt(value);
- this.position += INTEGER_SIZE;
+ wrapped.position(this.position);
+ wrapped.putInt(value);
+ this.position += SizeOf.INT;
return this;
}
@Override
public ByteBuffer putLong(int index, long value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putLong(index, value);
+ wrapped.position(this.position);
+ wrapped.putLong(index, value);
return this;
}
@Override
public ByteBuffer putLong(long value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putLong(value);
- this.position += LONG_SIZE;
+ wrapped.position(this.position);
+ wrapped.putLong(value);
+ this.position += SizeOf.LONG;
return this;
}
@Override
public ByteBuffer putShort(int index, short value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putShort(index, value);
+ wrapped.position(this.position);
+ wrapped.putShort(index, value);
return this;
}
@Override
public ByteBuffer putShort(short value) {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- this.wrapped.putShort(value);
- this.position += SHORT_SIZE;
+ wrapped.position(this.position);
+ wrapped.putShort(value);
+ this.position += SizeOf.SHORT;
return this;
}
@Override
public ByteBuffer slice() {
- this.wrapped.limit(this.limit);
- this.wrapped.position(this.position);
- MappedByteBufferAdapter result = new MappedByteBufferAdapter(
- this.wrapped.slice());
- this.wrapped.clear();
+ wrapped.position(this.position);
+ MappedByteBufferAdapter result = new MappedByteBufferAdapter(wrapped.slice());
+ wrapped.clear();
return result;
}
@Override
byte[] protectedArray() {
- return this.wrapped.protectedArray();
+ return wrapped.protectedArray();
}
@Override
int protectedArrayOffset() {
- return this.wrapped.protectedArrayOffset();
+ return wrapped.protectedArrayOffset();
}
@Override
boolean protectedHasArray() {
- return this.wrapped.protectedHasArray();
+ return wrapped.protectedHasArray();
}
- public PlatformAddress getBaseAddress() {
- return this.wrapped.getBaseAddress();
- }
-
- public boolean isAddressValid() {
- return this.wrapped.isAddressValid();
- }
-
- public void addressValidityCheck() {
- this.wrapped.addressValidityCheck();
- }
-
- public void free() {
- this.wrapped.free();
- }
-
- public int getByteCapacity() {
- return wrapped.getByteCapacity();
+ public final void free() {
+ wrapped.free();
}
}
diff --git a/luni/src/main/java/java/nio/MemoryBlock.java b/luni/src/main/java/java/nio/MemoryBlock.java
new file mode 100644
index 0000000..152965e
--- /dev/null
+++ b/luni/src/main/java/java/nio/MemoryBlock.java
@@ -0,0 +1,203 @@
+/*
+ * 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 java.nio;
+
+import java.io.IOException;
+import java.nio.channels.FileChannel.MapMode;
+import org.apache.harmony.luni.platform.OSMemory;
+
+class MemoryBlock {
+ /**
+ * Handles calling munmap(2) on a memory-mapped region.
+ */
+ private static class MemoryMappedBlock extends MemoryBlock {
+ private MemoryMappedBlock(int address, long byteCount) {
+ super(address, byteCount);
+ }
+
+ @Override public void free() {
+ if (address != 0) {
+ OSMemory.munmap(address, size);
+ address = 0;
+ }
+ }
+
+ @Override protected void finalize() throws Throwable {
+ free();
+ }
+ }
+
+ /**
+ * Handles calling free(3) on a native heap block.
+ */
+ private static class NativeHeapBlock extends MemoryBlock {
+ private NativeHeapBlock(int address, long byteCount) {
+ super(address, byteCount);
+ }
+
+ @Override public void free() {
+ if (address != 0) {
+ OSMemory.free(address);
+ address = 0;
+ }
+ }
+
+ @Override protected void finalize() throws Throwable {
+ free();
+ }
+ }
+
+ /**
+ * Represents a block of memory we don't own. (We don't take ownership of memory corresponding
+ * to direct buffers created by the JNI NewDirectByteBuffer function.)
+ */
+ private static class UnmanagedBlock extends MemoryBlock {
+ private UnmanagedBlock(int address, long byteCount) {
+ super(address, byteCount);
+ }
+ }
+
+ // TODO: should be long on 64-bit devices; int for performance.
+ protected int address;
+ protected final long size;
+
+ public static MemoryBlock mmap(int fd, long start, long size, MapMode mode) throws IOException {
+ if (size == 0) {
+ // You can't mmap(2) a zero-length region.
+ return new MemoryBlock(0, 0);
+ }
+ int address = OSMemory.mmap(fd, start, size, mode);
+ return new MemoryMappedBlock(address, size);
+ }
+
+ public static MemoryBlock malloc(int byteCount) {
+ return new NativeHeapBlock(OSMemory.malloc(byteCount), byteCount);
+ }
+
+ public static MemoryBlock wrapFromJni(int address, long byteCount) {
+ return new UnmanagedBlock(address, byteCount);
+ }
+
+ private MemoryBlock(int address, long size) {
+ this.address = address;
+ this.size = size;
+ }
+
+ public void free() {
+ }
+
+ public final void pokeByte(int offset, byte value) {
+ OSMemory.pokeByte(address + offset, value);
+ }
+
+ public final void pokeByteArray(int offset, byte[] src, int srcOffset, int byteCount) {
+ OSMemory.pokeByteArray(address + offset, src, srcOffset, byteCount);
+ }
+
+ public final void pokeCharArray(int offset, char[] src, int srcOffset, int charCount, boolean swap) {
+ OSMemory.pokeCharArray(address + offset, src, srcOffset, charCount, swap);
+ }
+
+ public final void pokeDoubleArray(int offset, double[] src, int srcOffset, int doubleCount, boolean swap) {
+ OSMemory.pokeDoubleArray(address + offset, src, srcOffset, doubleCount, swap);
+ }
+
+ public final void pokeFloatArray(int offset, float[] src, int srcOffset, int floatCount, boolean swap) {
+ OSMemory.pokeFloatArray(address + offset, src, srcOffset, floatCount, swap);
+ }
+
+ public final void pokeIntArray(int offset, int[] src, int srcOffset, int intCount, boolean swap) {
+ OSMemory.pokeIntArray(address + offset, src, srcOffset, intCount, swap);
+ }
+
+ public final void pokeLongArray(int offset, long[] src, int srcOffset, int longCount, boolean swap) {
+ OSMemory.pokeLongArray(address + offset, src, srcOffset, longCount, swap);
+ }
+
+ public final void pokeShortArray(int offset, short[] src, int srcOffset, int shortCount, boolean swap) {
+ OSMemory.pokeShortArray(address + offset, src, srcOffset, shortCount, swap);
+ }
+
+ public final byte peekByte(int offset) {
+ return OSMemory.peekByte(address + offset);
+ }
+
+ public final void peekByteArray(int offset, byte[] dst, int dstOffset, int byteCount) {
+ OSMemory.peekByteArray(address + offset, dst, dstOffset, byteCount);
+ }
+
+ public final void peekCharArray(int offset, char[] dst, int dstOffset, int charCount, boolean swap) {
+ OSMemory.peekCharArray(address + offset, dst, dstOffset, charCount, swap);
+ }
+
+ public final void peekDoubleArray(int offset, double[] dst, int dstOffset, int doubleCount, boolean swap) {
+ OSMemory.peekDoubleArray(address + offset, dst, dstOffset, doubleCount, swap);
+ }
+
+ public final void peekFloatArray(int offset, float[] dst, int dstOffset, int floatCount, boolean swap) {
+ OSMemory.peekFloatArray(address + offset, dst, dstOffset, floatCount, swap);
+ }
+
+ public final void peekIntArray(int offset, int[] dst, int dstOffset, int intCount, boolean swap) {
+ OSMemory.peekIntArray(address + offset, dst, dstOffset, intCount, swap);
+ }
+
+ public final void peekLongArray(int offset, long[] dst, int dstOffset, int longCount, boolean swap) {
+ OSMemory.peekLongArray(address + offset, dst, dstOffset, longCount, swap);
+ }
+
+ public final void peekShortArray(int offset, short[] dst, int dstOffset, int shortCount, boolean swap) {
+ OSMemory.peekShortArray(address + offset, dst, dstOffset, shortCount, swap);
+ }
+
+ public final void pokeShort(int offset, short value, ByteOrder order) {
+ OSMemory.pokeShort(address + offset, value, order.needsSwap);
+ }
+
+ public final short peekShort(int offset, ByteOrder order) {
+ return OSMemory.peekShort(address + offset, order.needsSwap);
+ }
+
+ public final void pokeInt(int offset, int value, ByteOrder order) {
+ OSMemory.pokeInt(address + offset, value, order.needsSwap);
+ }
+
+ public final int peekInt(int offset, ByteOrder order) {
+ return OSMemory.peekInt(address + offset, order.needsSwap);
+ }
+
+ public final void pokeLong(int offset, long value, ByteOrder order) {
+ OSMemory.pokeLong(address + offset, value, order.needsSwap);
+ }
+
+ public final long peekLong(int offset, ByteOrder order) {
+ return OSMemory.peekLong(address + offset, order.needsSwap);
+ }
+
+ public final int toInt() {
+ return address;
+ }
+
+ public final String toString() {
+ return getClass().getName() + "[" + address + "]";
+ }
+
+ public final long getSize() {
+ return size;
+ }
+}
diff --git a/luni/src/main/java/java/nio/NIOAccess.java b/luni/src/main/java/java/nio/NIOAccess.java
index 431cb8b..361a37f 100644
--- a/luni/src/main/java/java/nio/NIOAccess.java
+++ b/luni/src/main/java/java/nio/NIOAccess.java
@@ -16,13 +16,10 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
-
/**
* This class is used via JNI by code in frameworks/base/.
*/
-class NIOAccess {
+final class NIOAccess {
/**
* Returns the underlying native pointer to the data of the given
@@ -36,26 +33,11 @@
* position, or 0 if there is none
*/
static long getBasePointer(Buffer b) {
- if (b instanceof DirectBuffer) {
- PlatformAddress address = ((DirectBuffer) b).getEffectiveAddress();
- if (address == null) {
- return 0L;
- }
- return address.toInt() + (b.position() << b._elementSizeShift);
+ int address = b.effectiveDirectAddress;
+ if (address == 0) {
+ return 0L;
}
- return 0L;
- }
-
- /**
- * Returns the number of bytes remaining in the given Buffer. That is,
- * this scales <code>remaining()</code> by the byte-size of elements
- * of this Buffer.
- *
- * @param Buffer b the Buffer to be queried
- * @return the number of remaining bytes
- */
- static int getRemainingBytes(Buffer b) {
- return (b.limit - b.position) << b._elementSizeShift;
+ return address + (b.position << b._elementSizeShift);
}
/**
diff --git a/luni/src/main/java/java/nio/NioUtils.java b/luni/src/main/java/java/nio/NioUtils.java
new file mode 100644
index 0000000..5d7e7e2
--- /dev/null
+++ b/luni/src/main/java/java/nio/NioUtils.java
@@ -0,0 +1,87 @@
+/* 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 java.nio;
+
+import java.nio.channels.FileChannel;
+import org.apache.harmony.luni.platform.IFileSystem;
+
+/**
+ * @hide internal use only
+ */
+public final class NioUtils {
+ private NioUtils() {
+ }
+
+ /**
+ * Gets the start address of a direct buffer.
+ * <p>
+ * This method corresponds to the JNI function:
+ *
+ * <pre>
+ * void* GetDirectBufferAddress(JNIEnv* env, jobject buf);
+ * </pre>
+ *
+ * @param buf
+ * the direct buffer whose address shall be returned must not be
+ * <code>null</code>.
+ * @return the address of the buffer given, or zero if the buffer is not a
+ * direct Buffer.
+ */
+ public static int getDirectBufferAddress(Buffer buffer) {
+ return buffer.effectiveDirectAddress;
+ }
+
+ public static void freeDirectBuffer(ByteBuffer buffer) {
+ if (buffer == null) {
+ return;
+ }
+ if (buffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) buffer).free();
+ } else if (buffer instanceof MappedByteBuffer) {
+ ((MappedByteBufferAdapter) buffer).free();
+ } else {
+ throw new AssertionError();
+ }
+ }
+
+ /**
+ * Returns the int file descriptor from within the given FileChannel 'fc'.
+ */
+ public static int getFd(FileChannel fc) {
+ return ((FileChannelImpl) fc).getHandle();
+ }
+
+ /**
+ * Helps bridge between io and nio.
+ */
+ public static FileChannel newFileChannel(Object stream, int fd, int mode) {
+ switch (mode) {
+ case IFileSystem.O_RDONLY:
+ return new ReadOnlyFileChannel(stream, fd);
+ case IFileSystem.O_WRONLY:
+ return new WriteOnlyFileChannel(stream, fd);
+ case IFileSystem.O_RDWR:
+ return new ReadWriteFileChannel(stream, fd);
+ case IFileSystem.O_RDWRSYNC:
+ return new ReadWriteFileChannel(stream, fd);
+ case IFileSystem.O_APPEND:
+ return new WriteOnlyFileChannel(stream, fd, true);
+ default:
+ throw new RuntimeException("Unknown mode: " + mode);
+ }
+ }
+}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/PipeImpl.java b/luni/src/main/java/java/nio/PipeImpl.java
similarity index 98%
rename from luni/src/main/java/org/apache/harmony/nio/internal/PipeImpl.java
rename to luni/src/main/java/java/nio/PipeImpl.java
index 37c342c..2e6418e 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/PipeImpl.java
+++ b/luni/src/main/java/java/nio/PipeImpl.java
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.Closeable;
import java.io.FileDescriptor;
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.spi.SelectorProvider;
import libcore.io.IoUtils;
diff --git a/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java
index 3388fcc..6b1a03e 100644
--- a/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java
@@ -32,9 +32,9 @@
final class ReadOnlyCharArrayBuffer extends CharArrayBuffer {
static ReadOnlyCharArrayBuffer copy(CharArrayBuffer other, int markOfOther) {
- ReadOnlyCharArrayBuffer buf = new ReadOnlyCharArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadOnlyCharArrayBuffer buf =
+ new ReadOnlyCharArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -90,7 +90,7 @@
}
@Override
- public final CharBuffer put(char[] src, int off, int len) {
+ public final CharBuffer put(char[] src, int srcOffset, int charCount) {
throw new ReadOnlyBufferException();
}
@@ -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 6da6725..d061e9c 100644
--- a/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
@@ -17,8 +17,6 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-
/**
* DirectByteBuffer, ReadWriteDirectByteBuffer and ReadOnlyDirectByteBuffer
* compose the implementation of platform memory based byte buffers.
@@ -29,26 +27,18 @@
* <p>
* This class is marked final for runtime performance.
* </p>
- *
*/
final class ReadOnlyDirectByteBuffer extends DirectByteBuffer {
-
static ReadOnlyDirectByteBuffer copy(DirectByteBuffer other, int markOfOther) {
- ReadOnlyDirectByteBuffer buf = new ReadOnlyDirectByteBuffer(
- other.safeAddress, other.capacity(), other.offset);
- buf.limit = other.limit();
+ ReadOnlyDirectByteBuffer buf = new ReadOnlyDirectByteBuffer(other.block, other.capacity(), other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
- buf.order(other.order());
return buf;
}
- protected ReadOnlyDirectByteBuffer(SafeAddress address, int capacity, int offset) {
- super(address, capacity, offset);
- }
-
- protected ReadOnlyDirectByteBuffer(PlatformAddress address, int capacity, int offset) {
- super(new SafeAddress(address), capacity, offset);
+ protected ReadOnlyDirectByteBuffer(MemoryBlock block, int capacity, int offset) {
+ super(block, capacity, offset);
}
@Override
@@ -82,7 +72,7 @@
}
@Override
- public ByteBuffer put(byte[] src, int off, int len) {
+ public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
throw new ReadOnlyBufferException();
}
@@ -143,10 +133,6 @@
@Override
public ByteBuffer slice() {
- ReadOnlyDirectByteBuffer buf = new ReadOnlyDirectByteBuffer(
- safeAddress, 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 d3cf353..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);
- buf.limit = other.limit();
+ 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);
}
@@ -92,7 +90,7 @@
}
@Override
- public final DoubleBuffer put(double[] src, int off, int len) {
+ public final DoubleBuffer put(double[] src, int srcOffset, int byteCount) {
throw new ReadOnlyBufferException();
}
@@ -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/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java b/luni/src/main/java/java/nio/ReadOnlyFileChannel.java
similarity index 90%
rename from luni/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java
rename to luni/src/main/java/java/nio/ReadOnlyFileChannel.java
index 7cd64e3..851c1d1 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java
+++ b/luni/src/main/java/java/nio/ReadOnlyFileChannel.java
@@ -15,24 +15,16 @@
* limitations under the License.
*/
-/*
- * Android Notice
- * In this class the address length was changed from long to int.
- * This is due to performance optimizations for the device.
- */
-
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.MappedByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.ReadableByteChannel;
-public final class ReadOnlyFileChannel extends FileChannelImpl {
+final class ReadOnlyFileChannel extends FileChannelImpl {
public ReadOnlyFileChannel(Object stream, int handle) {
super(stream, handle);
}
diff --git a/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java
index f617a94..775e1d8 100644
--- a/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java
@@ -32,9 +32,9 @@
final class ReadOnlyFloatArrayBuffer extends FloatArrayBuffer {
static ReadOnlyFloatArrayBuffer copy(FloatArrayBuffer other, int markOfOther) {
- ReadOnlyFloatArrayBuffer buf = new ReadOnlyFloatArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadOnlyFloatArrayBuffer buf =
+ new ReadOnlyFloatArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -95,14 +95,13 @@
}
@Override
- public final FloatBuffer put(float[] src, int off, int len) {
+ public final FloatBuffer put(float[] src, int srcOffset, int byteCount) {
throw new ReadOnlyBufferException();
}
@Override
public FloatBuffer slice() {
- return new ReadOnlyFloatArrayBuffer(remaining(), backingArray, offset
- + position);
+ return new ReadOnlyFloatArrayBuffer(remaining(), backingArray, offset + position);
}
}
diff --git a/luni/src/main/java/java/nio/ReadOnlyHeapByteBuffer.java b/luni/src/main/java/java/nio/ReadOnlyHeapByteBuffer.java
index bee1e5d..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);
- buf.limit = other.limit();
+ 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;
}
@@ -91,7 +90,7 @@
}
@Override
- public ByteBuffer put(byte[] src, int off, int len) {
+ public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
throw new ReadOnlyBufferException();
}
@@ -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 12dd275..a137b3b 100644
--- a/luni/src/main/java/java/nio/ReadOnlyIntArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyIntArrayBuffer.java
@@ -32,9 +32,9 @@
final class ReadOnlyIntArrayBuffer extends IntArrayBuffer {
static ReadOnlyIntArrayBuffer copy(IntArrayBuffer other, int markOfOther) {
- ReadOnlyIntArrayBuffer buf = new ReadOnlyIntArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadOnlyIntArrayBuffer buf =
+ new ReadOnlyIntArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -95,14 +95,13 @@
}
@Override
- public final IntBuffer put(int[] src, int off, int len) {
+ public final IntBuffer put(int[] src, int srcOffset, int intCount) {
throw new ReadOnlyBufferException();
}
@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 fbe3249..87b0c88 100644
--- a/luni/src/main/java/java/nio/ReadOnlyLongArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyLongArrayBuffer.java
@@ -32,9 +32,9 @@
final class ReadOnlyLongArrayBuffer extends LongArrayBuffer {
static ReadOnlyLongArrayBuffer copy(LongArrayBuffer other, int markOfOther) {
- ReadOnlyLongArrayBuffer buf = new ReadOnlyLongArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadOnlyLongArrayBuffer buf =
+ new ReadOnlyLongArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -95,14 +95,13 @@
}
@Override
- public final LongBuffer put(long[] src, int off, int len) {
+ public final LongBuffer put(long[] src, int srcOffset, int longCount) {
throw new ReadOnlyBufferException();
}
@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 cf9d370..07b9c90 100644
--- a/luni/src/main/java/java/nio/ReadOnlyShortArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyShortArrayBuffer.java
@@ -32,9 +32,9 @@
final class ReadOnlyShortArrayBuffer extends ShortArrayBuffer {
static ReadOnlyShortArrayBuffer copy(ShortArrayBuffer other, int markOfOther) {
- ReadOnlyShortArrayBuffer buf = new ReadOnlyShortArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadOnlyShortArrayBuffer buf =
+ new ReadOnlyShortArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -95,14 +95,13 @@
}
@Override
- public final ShortBuffer put(short[] src, int off, int len) {
+ public final ShortBuffer put(short[] src, int srcOffset, int shortCount) {
throw new ReadOnlyBufferException();
}
@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 570efa4..546b3ce 100644
--- a/luni/src/main/java/java/nio/ReadWriteCharArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteCharArrayBuffer.java
@@ -31,9 +31,9 @@
final class ReadWriteCharArrayBuffer extends CharArrayBuffer {
static ReadWriteCharArrayBuffer copy(CharArrayBuffer other, int markOfOther) {
- ReadWriteCharArrayBuffer buf = new ReadWriteCharArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadWriteCharArrayBuffer buf =
+ new ReadWriteCharArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -58,8 +58,7 @@
@Override
public CharBuffer 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;
@@ -110,23 +109,22 @@
}
@Override
- public CharBuffer put(char[] src, int off, int len) {
+ public CharBuffer put(char[] src, int srcOffset, int charCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) len + (long) off > length) {
+ if (srcOffset < 0 || charCount < 0 || (long) charCount + (long) srcOffset > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (charCount > remaining()) {
throw new BufferOverflowException();
}
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ System.arraycopy(src, srcOffset, backingArray, offset + position, charCount);
+ position += charCount;
return this;
}
@Override
public CharBuffer slice() {
- return new ReadWriteCharArrayBuffer(remaining(), backingArray, offset
- + position);
+ return new ReadWriteCharArrayBuffer(remaining(), backingArray, offset + position);
}
}
diff --git a/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java b/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java
index e720c8a..71bd18b 100644
--- a/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java
@@ -17,9 +17,8 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.luni.platform.PlatformAddressFactory;
-// END android-added
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
/**
* DirectByteBuffer, ReadWriteDirectByteBuffer and ReadOnlyDirectByteBuffer
@@ -33,42 +32,29 @@
* </p>
*/
final class ReadWriteDirectByteBuffer extends DirectByteBuffer {
-
static ReadWriteDirectByteBuffer copy(DirectByteBuffer other, int markOfOther) {
- ReadWriteDirectByteBuffer buf = new ReadWriteDirectByteBuffer(
- other.safeAddress, other.capacity(), other.offset);
- buf.limit = other.limit();
+ 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;
}
+ // Used by ByteBuffer.allocateDirect.
ReadWriteDirectByteBuffer(int capacity) {
- super(capacity);
+ super(MemoryBlock.malloc(capacity), capacity, 0);
}
- // BEGIN android-added
- ReadWriteDirectByteBuffer(int pointer, int capacity) {
- this(PlatformAddressFactory.on(pointer, capacity),capacity,0);
- }
- // END android-added
-
- ReadWriteDirectByteBuffer(SafeAddress address, int capacity, int offset) {
- super(address, capacity, offset);
+ // Used by the JNI NewDirectByteBuffer function.
+ ReadWriteDirectByteBuffer(int address, int capacity) {
+ super(MemoryBlock.wrapFromJni(address, capacity), capacity, 0);
}
- ReadWriteDirectByteBuffer(PlatformAddress address, int aCapacity,
- int anOffset) {
- super(new SafeAddress(address), aCapacity, anOffset);
+ ReadWriteDirectByteBuffer(MemoryBlock block, int capacity, int offset) {
+ super(block, capacity, offset);
}
- // BEGIN android-added
- int getAddress() {
- return this.safeAddress.address.toInt();
- }
- // END android-added
-
@Override
public ByteBuffer asReadOnlyBuffer() {
return ReadOnlyDirectByteBuffer.copy(this, mark);
@@ -76,8 +62,8 @@
@Override
public ByteBuffer compact() {
- PlatformAddress effectiveAddress = getEffectiveAddress();
- effectiveAddress.offsetBytes(position).moveTo(effectiveAddress, remaining());
+ int addr = effectiveDirectAddress;
+ OSMemory.memmove(addr, addr + position, remaining());
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
@@ -99,7 +85,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- getBaseAddress().setByte(offset + position++, value);
+ this.block.pokeByte(offset + position++, value);
return this;
}
@@ -108,259 +94,177 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- getBaseAddress().setByte(offset + index, value);
+ this.block.pokeByte(offset + index, value);
return this;
}
- /*
- * Override ByteBuffer.put(byte[], int, int) to improve performance.
- *
- * (non-Javadoc)
- *
- * @see java.nio.ByteBuffer#put(byte[], int, int)
- */
- @Override
- public ByteBuffer put(byte[] src, int off, int len) {
- int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
- throw new IndexOutOfBoundsException();
- }
- if (len > remaining()) {
- throw new BufferOverflowException();
- }
- getBaseAddress().setByteArray(offset + position, src, off, len);
- position += len;
- return this;
- }
-
- // BEGIN android-added
- /**
- * Writes <code>short</code>s in the given short array, starting from the
- * specified offset, to the current position and increase the position by
- * the number of <code>short</code>s written.
- *
- * @param src
- * The source short array
- * @param off
- * The offset of short array, must be no less than zero and no
- * greater than <code>src.length</code>
- * @param len
- * The number of <code>short</code>s to write, must be no less
- * than zero and no greater than <code>src.length - off</code>
- * @return This buffer
- * @exception BufferOverflowException
- * If <code>remaining()</code> is less than
- * <code>len</code>
- * @exception IndexOutOfBoundsException
- * If either <code>off</code> or <code>len</code> is
- * invalid
- * @exception ReadOnlyBufferException
- * If no changes may be made to the contents of this buffer
- */
- ByteBuffer put(short[] src, int off, int len) {
- int length = src.length;
- if (off < 0 || len < 0 || (long)off + (long)len > length) {
- throw new IndexOutOfBoundsException();
- }
- if (len << 1 > remaining()) {
- throw new BufferOverflowException();
- }
- if (isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
- boolean swap = order() != ByteOrder.nativeOrder();
- getBaseAddress().setShortArray(offset + position, src, off, len, swap);
- position += len << 1;
- return this;
- }
-
- /**
- * Writes <code>int</code>s in the given int array, starting from the
- * specified offset, to the current position and increase the position by
- * the number of <code>int</code>s written.
- *
- * @param src
- * The source int array
- * @param off
- * The offset of int array, must be no less than zero and no
- * greater than <code>src.length</code>
- * @param len
- * The number of <code>int</code>s to write, must be no less
- * than zero and no greater than <code>src.length - off</code>
- * @return This buffer
- * @exception BufferOverflowException
- * If <code>remaining()</code> is less than
- * <code>len</code>
- * @exception IndexOutOfBoundsException
- * If either <code>off</code> or <code>len</code> is
- * invalid
- * @exception ReadOnlyBufferException
- * If no changes may be made to the contents of this buffer
- */
- ByteBuffer put(int[] src, int off, int len) {
- int length = src.length;
- if (off < 0 || len < 0 || (long)off + (long)len > length) {
- throw new IndexOutOfBoundsException();
- }
- if (len << 2 > remaining()) {
- throw new BufferOverflowException();
- }
- if (isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
- boolean swap = order() != ByteOrder.nativeOrder();
- getBaseAddress().setIntArray(offset + position, src, off, len, swap);
- position += len << 2;
- return this;
- }
-
- /**
- * Writes <code>float</code>s in the given float array, starting from the
- * specified offset, to the current position and increase the position by
- * the number of <code>float</code>s written.
- *
- * @param src
- * The source float array
- * @param off
- * The offset of float array, must be no less than zero and no
- * greater than <code>src.length</code>
- * @param len
- * The number of <code>float</code>s to write, must be no less
- * than zero and no greater than <code>src.length - off</code>
- * @return This buffer
- * @exception BufferOverflowException
- * If <code>remaining()</code> is less than
- * <code>len</code>
- * @exception IndexOutOfBoundsException
- * If either <code>off</code> or <code>len</code> is
- * invalid
- * @exception ReadOnlyBufferException
- * If no changes may be made to the contents of this buffer
- */
- ByteBuffer put(float[] src, int off, int len) {
- int length = src.length;
- if (off < 0 || len < 0 || (long)off + (long)len > length) {
- throw new IndexOutOfBoundsException();
- }
- if (len << 2 > remaining()) {
- throw new BufferOverflowException();
- }
- if (isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
- boolean swap = order() != ByteOrder.nativeOrder();
- getBaseAddress().setFloatArray(offset + position, src, off, len, swap);
- position += len << 2;
- return this;
- }
- // END android-added
-
@Override
- public ByteBuffer putDouble(double value) {
- int newPosition = position + 8;
+ public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
+ checkPutBounds(1, src.length, srcOffset, byteCount);
+ this.block.pokeByteArray(offset + position, src, srcOffset, byteCount);
+ position += byteCount;
+ return this;
+ }
+
+ final void put(char[] src, int srcOffset, int 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ this.block.pokeShortArray(offset + position, src, srcOffset, shortCount, order.needsSwap);
+ position += byteCount;
+ }
+
+ @Override
+ public ByteBuffer putChar(char value) {
+ int newPosition = position + SizeOf.CHAR;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- getBaseAddress().setDouble(offset + position, value, order);
+ this.block.pokeShort(offset + position, (short) value, order);
+ position = newPosition;
+ return this;
+ }
+
+ @Override
+ public ByteBuffer putChar(int index, char value) {
+ if (index < 0 || (long) index + SizeOf.CHAR > limit) {
+ throw new IndexOutOfBoundsException();
+ }
+ this.block.pokeShort(offset + index, (short) value, order);
+ return this;
+ }
+
+ @Override
+ public ByteBuffer putDouble(double value) {
+ int newPosition = position + SizeOf.DOUBLE;
+ if (newPosition > limit) {
+ throw new BufferOverflowException();
+ }
+ this.block.pokeLong(offset + position, Double.doubleToRawLongBits(value), order);
position = newPosition;
return this;
}
@Override
public ByteBuffer putDouble(int index, double value) {
- if (index < 0 || (long) index + 8 > limit) {
+ if (index < 0 || (long) index + SizeOf.DOUBLE > limit) {
throw new IndexOutOfBoundsException();
}
- getBaseAddress().setDouble(offset + index, value, order);
+ this.block.pokeLong(offset + index, Double.doubleToRawLongBits(value), order);
return this;
}
@Override
public ByteBuffer putFloat(float value) {
- int newPosition = position + 4;
+ int newPosition = position + SizeOf.FLOAT;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- getBaseAddress().setFloat(offset + position, value, order);
+ this.block.pokeInt(offset + position, Float.floatToRawIntBits(value), order);
position = newPosition;
return this;
}
@Override
public ByteBuffer putFloat(int index, float value) {
- if (index < 0 || (long) index + 4 > limit) {
+ if (index < 0 || (long) index + SizeOf.FLOAT > limit) {
throw new IndexOutOfBoundsException();
}
- getBaseAddress().setFloat(offset + index, value, order);
+ this.block.pokeInt(offset + index, Float.floatToRawIntBits(value), order);
return this;
}
@Override
public ByteBuffer putInt(int value) {
- int newPosition = position + 4;
+ int newPosition = position + SizeOf.INT;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- getBaseAddress().setInt(offset + position, value, order);
+ this.block.pokeInt(offset + position, value, order);
position = newPosition;
return this;
}
@Override
public ByteBuffer putInt(int index, int value) {
- if (index < 0 || (long) index + 4 > limit) {
+ if (index < 0 || (long) index + SizeOf.INT > limit) {
throw new IndexOutOfBoundsException();
}
- getBaseAddress().setInt(offset + index, value, order);
+ this.block.pokeInt(offset + index, value, order);
return this;
}
@Override
public ByteBuffer putLong(long value) {
- int newPosition = position + 8;
+ int newPosition = position + SizeOf.LONG;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- getBaseAddress().setLong(offset + position, value, order);
+ this.block.pokeLong(offset + position, value, order);
position = newPosition;
return this;
}
@Override
public ByteBuffer putLong(int index, long value) {
- if (index < 0 || (long) index + 8 > limit) {
+ if (index < 0 || (long) index + SizeOf.LONG > limit) {
throw new IndexOutOfBoundsException();
}
- getBaseAddress().setLong(offset + index, value, order);
+ this.block.pokeLong(offset + index, value, order);
return this;
}
@Override
public ByteBuffer putShort(short value) {
- int newPosition = position + 2;
+ int newPosition = position + SizeOf.SHORT;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- getBaseAddress().setShort(offset + position, value, order);
+ this.block.pokeShort(offset + position, value, order);
position = newPosition;
return this;
}
@Override
public ByteBuffer putShort(int index, short value) {
- if (index < 0 || (long) index + 2 > limit) {
+ if (index < 0 || (long) index + SizeOf.SHORT > limit) {
throw new IndexOutOfBoundsException();
}
- getBaseAddress().setShort(offset + index, value, order);
+ this.block.pokeShort(offset + index, value, order);
return this;
}
@Override
public ByteBuffer slice() {
- ReadWriteDirectByteBuffer buf = new ReadWriteDirectByteBuffer(
- safeAddress, 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 c7d4d94..880b339 100644
--- a/luni/src/main/java/java/nio/ReadWriteDoubleArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteDoubleArrayBuffer.java
@@ -31,11 +31,10 @@
*/
final class ReadWriteDoubleArrayBuffer extends DoubleArrayBuffer {
- static ReadWriteDoubleArrayBuffer copy(DoubleArrayBuffer other,
- int markOfOther) {
- ReadWriteDoubleArrayBuffer buf = new ReadWriteDoubleArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ static ReadWriteDoubleArrayBuffer copy(DoubleArrayBuffer other, int markOfOther) {
+ ReadWriteDoubleArrayBuffer buf =
+ new ReadWriteDoubleArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -49,8 +48,7 @@
super(capacity);
}
- ReadWriteDoubleArrayBuffer(int capacity, double[] backingArray,
- int arrayOffset) {
+ ReadWriteDoubleArrayBuffer(int capacity, double[] backingArray, int arrayOffset) {
super(capacity, backingArray, arrayOffset);
}
@@ -61,8 +59,7 @@
@Override
public DoubleBuffer 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;
@@ -113,23 +110,22 @@
}
@Override
- public DoubleBuffer put(double[] src, int off, int len) {
+ public DoubleBuffer put(double[] src, int srcOffset, int doubleCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || doubleCount < 0 || (long) srcOffset + (long) doubleCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (doubleCount > remaining()) {
throw new BufferOverflowException();
}
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ System.arraycopy(src, srcOffset, backingArray, offset + position, doubleCount);
+ position += doubleCount;
return this;
}
@Override
public DoubleBuffer slice() {
- return new ReadWriteDoubleArrayBuffer(remaining(), backingArray, offset
- + position);
+ return new ReadWriteDoubleArrayBuffer(remaining(), backingArray, offset + position);
}
}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/ReadWriteFileChannel.java b/luni/src/main/java/java/nio/ReadWriteFileChannel.java
similarity index 81%
rename from luni/src/main/java/org/apache/harmony/nio/internal/ReadWriteFileChannel.java
rename to luni/src/main/java/java/nio/ReadWriteFileChannel.java
index ef888b1..a458a6c 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/ReadWriteFileChannel.java
+++ b/luni/src/main/java/java/nio/ReadWriteFileChannel.java
@@ -15,18 +15,11 @@
* limitations under the License.
*/
-/*
- * Android Notice
- * In this class the address length was changed from long to int.
- * This is due to performance optimizations for the device.
- */
-
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.IOException;
-import java.nio.MappedByteBuffer;
-public final class ReadWriteFileChannel extends FileChannelImpl {
+final class ReadWriteFileChannel extends FileChannelImpl {
public ReadWriteFileChannel(Object stream, int handle) {
super(stream, handle);
}
diff --git a/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java
index 838172f..bf2f485 100644
--- a/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java
@@ -31,11 +31,10 @@
*/
final class ReadWriteFloatArrayBuffer extends FloatArrayBuffer {
- static ReadWriteFloatArrayBuffer copy(FloatArrayBuffer other,
- int markOfOther) {
- ReadWriteFloatArrayBuffer buf = new ReadWriteFloatArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ static ReadWriteFloatArrayBuffer copy(FloatArrayBuffer other, int markOfOther) {
+ ReadWriteFloatArrayBuffer buf =
+ new ReadWriteFloatArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -49,8 +48,7 @@
super(capacity);
}
- ReadWriteFloatArrayBuffer(int capacity, float[] backingArray,
- int arrayOffset) {
+ ReadWriteFloatArrayBuffer(int capacity, float[] backingArray, int arrayOffset) {
super(capacity, backingArray, arrayOffset);
}
@@ -61,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;
@@ -113,23 +110,22 @@
}
@Override
- public FloatBuffer put(float[] src, int off, int len) {
+ public FloatBuffer put(float[] src, int srcOffset, int floatCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || floatCount < 0 || (long) srcOffset + (long) floatCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (floatCount > remaining()) {
throw new BufferOverflowException();
}
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ System.arraycopy(src, srcOffset, backingArray, offset + position, floatCount);
+ position += floatCount;
return this;
}
@Override
public FloatBuffer slice() {
- return new ReadWriteFloatArrayBuffer(remaining(), backingArray, offset
- + position);
+ return new ReadWriteFloatArrayBuffer(remaining(), backingArray, offset + position);
}
}
diff --git a/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java b/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java
index cbf41b8..7cd1c5c 100644
--- a/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java
@@ -16,6 +16,9 @@
package java.nio;
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
+
/**
* HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose
* the implementation of array based byte buffers.
@@ -30,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);
- buf.limit = other.limit();
+ 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;
}
@@ -58,8 +60,7 @@
@Override
public ByteBuffer 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;
@@ -109,26 +110,67 @@
return this;
}
- /*
- * Override ByteBuffer.put(byte[], int, int) to improve performance.
- *
- * (non-Javadoc)
- *
- * @see java.nio.ByteBuffer#put(byte[], int, int)
- */
@Override
- public ByteBuffer put(byte[] src, int off, int len) {
- if (off < 0 || len < 0 || (long) off + (long) len > src.length) {
+ public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
+ checkPutBounds(1, src.length, srcOffset, byteCount);
+ System.arraycopy(src, srcOffset, backingArray, offset + position, byteCount);
+ position += byteCount;
+ return this;
+ }
+
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ 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);
+ position += byteCount;
+ }
+
+ @Override
+ public ByteBuffer putChar(int index, char value) {
+ if (index < 0 || (long) index + SizeOf.CHAR > limit) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ OSMemory.pokeShort(backingArray, offset + index, (short) value, order);
+ return this;
+ }
+
+ @Override
+ public ByteBuffer putChar(char value) {
+ int newPosition = position + SizeOf.CHAR;
+ if (newPosition > limit) {
throw new BufferOverflowException();
}
- if (isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ OSMemory.pokeShort(backingArray, offset + position, (short) value, order);
+ position = newPosition;
return this;
}
@@ -144,79 +186,76 @@
@Override
public ByteBuffer putFloat(float value) {
- return putInt(Float.floatToIntBits(value));
+ return putInt(Float.floatToRawIntBits(value));
}
@Override
public ByteBuffer putFloat(int index, float value) {
- return putInt(index, Float.floatToIntBits(value));
+ return putInt(index, Float.floatToRawIntBits(value));
}
@Override
public ByteBuffer putInt(int value) {
- int newPosition = position + 4;
+ int newPosition = position + SizeOf.INT;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- store(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 + 4 > limit) {
+ if (index < 0 || (long) index + SizeOf.INT > limit) {
throw new IndexOutOfBoundsException();
}
- store(index, value);
+ OSMemory.pokeInt(backingArray, offset + index, value, order);
return this;
}
@Override
public ByteBuffer putLong(int index, long value) {
- if (index < 0 || (long) index + 8 > limit) {
+ if (index < 0 || (long) index + SizeOf.LONG > limit) {
throw new IndexOutOfBoundsException();
}
- store(index, value);
+ OSMemory.pokeLong(backingArray, offset + index, value, order);
return this;
}
@Override
public ByteBuffer putLong(long value) {
- int newPosition = position + 8;
+ int newPosition = position + SizeOf.LONG;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- store(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 + 2 > limit) {
+ if (index < 0 || (long) index + SizeOf.SHORT > limit) {
throw new IndexOutOfBoundsException();
}
- store(index, value);
+ OSMemory.pokeShort(backingArray, offset + index, value, order);
return this;
}
@Override
public ByteBuffer putShort(short value) {
- int newPosition = position + 2;
+ int newPosition = position + SizeOf.SHORT;
if (newPosition > limit) {
throw new BufferOverflowException();
}
- store(position, value);
+ OSMemory.pokeShort(backingArray, offset + position, value, order);
position = newPosition;
return this;
}
@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 9aa74d7..72dffcb 100644
--- a/luni/src/main/java/java/nio/ReadWriteIntArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteIntArrayBuffer.java
@@ -31,9 +31,9 @@
final class ReadWriteIntArrayBuffer extends IntArrayBuffer {
static ReadWriteIntArrayBuffer copy(IntArrayBuffer other, int markOfOther) {
- ReadWriteIntArrayBuffer buf = new ReadWriteIntArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadWriteIntArrayBuffer buf =
+ new ReadWriteIntArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -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;
@@ -110,23 +109,22 @@
}
@Override
- public IntBuffer put(int[] src, int off, int len) {
+ public IntBuffer put(int[] src, int srcOffset, int intCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || intCount < 0 || (long) srcOffset + (long) intCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (intCount > remaining()) {
throw new BufferOverflowException();
}
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ System.arraycopy(src, srcOffset, backingArray, offset + position, intCount);
+ position += intCount;
return this;
}
@Override
public IntBuffer slice() {
- return new ReadWriteIntArrayBuffer(remaining(), backingArray, offset
- + position);
+ return new ReadWriteIntArrayBuffer(remaining(), backingArray, offset + position);
}
}
diff --git a/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java
index 2a7e332..e5c5aa3 100644
--- a/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java
@@ -31,9 +31,9 @@
final class ReadWriteLongArrayBuffer extends LongArrayBuffer {
static ReadWriteLongArrayBuffer copy(LongArrayBuffer other, int markOfOther) {
- ReadWriteLongArrayBuffer buf = new ReadWriteLongArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ ReadWriteLongArrayBuffer buf =
+ new ReadWriteLongArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -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;
@@ -110,23 +109,22 @@
}
@Override
- public LongBuffer put(long[] src, int off, int len) {
+ public LongBuffer put(long[] src, int srcOffset, int longCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || longCount < 0 || (long) srcOffset + (long) longCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (longCount > remaining()) {
throw new BufferOverflowException();
}
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ System.arraycopy(src, srcOffset, backingArray, offset + position, longCount);
+ position += longCount;
return this;
}
@Override
public LongBuffer slice() {
- return new ReadWriteLongArrayBuffer(remaining(), backingArray, offset
- + position);
+ return new ReadWriteLongArrayBuffer(remaining(), backingArray, offset + position);
}
}
diff --git a/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java
index f3b4220..727d8c2 100644
--- a/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java
@@ -31,11 +31,10 @@
*/
final class ReadWriteShortArrayBuffer extends ShortArrayBuffer {
- static ReadWriteShortArrayBuffer copy(ShortArrayBuffer other,
- int markOfOther) {
- ReadWriteShortArrayBuffer buf = new ReadWriteShortArrayBuffer(other
- .capacity(), other.backingArray, other.offset);
- buf.limit = other.limit();
+ static ReadWriteShortArrayBuffer copy(ShortArrayBuffer other, int markOfOther) {
+ ReadWriteShortArrayBuffer buf =
+ new ReadWriteShortArrayBuffer(other.capacity(), other.backingArray, other.offset);
+ buf.limit = other.limit;
buf.position = other.position();
buf.mark = markOfOther;
return buf;
@@ -61,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;
@@ -113,23 +111,22 @@
}
@Override
- public ShortBuffer put(short[] src, int off, int len) {
+ public ShortBuffer put(short[] src, int srcOffset, int shortCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || shortCount < 0 || (long) srcOffset + (long) shortCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (shortCount > remaining()) {
throw new BufferOverflowException();
}
- System.arraycopy(src, off, backingArray, offset + position, len);
- position += len;
+ System.arraycopy(src, srcOffset, backingArray, offset + position, shortCount);
+ position += shortCount;
return this;
}
@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/org/apache/harmony/nio/internal/SelectionKeyImpl.java b/luni/src/main/java/java/nio/SelectionKeyImpl.java
similarity index 84%
rename from luni/src/main/java/org/apache/harmony/nio/internal/SelectionKeyImpl.java
rename to luni/src/main/java/java/nio/SelectionKeyImpl.java
index c6e9930..694770e 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/SelectionKeyImpl.java
+++ b/luni/src/main/java/java/nio/SelectionKeyImpl.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectableChannel;
@@ -37,10 +37,6 @@
private SelectorImpl selector;
- // BEGIN android-removed
- // private int index;
- // END android-removed
-
public SelectionKeyImpl(AbstractSelectableChannel channel, int operations,
Object attachment, SelectorImpl selector) {
this.channel = channel;
@@ -76,9 +72,6 @@
}
synchronized (selector.keysLock) {
interestOps = operations;
- // BEGIN android-removed
- // selector.modKey(this);
- // END android-removed
}
return this;
}
@@ -101,16 +94,6 @@
this.readyOps = readyOps;
}
- // BEGIN android-removed
- // int getIndex() {
- // return index;
- // }
-
- // void setIndex(int index) {
- // this.index = index;
- // }
- // END android-removed
-
private void checkValid() {
if (!isValid()) {
throw new CancelledKeyException();
@@ -122,7 +105,6 @@
* does not need connecting, this always return true.
*/
boolean isConnected() {
- return !(channel instanceof SocketChannel)
- || ((SocketChannel) channel).isConnected();
+ return !(channel instanceof SocketChannel) || ((SocketChannel) channel).isConnected();
}
}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/SelectorImpl.java b/luni/src/main/java/java/nio/SelectorImpl.java
similarity index 97%
rename from luni/src/main/java/org/apache/harmony/nio/internal/SelectorImpl.java
rename to luni/src/main/java/java/nio/SelectorImpl.java
index 35e383f..e01181a 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/SelectorImpl.java
+++ b/luni/src/main/java/java/nio/SelectorImpl.java
@@ -13,11 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.FileDescriptor;
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.IllegalSelectorException;
import java.nio.channels.Pipe;
@@ -71,8 +70,7 @@
/**
* Used to synchronize when a key's interest ops change.
*/
- private static class KeysLock {}
- final Object keysLock = new KeysLock();
+ final Object keysLock = new Object();
private final Set<SelectionKeyImpl> mutableKeys = new HashSet<SelectionKeyImpl>();
@@ -217,8 +215,8 @@
if (isBlock) {
begin();
}
- success = Platform.getNetworkSystem().select(
- readableFDs, writableFDs, readableKeysCount, writableKeysCount, timeout, flags);
+ success = Platform.NETWORK.select(readableFDs, writableFDs,
+ readableKeysCount, writableKeysCount, timeout, flags);
} finally {
if (isBlock) {
end();
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/SelectorProviderImpl.java b/luni/src/main/java/java/nio/SelectorProviderImpl.java
similarity index 70%
rename from luni/src/main/java/org/apache/harmony/nio/internal/SelectorProviderImpl.java
rename to luni/src/main/java/java/nio/SelectorProviderImpl.java
index 0c75808..03003fe 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/SelectorProviderImpl.java
+++ b/luni/src/main/java/java/nio/SelectorProviderImpl.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.IOException;
import java.nio.channels.DatagramChannel;
@@ -25,49 +25,26 @@
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
-/*
- * Internal implementation of SelectorProvider.
+/**
+ * @hide for java.nio.channels.spi.SelectorProvider only.
*/
-public class SelectorProviderImpl extends SelectorProvider {
-
- /*
- * Constructor for this class.
- */
- public SelectorProviderImpl() {
- super();
- }
-
- /**
- * @see java.nio.channels.spi.SelectorProvider#openDatagramChannel()
- */
+public final class SelectorProviderImpl extends SelectorProvider {
public DatagramChannel openDatagramChannel() throws IOException {
return new DatagramChannelImpl(this);
}
- /**
- * @see java.nio.channels.spi.SelectorProvider#openPipe()
- */
public Pipe openPipe() throws IOException {
return new PipeImpl();
}
- /**
- * @see java.nio.channels.spi.SelectorProvider#openSelector()
- */
public AbstractSelector openSelector() throws IOException {
return new SelectorImpl(this);
}
- /**
- * @see java.nio.channels.spi.SelectorProvider#openServerSocketChannel()
- */
public ServerSocketChannel openServerSocketChannel() throws IOException {
return new ServerSocketChannelImpl(this);
}
- /**
- * @see java.nio.channels.spi.SelectorProvider#openSocketChannel()
- */
public SocketChannel openSocketChannel() throws IOException {
return new SocketChannelImpl(this);
}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/ServerSocketChannelImpl.java b/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
similarity index 94%
rename from luni/src/main/java/org/apache/harmony/nio/internal/ServerSocketChannelImpl.java
rename to luni/src/main/java/java/nio/ServerSocketChannelImpl.java
index 75e9910..abea8cf 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/ServerSocketChannelImpl.java
+++ b/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.FileDescriptor;
import java.io.IOException;
@@ -37,8 +37,7 @@
/**
* The default ServerSocketChannel.
*/
-public final class ServerSocketChannelImpl
- extends ServerSocketChannel implements FileDescriptorHandler {
+final class ServerSocketChannelImpl extends ServerSocketChannel implements FileDescriptorHandler {
private final FileDescriptor fd = new FileDescriptor();
private final SocketImpl impl = new PlainServerSocketImpl(fd);
@@ -46,8 +45,7 @@
private boolean isBound = false;
- private static class AcceptLock {}
- private final Object acceptLock = new AcceptLock();
+ private final Object acceptLock = new Object();
public ServerSocketChannelImpl(SelectorProvider sp) throws IOException {
super(sp);
@@ -83,8 +81,7 @@
boolean isBlocking = isBlocking();
if (!isBlocking) {
int[] tryResult = new int[1];
- boolean success = Platform.getNetworkSystem().select(
- new FileDescriptor[] { fd },
+ boolean success = Platform.NETWORK.select(new FileDescriptor[] { fd },
new FileDescriptor[0], 1, 0, 0, tryResult);
if (!success || 0 == tryResult[0]) {
// no pending connections, returns immediately.
diff --git a/luni/src/main/java/java/nio/ShortArrayBuffer.java b/luni/src/main/java/java/nio/ShortArrayBuffer.java
index e6d96ed..253a305 100644
--- a/luni/src/main/java/java/nio/ShortArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ShortArrayBuffer.java
@@ -66,16 +66,16 @@
}
@Override
- public final ShortBuffer get(short[] dst, int off, int len) {
+ public final ShortBuffer get(short[] dst, int dstOffset, int shortCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (dstOffset < 0 || shortCount < 0 || (long) dstOffset + (long) shortCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (shortCount > remaining()) {
throw new BufferUnderflowException();
}
- System.arraycopy(backingArray, offset + position, dst, off, len);
- position += len;
+ System.arraycopy(backingArray, offset + position, dst, dstOffset, shortCount);
+ position += shortCount;
return this;
}
diff --git a/luni/src/main/java/java/nio/ShortBuffer.java b/luni/src/main/java/java/nio/ShortBuffer.java
index c0fd0e7..02d9050 100644
--- a/luni/src/main/java/java/nio/ShortBuffer.java
+++ b/luni/src/main/java/java/nio/ShortBuffer.java
@@ -46,7 +46,7 @@
if (capacity < 0) {
throw new IllegalArgumentException();
}
- return BufferFactory.newShortBuffer(capacity);
+ return new ReadWriteShortArrayBuffer(capacity);
}
/**
@@ -67,44 +67,37 @@
* Creates a new short buffer by wrapping the given short array.
* <p>
* The new buffer's position will be {@code start}, limit will be
- * {@code start + len}, capacity will be the length of the array.
+ * {@code start + shortCount}, capacity will be the length of the array.
*
* @param array
* the short array which the new buffer will be based on.
* @param start
* the start index, must not be negative and not greater than
* {@code array.length}.
- * @param len
+ * @param shortCount
* the length, must not be negative and not greater than
* {@code array.length - start}.
* @return the created short buffer.
* @exception IndexOutOfBoundsException
- * if either {@code start} or {@code len} is invalid.
+ * if either {@code start} or {@code shortCount} is invalid.
*/
- public static ShortBuffer wrap(short[] array, int start, int len) {
+ public static ShortBuffer wrap(short[] array, int start, int shortCount) {
if (array == null) {
throw new NullPointerException();
}
- if (start < 0 || len < 0 || (long) start + (long) len > array.length) {
+ if (start < 0 || shortCount < 0 || (long) start + (long) shortCount > array.length) {
throw new IndexOutOfBoundsException();
}
- ShortBuffer buf = BufferFactory.newShortBuffer(array);
+ ShortBuffer buf = new ReadWriteShortArrayBuffer(array);
buf.position = start;
- buf.limit = start + len;
+ buf.limit = start + shortCount;
return buf;
}
- /**
- * Constructs a {@code ShortBuffer} with given capacity.
- *
- * @param capacity
- * The capacity of the buffer
- */
ShortBuffer(int capacity) {
- super(capacity);
- _elementSizeShift = 1;
+ super(1, capacity, null);
}
public final short[] array() {
@@ -256,27 +249,27 @@
*
* @param dst
* the target short array.
- * @param off
+ * @param dstOffset
* the offset of the short array, must not be negative and not
* greater than {@code dst.length}.
- * @param len
+ * @param shortCount
* the number of shorts to read, must be no less than zero and
- * not greater than {@code dst.length - off}.
+ * not greater than {@code dst.length - dstOffset}.
* @return this buffer.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code dstOffset} or {@code shortCount} is invalid.
* @exception BufferUnderflowException
- * if {@code len} is greater than {@code remaining()}.
+ * if {@code shortCount} is greater than {@code remaining()}.
*/
- public ShortBuffer get(short[] dst, int off, int len) {
+ public ShortBuffer get(short[] dst, int dstOffset, int shortCount) {
int length = dst.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (dstOffset < 0 || shortCount < 0 || (long) dstOffset + (long) shortCount > length) {
throw new IndexOutOfBoundsException();
}
- if (len > remaining()) {
+ if (shortCount > remaining()) {
throw new BufferUnderflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = dstOffset; i < dstOffset + shortCount; ++i) {
dst[i] = get();
}
return this;
@@ -398,30 +391,29 @@
*
* @param src
* the source short array.
- * @param off
+ * @param srcOffset
* the offset of short array, must not be negative and not
* greater than {@code src.length}.
- * @param len
+ * @param shortCount
* the number of shorts to write, must be no less than zero and
- * not greater than {@code src.length - off}.
+ * not greater than {@code src.length - srcOffset}.
* @return this buffer.
* @exception BufferOverflowException
- * if {@code remaining()} is less than {@code len}.
+ * if {@code remaining()} is less than {@code shortCount}.
* @exception IndexOutOfBoundsException
- * if either {@code off} or {@code len} is invalid.
+ * if either {@code srcOffset} or {@code shortCount} is invalid.
* @exception ReadOnlyBufferException
* if no changes may be made to the contents of this buffer.
*/
- public ShortBuffer put(short[] src, int off, int len) {
+ public ShortBuffer put(short[] src, int srcOffset, int shortCount) {
int length = src.length;
- if (off < 0 || len < 0 || (long) off + (long) len > length) {
+ if (srcOffset < 0 || shortCount < 0 || (long) srcOffset + (long) shortCount > length) {
throw new IndexOutOfBoundsException();
}
-
- if (len > remaining()) {
+ if (shortCount > remaining()) {
throw new BufferOverflowException();
}
- for (int i = off; i < off + len; i++) {
+ for (int i = srcOffset; i < srcOffset + shortCount; ++i) {
put(src[i]);
}
return this;
@@ -488,22 +480,4 @@
* @return a sliced buffer that shares its content with this buffer.
*/
public abstract ShortBuffer slice();
-
- /**
- * Returns a string representing the state of this short buffer.
- *
- * @return a string representing the state of this short buffer.
- */
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder();
- buf.append(getClass().getName());
- buf.append(", status: capacity=");
- buf.append(capacity());
- buf.append(" position=");
- buf.append(position());
- buf.append(" limit=");
- buf.append(limit());
- return buf.toString();
- }
}
diff --git a/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java b/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java
index d534460..0f6e680 100644
--- a/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java
@@ -16,8 +16,7 @@
package java.nio;
-import org.apache.harmony.luni.platform.PlatformAddress;
-import org.apache.harmony.nio.internal.DirectBuffer;
+import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a short buffer.
@@ -31,77 +30,26 @@
* </ul>
* </p>
*/
-final class ShortToByteBufferAdapter extends ShortBuffer implements
- DirectBuffer {
-
- static ShortBuffer wrap(ByteBuffer byteBuffer) {
- return new ShortToByteBufferAdapter(byteBuffer.slice());
- }
+final class ShortToByteBufferAdapter extends ShortBuffer {
private final ByteBuffer byteBuffer;
- ShortToByteBufferAdapter(ByteBuffer byteBuffer) {
- super((byteBuffer.capacity() >> 1));
+ 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();
- }
-
- public int getByteCapacity() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getByteCapacity();
- }
- assert false : byteBuffer;
- return -1;
- }
-
- public PlatformAddress getEffectiveAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- // BEGIN android-changed
- PlatformAddress addr = ((DirectBuffer)byteBuffer).getEffectiveAddress();
- effectiveDirectAddress = addr.toInt();
- return addr;
- // END android-changed
- }
- assert false : byteBuffer;
- return null;
- }
-
- public PlatformAddress getBaseAddress() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).getBaseAddress();
- }
- assert false : byteBuffer;
- return null;
- }
-
- public boolean isAddressValid() {
- if (byteBuffer instanceof DirectBuffer) {
- return ((DirectBuffer) byteBuffer).isAddressValid();
- }
- assert false : byteBuffer;
- return false;
- }
-
- public void addressValidityCheck() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).addressValidityCheck();
- } else {
- assert false : byteBuffer;
- }
- }
-
- public void free() {
- if (byteBuffer instanceof DirectBuffer) {
- ((DirectBuffer) byteBuffer).free();
- } else {
- assert false : byteBuffer;
- }
+ this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public ShortBuffer asReadOnlyBuffer() {
- ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer
- .asReadOnlyBuffer());
+ ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -113,8 +61,8 @@
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
- byteBuffer.limit(limit << 1);
- byteBuffer.position(position << 1);
+ byteBuffer.limit(limit * SizeOf.SHORT);
+ byteBuffer.position(position * SizeOf.SHORT);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
@@ -125,8 +73,7 @@
@Override
public ShortBuffer duplicate() {
- ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer
- .duplicate());
+ ShortToByteBufferAdapter buf = new ShortToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
@@ -138,7 +85,7 @@
if (position == limit) {
throw new BufferUnderflowException();
}
- return byteBuffer.getShort(position++ << 1);
+ return byteBuffer.getShort(position++ * SizeOf.SHORT);
}
@Override
@@ -146,7 +93,20 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- return byteBuffer.getShort(index << 1);
+ 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);
+ if (byteBuffer instanceof DirectByteBuffer) {
+ ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, shortCount);
+ } else {
+ ((HeapByteBuffer) byteBuffer).get(dst, dstOffset, shortCount);
+ }
+ this.position += shortCount;
+ return this;
}
@Override
@@ -184,7 +144,7 @@
if (position == limit) {
throw new BufferOverflowException();
}
- byteBuffer.putShort(position++ << 1, c);
+ byteBuffer.putShort(position++ * SizeOf.SHORT, c);
return this;
}
@@ -193,29 +153,27 @@
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
- byteBuffer.putShort(index << 1, c);
+ byteBuffer.putShort(index * SizeOf.SHORT, c);
return this;
}
- // BEGIN android-added
@Override
- public ShortBuffer put(short[] s, int off, int len) {
+ public ShortBuffer put(short[] src, int srcOffset, int shortCount) {
+ byteBuffer.limit(limit * SizeOf.SHORT);
+ byteBuffer.position(position * SizeOf.SHORT);
if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
- byteBuffer.limit(limit << 1);
- byteBuffer.position(position << 1);
- ((ReadWriteDirectByteBuffer) byteBuffer).put(s, off, len);
- this.position += len;
- return this;
+ ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, shortCount);
} else {
- return super.put(s, off, len);
+ ((ReadWriteHeapByteBuffer) byteBuffer).put(src, srcOffset, shortCount);
}
+ this.position += shortCount;
+ return this;
}
- // END android-added
@Override
public ShortBuffer slice() {
- byteBuffer.limit(limit << 1);
- byteBuffer.position(position << 1);
+ 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/org/apache/harmony/nio/internal/SocketChannelImpl.java b/luni/src/main/java/java/nio/SocketChannelImpl.java
similarity index 92%
rename from luni/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java
rename to luni/src/main/java/java/nio/SocketChannelImpl.java
index 529e00a..2f52646 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java
+++ b/luni/src/main/java/java/nio/SocketChannelImpl.java
@@ -15,11 +15,7 @@
* limitations under the License.
*/
-package org.apache.harmony.nio.internal;
-
-// BEGIN android-note
-// In this class the address length was changed from long to int.
-// END android-note
+package java.nio;
import java.io.FileDescriptor;
import java.io.IOException;
@@ -33,7 +29,6 @@
import java.net.SocketException;
import java.net.SocketUtils;
import java.net.UnknownHostException;
-import java.nio.ByteBuffer;
import java.nio.channels.AlreadyConnectedException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ConnectionPendingException;
@@ -47,9 +42,7 @@
import libcore.io.IoUtils;
import org.apache.harmony.luni.net.PlainSocketImpl;
import org.apache.harmony.luni.platform.FileDescriptorHandler;
-import org.apache.harmony.luni.platform.INetworkSystem;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.nio.AddressUtil;
/*
* The default implementation class of java.nio.channels.SocketChannel.
@@ -58,9 +51,6 @@
private static final int EOF = -1;
- // The singleton to do the native network operation.
- static final INetworkSystem networkSystem = Platform.getNetworkSystem();
-
// Status un-init, not initialized.
static final int SOCKET_STATUS_UNINIT = EOF;
@@ -77,7 +67,7 @@
static final int SOCKET_STATUS_CLOSED = 3;
// The descriptor to interact with native code.
- FileDescriptor fd;
+ final FileDescriptor fd;
// Our internal Socket.
private SocketAdapter socket = null;
@@ -97,11 +87,9 @@
// Whether the socket is bound.
volatile boolean isBound = false;
- private static class ReadLock {}
- private final Object readLock = new ReadLock();
+ private final Object readLock = new Object();
- private static class WriteLock {}
- private final Object writeLock = new WriteLock();
+ private final Object writeLock = new Object();
/*
* Constructor for creating a connected socket channel.
@@ -118,7 +106,7 @@
fd = new FileDescriptor();
status = SOCKET_STATUS_UNCONNECTED;
if (connect) {
- networkSystem.socket(fd, true);
+ Platform.NETWORK.socket(fd, true);
}
}
@@ -194,10 +182,10 @@
try {
if (isBlocking()) {
begin();
- networkSystem.connect(fd, normalAddr, port, 0);
+ Platform.NETWORK.connect(fd, normalAddr, port, 0);
finished = true; // Or we'd have thrown an exception.
} else {
- finished = networkSystem.connectNonBlocking(fd, normalAddr, port);
+ finished = Platform.NETWORK.connectNonBlocking(fd, normalAddr, port);
// set back to nonblocking to work around with a bug in portlib
if (!isBlocking()) {
IoUtils.setBlocking(fd, false);
@@ -238,8 +226,8 @@
}
private void initLocalAddressAndPort() {
- localAddress = networkSystem.getSocketLocalAddress(fd);
- localPort = networkSystem.getSocketLocalPort(fd);
+ localAddress = Platform.NETWORK.getSocketLocalAddress(fd);
+ localPort = Platform.NETWORK.getSocketLocalPort(fd);
if (socket != null) {
socket.socketImpl().initLocalPort(localPort);
}
@@ -265,7 +253,7 @@
begin();
final int WAIT_FOREVER = -1;
final int POLL = 0;
- finished = networkSystem.isConnected(fd, isBlocking() ? WAIT_FOREVER : POLL);
+ finished = Platform.NETWORK.isConnected(fd, isBlocking() ? WAIT_FOREVER : POLL);
isBound = finished;
initLocalAddressAndPort();
} catch (ConnectException e) {
@@ -372,14 +360,14 @@
if (target.isDirect()) {
// BEGIN android-changed
// changed address from long to int
- int address = AddressUtil.getDirectBufferAddress(target);
- readCount = networkSystem.readDirect(fd, address + offset, length);
+ int address = NioUtils.getDirectBufferAddress(target);
+ readCount = Platform.NETWORK.readDirect(fd, address + offset, length);
// END android-changed
} else {
// target is assured to have array.
byte[] array = target.array();
offset += target.arrayOffset();
- readCount = networkSystem.read(fd, array, offset, length);
+ readCount = Platform.NETWORK.read(fd, array, offset, length);
}
return readCount;
} finally {
@@ -450,15 +438,15 @@
begin();
}
if (source.isDirect()) {
- int address = AddressUtil.getDirectBufferAddress(source);
- writeCount = networkSystem.writeDirect(fd, address, pos, length);
+ int address = NioUtils.getDirectBufferAddress(source);
+ writeCount = Platform.NETWORK.writeDirect(fd, address, pos, length);
} else if (source.hasArray()) {
pos += source.arrayOffset();
- writeCount = networkSystem.write(fd, source.array(), pos, length);
+ writeCount = Platform.NETWORK.write(fd, source.array(), pos, length);
} else {
byte[] array = new byte[length];
source.get(array);
- writeCount = networkSystem.write(fd, array, 0, length);
+ writeCount = Platform.NETWORK.write(fd, array, 0, length);
}
source.position(pos + writeCount);
} finally {
@@ -530,13 +518,13 @@
* Do really closing action here.
*/
@Override
- synchronized protected void implCloseSelectableChannel() throws IOException {
- if (SOCKET_STATUS_CLOSED != status) {
+ protected synchronized void implCloseSelectableChannel() throws IOException {
+ if (status != SOCKET_STATUS_CLOSED) {
status = SOCKET_STATUS_CLOSED;
- if (null != socket && !socket.isClosed()) {
+ if (socket != null && !socket.isClosed()) {
socket.close();
} else {
- networkSystem.close(fd);
+ Platform.NETWORK.close(fd);
}
}
}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/WriteOnlyFileChannel.java b/luni/src/main/java/java/nio/WriteOnlyFileChannel.java
similarity index 88%
rename from luni/src/main/java/org/apache/harmony/nio/internal/WriteOnlyFileChannel.java
rename to luni/src/main/java/java/nio/WriteOnlyFileChannel.java
index 21fa9d3..48c654c 100644
--- a/luni/src/main/java/org/apache/harmony/nio/internal/WriteOnlyFileChannel.java
+++ b/luni/src/main/java/java/nio/WriteOnlyFileChannel.java
@@ -15,23 +15,15 @@
* limitations under the License.
*/
-/*
- * Android Notice
- * In this class the address length was changed from long to int.
- * This is due to performance optimizations for the device.
- */
-
-package org.apache.harmony.nio.internal;
+package java.nio;
import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.MappedByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileLock;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.WritableByteChannel;
-public final class WriteOnlyFileChannel extends FileChannelImpl {
+final class WriteOnlyFileChannel extends FileChannelImpl {
private boolean append = false;
@@ -44,11 +36,6 @@
append = isAppend;
}
- /*
- * (non-Javadoc)
- *
- * @see org.apache.harmony.nio.internal.FileChannelImpl#position()
- */
public long position() throws IOException {
return append ? size() : super.position();
}
diff --git a/luni/src/main/java/java/nio/channels/Channels.java b/luni/src/main/java/java/nio/channels/Channels.java
index 615e781..be498c4 100644
--- a/luni/src/main/java/java/nio/channels/Channels.java
+++ b/luni/src/main/java/java/nio/channels/Channels.java
@@ -19,28 +19,23 @@
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
import java.io.OutputStream;
+import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
-import org.apache.harmony.nio.internal.IOUtil;
/**
* This class provides several utilities to get I/O streams from channels.
*/
public final class Channels {
- /*
- * Not intended to be instantiated.
- */
- private Channels() {
- super();
- }
+ private Channels() {}
/**
* Returns an input stream on the given channel. The resulting stream has
@@ -60,7 +55,7 @@
* @return an InputStream that takes bytes from the given byte channel.
*/
public static InputStream newInputStream(ReadableByteChannel channel) {
- return new ReadableByteChannelInputStream(channel);
+ return new ChannelInputStream(channel);
}
/**
@@ -80,7 +75,7 @@
* @return an OutputStream that puts bytes onto the given byte channel.
*/
public static OutputStream newOutputStream(WritableByteChannel channel) {
- return new WritableByteChannelOutputStream(channel);
+ return new ChannelOutputStream(channel);
}
/**
@@ -97,7 +92,7 @@
* @return a byte channel that reads bytes from the input stream.
*/
public static ReadableByteChannel newChannel(InputStream inputStream) {
- return new ReadableByteChannelImpl(inputStream);
+ return new InputStreamChannel(inputStream);
}
/**
@@ -115,7 +110,7 @@
* @return a byte channel that writes bytes to the output stream.
*/
public static WritableByteChannel newChannel(OutputStream outputStream) {
- return new WritableByteChannelImpl(outputStream);
+ return new OutputStreamChannel(outputStream);
}
/**
@@ -132,8 +127,11 @@
*/
public static Reader newReader(ReadableByteChannel channel,
CharsetDecoder decoder, int minBufferCapacity) {
- return new ByteChannelReader(new ReaderInputStream(channel), decoder,
- minBufferCapacity);
+ /*
+ * This method doesn't honor minBufferCapacity. Ignoring that parameter
+ * saves us from having to add a hidden constructor to InputStreamReader.
+ */
+ return new InputStreamReader(new ChannelInputStream(channel), decoder);
}
/**
@@ -150,6 +148,9 @@
*/
public static Reader newReader(ReadableByteChannel channel,
String charsetName) {
+ if (charsetName == null) {
+ throw new NullPointerException();
+ }
return newReader(channel, Charset.forName(charsetName).newDecoder(), -1);
}
@@ -168,8 +169,11 @@
*/
public static Writer newWriter(WritableByteChannel channel,
CharsetEncoder encoder, int minBufferCapacity) {
- return new ByteChannelWriter(new WritableByteChannelOutputStream(
- channel), encoder, minBufferCapacity);
+ /*
+ * This method doesn't honor minBufferCapacity. Ignoring that parameter
+ * saves us from having to add a hidden constructor to OutputStreamWriter.
+ */
+ return new OutputStreamWriter(new ChannelOutputStream(channel), encoder);
}
/**
@@ -187,28 +191,24 @@
*/
public static Writer newWriter(WritableByteChannel channel,
String charsetName) {
+ if (charsetName == null) {
+ throw new NullPointerException();
+ }
return newWriter(channel, Charset.forName(charsetName).newEncoder(), -1);
}
- /*
- * wrap a byte array to a ByteBuffer
+ /**
+ * An input stream that delegates to a readable channel.
*/
- static ByteBuffer wrapByteBuffer(byte[] bytes, int offset, int length) {
- ByteBuffer buffer = ByteBuffer.wrap(bytes);
- int newLimit = offset + length <= buffer.capacity() ? offset + length
- : buffer.capacity();
- buffer.limit(newLimit);
- buffer.position(offset);
- return buffer;
- }
-
private static class ChannelInputStream extends InputStream {
- protected ReadableByteChannel channel;
+ private final ReadableByteChannel channel;
- public ChannelInputStream(ReadableByteChannel aChannel) {
- super();
- channel = aChannel;
+ ChannelInputStream(ReadableByteChannel channel) {
+ if (channel == null) {
+ throw new NullPointerException();
+ }
+ this.channel = channel;
}
@Override
@@ -223,101 +223,56 @@
}
@Override
+ public synchronized int read(byte[] target, int offset, int length) throws IOException {
+ ByteBuffer buffer = ByteBuffer.wrap(target, offset, length);
+ checkBlocking(channel);
+ return channel.read(buffer);
+ }
+
+ @Override public int available() throws IOException {
+ if (channel instanceof FileChannel) {
+ FileChannel fileChannel = (FileChannel) channel;
+ long result = fileChannel.size() - fileChannel.position();
+ return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result;
+ } else {
+ return super.available();
+ }
+ }
+
+ @Override
public synchronized void close() throws IOException {
channel.close();
}
}
- /*
- * Wrapper class used for newInputStream(ReadableByteChannel channel)
+ /**
+ * An output stream that delegates to a writable channel.
*/
- private static class ReadableByteChannelInputStream extends ChannelInputStream {
+ private static class ChannelOutputStream extends OutputStream {
- public ReadableByteChannelInputStream(ReadableByteChannel aChannel) {
- super(aChannel);
- }
+ private final WritableByteChannel channel;
- @Override
- public synchronized int read(byte[] target, int offset, int length)
- throws IOException {
- // avoid int overflow, check null target
- if (length + offset > target.length || length < 0 || offset < 0) {
- throw new ArrayIndexOutOfBoundsException();
+ ChannelOutputStream(WritableByteChannel channel) {
+ if (channel == null) {
+ throw new NullPointerException();
}
- if (0 == length) {
- return 0;
- }
- if (channel instanceof SelectableChannel) {
- if (!((SelectableChannel) channel).isBlocking()) {
- throw new IllegalBlockingModeException();
- }
- }
- ByteBuffer buffer = ByteBuffer.wrap(target, offset, length);
- return channel.read(buffer);
- }
- }
-
- /*
- * Wrapper class used for newReader(ReadableByteChannel channel,
- * CharsetDecoder decoder, int minBufferCapacity)
- */
- private static class ReaderInputStream extends ChannelInputStream {
-
- public ReaderInputStream(ReadableByteChannel aChannel) {
- super(aChannel);
- }
-
- @Override
- public synchronized int read(byte[] target, int offset, int length)
- throws IOException {
- // avoid int overflow, check null target
- if (length + offset > target.length || length < 0 || offset < 0) {
- throw new ArrayIndexOutOfBoundsException();
- }
- if (0 == length) {
- return 0;
- }
- ByteBuffer buffer = ByteBuffer.wrap(target, offset, length);
- return channel.read(buffer);
- }
- }
-
- /*
- * Wrapper class used for newOutputStream(WritableByteChannel channel)
- */
- private static class WritableByteChannelOutputStream extends OutputStream {
-
- private WritableByteChannel channel;
-
- public WritableByteChannelOutputStream(WritableByteChannel aChannel) {
- super();
- channel = aChannel;
+ this.channel = channel;
}
@Override
public synchronized void write(int oneByte) throws IOException {
- byte[] wrappedByte = new byte[1];
- wrappedByte[0] = (byte) oneByte;
+ byte[] wrappedByte = { (byte) oneByte };
write(wrappedByte);
}
@Override
- public synchronized void write(byte[] source, int offset, int length)
- throws IOException {
- // avoid int overflow, check null source
- if (length + offset > source.length || length < 0 || offset < 0) {
- throw new ArrayIndexOutOfBoundsException();
- }
- if (0 == length) {
- return;
- }
- if (channel instanceof SelectableChannel) {
- if (!((SelectableChannel) channel).isBlocking()) {
- throw new IllegalBlockingModeException();
- }
- }
+ public synchronized void write(byte[] source, int offset, int length) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(source, offset, length);
- channel.write(buffer);
+ checkBlocking(channel);
+ int total = 0;
+ while (total < length) {
+ total += channel.write(buffer);
+ }
}
@Override
@@ -326,16 +281,24 @@
}
}
- /*
- * Wrapper class used for newChannel(InputStream inputStream)
- */
- private static class ReadableByteChannelImpl extends
- AbstractInterruptibleChannel implements ReadableByteChannel {
- private InputStream inputStream;
+ static void checkBlocking(Channel channel) {
+ if (channel instanceof SelectableChannel && !((SelectableChannel) channel).isBlocking()) {
+ throw new IllegalBlockingModeException();
+ }
+ }
- ReadableByteChannelImpl(InputStream aInputStream) {
- super();
- inputStream = aInputStream;
+ /**
+ * A readable channel that delegates to an input stream.
+ */
+ private static class InputStreamChannel extends AbstractInterruptibleChannel
+ implements ReadableByteChannel {
+ private final InputStream inputStream;
+
+ InputStreamChannel(InputStream inputStream) {
+ if (inputStream == null) {
+ throw new NullPointerException();
+ }
+ this.inputStream = inputStream;
}
public synchronized int read(ByteBuffer target) throws IOException {
@@ -363,16 +326,18 @@
}
}
- /*
- * Wrapper class used for newChannel(OutputStream outputStream)
+ /**
+ * A writable channel that delegates to an output stream.
*/
- private static class WritableByteChannelImpl extends
- AbstractInterruptibleChannel implements WritableByteChannel {
- private OutputStream outputStream;
+ private static class OutputStreamChannel extends AbstractInterruptibleChannel
+ implements WritableByteChannel {
+ private final OutputStream outputStream;
- WritableByteChannelImpl(OutputStream aOutputStream) {
- super();
- outputStream = aOutputStream;
+ OutputStreamChannel(OutputStream outputStream) {
+ if (outputStream == null) {
+ throw new NullPointerException();
+ }
+ this.outputStream = outputStream;
}
public synchronized int write(ByteBuffer source) throws IOException {
@@ -399,133 +364,4 @@
outputStream.close();
}
}
-
- /*
- * Wrapper class used for newReader(ReadableByteChannel channel,
- * CharsetDecoder decoder, int minBufferCapacity)
- */
- private static class ByteChannelReader extends Reader {
-
- private InputStream inputStream;
-
- private static final int BUFFER_SIZE = 8192;
-
- CharsetDecoder decoder;
-
- ByteBuffer bytes;
-
- CharBuffer chars;
-
- public ByteChannelReader(InputStream aInputStream,
- CharsetDecoder aDecoder, int minBufferCapacity) {
- super(aInputStream);
- aDecoder.reset();
- inputStream = aInputStream;
- int bufferSize = Math.max(minBufferCapacity, BUFFER_SIZE);
- bytes = ByteBuffer.allocate(bufferSize);
- chars = CharBuffer.allocate(bufferSize);
- decoder = aDecoder;
- chars.limit(0);
- }
-
- @Override
- public void close() throws IOException {
- synchronized (lock) {
- decoder = null;
- if (inputStream != null) {
- inputStream.close();
- inputStream = null;
- }
- }
- }
-
- @Override
- public boolean ready() {
- synchronized (lock) {
- if (null == inputStream) {
- return false;
- }
- try {
- return chars.limit() > chars.position()
- || inputStream.available() > 0;
- } catch (IOException e) {
- return false;
- }
- }
- }
-
- @Override
- public int read() throws IOException {
- return IOUtil.readInputStreamReader(inputStream, bytes, chars,
- decoder, lock);
- }
-
- @Override
- public int read(char[] buf, int offset, int length) throws IOException {
- return IOUtil.readInputStreamReader(buf, offset, length,
- inputStream, bytes, chars, decoder, lock);
- }
- }
-
- /*
- * Wrapper class used for newWriter(WritableByteChannel channel,
- * CharsetEncoder encoder, int minBufferCapacity)
- */
- private static class ByteChannelWriter extends Writer {
-
- private static final int BUFFER_SIZE = 8192;
-
- private OutputStream outputStream;
-
- private CharsetEncoder encoder;
-
- private ByteBuffer byteBuf;
-
- public ByteChannelWriter(OutputStream aOutputStream,
- CharsetEncoder aEncoder, int minBufferCap) {
- super(aOutputStream);
- aEncoder.charset();
- outputStream = aOutputStream;
- byteBuf = ByteBuffer.allocate(Math.max(minBufferCap, BUFFER_SIZE));
- encoder = aEncoder;
- }
-
- @Override
- public void close() throws IOException {
- synchronized (lock) {
- if (encoder != null) {
- flush();
- outputStream.flush();
- outputStream.close();
- encoder = null;
- byteBuf = null;
- }
- }
- }
-
- @Override
- public void flush() throws IOException {
- IOUtil
- .flushOutputStreamWriter(outputStream, byteBuf, encoder,
- lock);
- }
-
- @Override
- public void write(char[] buf, int offset, int count) throws IOException {
- IOUtil.writeOutputStreamWriter(buf, offset, count, outputStream,
- byteBuf, encoder, lock);
- }
-
- @Override
- public void write(int oneChar) throws IOException {
- IOUtil.writeOutputStreamWriter(oneChar, outputStream, byteBuf,
- encoder, lock);
- }
-
- @Override
- public void write(String str, int offset, int count) throws IOException {
- IOUtil.writeOutputStreamWriter(str, offset, count, outputStream,
- byteBuf, encoder, lock);
- }
- }
}
diff --git a/luni/src/main/java/java/nio/channels/spi/AbstractSelectableChannel.java b/luni/src/main/java/java/nio/channels/spi/AbstractSelectableChannel.java
index 5be8919..674f5a4 100644
--- a/luni/src/main/java/java/nio/channels/spi/AbstractSelectableChannel.java
+++ b/luni/src/main/java/java/nio/channels/spi/AbstractSelectableChannel.java
@@ -42,11 +42,7 @@
*/
private List<SelectionKey> keyList = new ArrayList<SelectionKey>();
- // Marker class so lock type shows up in profilers
- static private class BlockingLock {
- }
-
- private final Object blockingLock = new BlockingLock();
+ private final Object blockingLock = new Object();
boolean isBlocking = true;
diff --git a/luni/src/main/java/java/nio/channels/spi/SelectorProvider.java b/luni/src/main/java/java/nio/channels/spi/SelectorProvider.java
index dac2369..2ba5c0d 100644
--- a/luni/src/main/java/java/nio/channels/spi/SelectorProvider.java
+++ b/luni/src/main/java/java/nio/channels/spi/SelectorProvider.java
@@ -18,6 +18,7 @@
package java.nio.channels.spi;
import java.io.IOException;
+import java.nio.SelectorProviderImpl;
import java.nio.channels.Channel;
import java.nio.channels.DatagramChannel;
import java.nio.channels.Pipe;
@@ -26,7 +27,6 @@
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ServiceLoader;
-import org.apache.harmony.nio.internal.SelectorProviderImpl;
/**
* {@code SelectorProvider} is an abstract base class that declares methods for
@@ -39,6 +39,7 @@
* the system default provider is returned.
*/
public abstract class SelectorProvider {
+
private static SelectorProvider provider = null;
/**
diff --git a/luni/src/main/java/java/nio/charset/Charset.java b/luni/src/main/java/java/nio/charset/Charset.java
index fe56655..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
@@ -308,7 +308,7 @@
* Equivalent to {@code forName} but only throws {@code UnsupportedEncodingException},
* which is all pre-nio code claims to throw.
*
- * @hide
+ * @hide internal use only
*/
public static Charset forNameUEE(String charsetName) throws UnsupportedEncodingException {
try {
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/AlgorithmParameterGenerator.java b/luni/src/main/java/java/security/AlgorithmParameterGenerator.java
index 43d577b..daefa3c 100644
--- a/luni/src/main/java/java/security/AlgorithmParameterGenerator.java
+++ b/luni/src/main/java/java/security/AlgorithmParameterGenerator.java
@@ -30,10 +30,10 @@
private static final String SERVICE = "AlgorithmParameterGenerator";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store SecureRandom
- private static SecureRandom randm = new SecureRandom();
+ private static final SecureRandom RANDOM = new SecureRandom();
// Store used provider
private final Provider provider;
@@ -90,12 +90,9 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new AlgorithmParameterGenerator(
- (AlgorithmParameterGeneratorSpi) engine.spi, engine.provider,
- algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi) sap.spi,
+ sap.provider, algorithm);
}
/**
@@ -154,12 +151,9 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new AlgorithmParameterGenerator(
- (AlgorithmParameterGeneratorSpi) engine.spi, provider,
- algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi) spi, provider,
+ algorithm);
}
/**
@@ -182,7 +176,7 @@
* the size (in number of bits).
*/
public final void init(int size) {
- spiImpl.engineInit(size, randm);
+ spiImpl.engineInit(size, RANDOM);
}
/**
@@ -211,7 +205,7 @@
*/
public final void init(AlgorithmParameterSpec genParamSpec)
throws InvalidAlgorithmParameterException {
- spiImpl.engineInit(genParamSpec, randm);
+ spiImpl.engineInit(genParamSpec, RANDOM);
}
/**
diff --git a/luni/src/main/java/java/security/AlgorithmParameters.java b/luni/src/main/java/java/security/AlgorithmParameters.java
index 8f751d0..8bbbe1b 100644
--- a/luni/src/main/java/java/security/AlgorithmParameters.java
+++ b/luni/src/main/java/java/security/AlgorithmParameters.java
@@ -36,27 +36,27 @@
/**
* Used to access common engine functionality.
*/
- private static Engine engine = new Engine(SEVICE);
+ private static final Engine ENGINE = new Engine(SEVICE);
/**
* The security provider.
*/
- private Provider provider;
+ private final Provider provider;
/**
* The SPI implementation.
*/
- private AlgorithmParametersSpi spiImpl;
+ private final AlgorithmParametersSpi spiImpl;
/**
* The security algorithm.
*/
- private String algorithm;
+ private final String algorithm;
/**
* The initialization state.
*/
- private boolean initialized; // = false;
+ private boolean initialized;
/**
* Constructs a new instance of {@code AlgorithmParameters} with the given
@@ -94,11 +94,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new AlgorithmParameters((AlgorithmParametersSpi) engine.spi,
- engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new AlgorithmParameters((AlgorithmParametersSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -156,11 +153,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new AlgorithmParameters((AlgorithmParametersSpi) engine.spi,
- provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new AlgorithmParameters((AlgorithmParametersSpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/java/security/KeyFactory.java b/luni/src/main/java/java/security/KeyFactory.java
index 8387740..916b697 100644
--- a/luni/src/main/java/java/security/KeyFactory.java
+++ b/luni/src/main/java/java/security/KeyFactory.java
@@ -31,18 +31,17 @@
// The service name.
private static final String SERVICE = "KeyFactory";
- // The provider
- private Provider provider;
-
-
// Used to access common engine functionality
- static private Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
+
+ // The provider
+ private final Provider provider;
// The SPI implementation.
- private KeyFactorySpi spiImpl;
+ private final KeyFactorySpi spiImpl;
// The algorithm.
- private String algorithm;
+ private final String algorithm;
/**
* Constructs a new instance of {@code KeyFactory} with the specified
@@ -59,7 +58,7 @@
Provider provider,
String algorithm) {
this.provider = provider;
- this. algorithm = algorithm;
+ this.algorithm = algorithm;
this.spiImpl = keyFacSpi;
}
@@ -75,14 +74,12 @@
* if no provider provides the requested algorithm.
*/
public static KeyFactory getInstance(String algorithm)
- throws NoSuchAlgorithmException {
+ throws NoSuchAlgorithmException {
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new KeyFactory((KeyFactorySpi)engine.spi, engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new KeyFactory((KeyFactorySpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -136,10 +133,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new KeyFactory((KeyFactorySpi)engine.spi, provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new KeyFactory((KeyFactorySpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/java/security/KeyPairGenerator.java b/luni/src/main/java/java/security/KeyPairGenerator.java
index cc91b18..d5851fa 100644
--- a/luni/src/main/java/java/security/KeyPairGenerator.java
+++ b/luni/src/main/java/java/security/KeyPairGenerator.java
@@ -34,10 +34,10 @@
private static final String SERVICE = "KeyPairGenerator";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store SecureRandom
- private static SecureRandom random = new SecureRandom();
+ private static final SecureRandom RANDOM = new SecureRandom();
// Store used provider
private Provider provider;
@@ -82,19 +82,16 @@
if (algorithm == null) {
throw new NullPointerException();
}
- KeyPairGenerator result;
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- if (engine.spi instanceof KeyPairGenerator) {
- result = (KeyPairGenerator) engine.spi;
- result.algorithm = algorithm;
- result.provider = engine.provider;
- return result;
- }
- result = new KeyPairGeneratorImpl((KeyPairGeneratorSpi) engine.spi,
- engine.provider, algorithm);
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ Object spi = sap.spi;
+ Provider provider = sap.provider;
+ if (spi instanceof KeyPairGenerator) {
+ KeyPairGenerator result = (KeyPairGenerator) spi;
+ result.algorithm = algorithm;
+ result.provider = provider;
return result;
}
+ return new KeyPairGeneratorImpl((KeyPairGeneratorSpi) spi, provider, algorithm);
}
/**
@@ -148,19 +145,14 @@
if (algorithm == null) {
throw new NullPointerException();
}
- KeyPairGenerator result;
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- if (engine.spi instanceof KeyPairGenerator) {
- result = (KeyPairGenerator) engine.spi;
- result.algorithm = algorithm;
- result.provider = provider;
- return result;
- }
- result = new KeyPairGeneratorImpl((KeyPairGeneratorSpi) engine.spi,
- provider, algorithm);
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ if (spi instanceof KeyPairGenerator) {
+ KeyPairGenerator result = (KeyPairGenerator) spi;
+ result.algorithm = algorithm;
+ result.provider = provider;
return result;
}
+ return new KeyPairGeneratorImpl((KeyPairGeneratorSpi) spi, provider, algorithm);
}
/**
@@ -181,7 +173,7 @@
* the size of the key (number of bits)
*/
public void initialize(int keysize) {
- initialize(keysize, random);
+ initialize(keysize, RANDOM);
}
/**
@@ -196,7 +188,7 @@
*/
public void initialize(AlgorithmParameterSpec param)
throws InvalidAlgorithmParameterException {
- initialize(param, random);
+ initialize(param, RANDOM);
}
/**
@@ -262,11 +254,6 @@
// Save KeyPairGeneratorSpi
private KeyPairGeneratorSpi spiImpl;
- // Implementation of KeyPaiGenerator constructor
- //
- // @param KeyPairGeneratorSpi
- // @param provider
- // @param algorithm
private KeyPairGeneratorImpl(KeyPairGeneratorSpi keyPairGeneratorSpi,
Provider provider, String algorithm) {
super(algorithm);
diff --git a/luni/src/main/java/java/security/KeyStore.java b/luni/src/main/java/java/security/KeyStore.java
index fcd0469..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;
/**
@@ -51,7 +52,7 @@
private static final String SERVICE = "KeyStore";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store KeyStore property name
private static final String PROPERTYNAME = "keystore.type";
@@ -111,13 +112,11 @@
if (type == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- try {
- engine.getInstance(type, null);
- return new KeyStore((KeyStoreSpi) engine.spi, engine.provider, type);
- } catch (NoSuchAlgorithmException e) {
+ try {
+ Engine.SpiAndProvider sap = ENGINE.getInstance(type, null);
+ return new KeyStore((KeyStoreSpi) sap.spi, sap.provider, type);
+ } catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e.getMessage());
- }
}
}
@@ -187,14 +186,12 @@
throw new NullPointerException();
}
// return KeyStore instance
- synchronized (engine) {
- try {
- engine.getInstance(type, provider, null);
- return new KeyStore((KeyStoreSpi) engine.spi, provider, type);
- } catch (Exception e) {
+ try {
+ Object spi = ENGINE.getInstance(type, provider, null);
+ return new KeyStore((KeyStoreSpi) spi, provider, type);
+ } catch (Exception e) {
// override exception
- throw new KeyStoreException(e.getMessage());
- }
+ throw new KeyStoreException(e.getMessage());
}
}
@@ -879,7 +876,8 @@
// CallbackHandlerProtection
if (!(protectionParameter instanceof PasswordProtection)
&& !(protectionParameter instanceof CallbackHandlerProtection)) {
- throw new IllegalArgumentException("protectionParameter is neither PasswordProtection nor CallbackHandlerProtection instance");
+ throw new IllegalArgumentException("protectionParameter is neither "
+ + "PasswordProtection nor CallbackHandlerProtection instance");
}
// check file parameter
if (!file.exists()) {
@@ -963,13 +961,13 @@
// Store AccessControlContext which is used in getKeyStore() method
private final AccessControlContext accControlContext;
- //
- // Constructor BuilderImpl initializes private fields: keyStore,
- // protParameter, typeForKeyStore providerForKeyStore fileForLoad,
- // isGetKeyStore
- //
+ /**
+ * Constructor BuilderImpl initializes private fields: keyStore,
+ * protParameter, typeForKeyStore providerForKeyStore fileForLoad,
+ * isGetKeyStore
+ */
BuilderImpl(KeyStore ks, ProtectionParameter pp, File file,
- String type, Provider provider, AccessControlContext context) {
+ String type, Provider provider, AccessControlContext context) {
super();
keyStore = ks;
protParameter = pp;
@@ -981,20 +979,20 @@
accControlContext = context;
}
- //
- // Implementation of abstract getKeyStore() method If
- // KeyStoreBuilder encapsulates KeyStore object then this object is
- // returned
- //
- // If KeyStoreBuilder encapsulates KeyStore type and provider then
- // KeyStore is created using these parameters. If KeyStoreBuilder
- // encapsulates file and ProtectionParameter then KeyStore data are
- // loaded from FileInputStream that is created on file. If file is
- // not defined then KeyStore object is initialized with null
- // InputStream and null password.
- //
- // Result KeyStore object is returned.
- //
+ /**
+ * Implementation of abstract getKeyStore() method If
+ * KeyStoreBuilder encapsulates KeyStore object then this object is
+ * returned
+ *
+ * If KeyStoreBuilder encapsulates KeyStore type and provider then
+ * KeyStore is created using these parameters. If KeyStoreBuilder
+ * encapsulates file and ProtectionParameter then KeyStore data are
+ * loaded from FileInputStream that is created on file. If file is
+ * not defined then KeyStore object is initialized with null
+ * InputStream and null password.
+ *
+ * Result KeyStore object is returned.
+ */
@Override
public synchronized KeyStore getKeyStore() throws KeyStoreException {
// If KeyStore was created but in final block some exception was
@@ -1027,7 +1025,8 @@
passwd = KeyStoreSpi
.getPasswordFromCallBack(protParameter);
} else {
- throw new KeyStoreException("protectionParameter is neither PasswordProtection nor CallbackHandlerProtection instance");
+ throw new KeyStoreException("protectionParameter is neither "
+ + "PasswordProtection nor CallbackHandlerProtection instance");
}
// load KeyStore from file
@@ -1040,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(
@@ -1065,13 +1061,13 @@
}
}
- //
- // This is implementation of abstract method
- // getProtectionParameter(String alias)
- //
- // Return: ProtectionParameter to get Entry which was saved in
- // KeyStore with defined alias
- //
+ /**
+ * This is implementation of abstract method
+ * getProtectionParameter(String alias)
+ *
+ * Return: ProtectionParameter to get Entry which was saved in
+ * KeyStore with defined alias
+ */
@Override
public synchronized ProtectionParameter getProtectionParameter(
String alias) throws KeyStoreException {
@@ -1286,13 +1282,15 @@
// the end certificate
String s = chain[0].getType();
if (!(chain[0].getPublicKey().getAlgorithm()).equals(privateKey.getAlgorithm())) {
- throw new IllegalArgumentException("Algorithm of private key does not match " +
- "algorithm of public key in end certificate of entry (with index number: 0)");
+ throw new IllegalArgumentException("Algorithm of private key does not match "
+ + "algorithm of public key in end certificate of entry "
+ + "(with index number: 0)");
}
// Match certificate types
for (int i = 1; i < chain.length; i++) {
if (!s.equals(chain[i].getType())) {
- throw new IllegalArgumentException("Certificates from the given chain have different types");
+ throw new IllegalArgumentException("Certificates from the given chain have "
+ + "different types");
}
}
// clone chain - this.chain = (Certificate[])chain.clone();
diff --git a/luni/src/main/java/java/security/MessageDigest.java b/luni/src/main/java/java/security/MessageDigest.java
index aac5403..3154028 100644
--- a/luni/src/main/java/java/security/MessageDigest.java
+++ b/luni/src/main/java/java/security/MessageDigest.java
@@ -51,7 +51,7 @@
public abstract class MessageDigest extends MessageDigestSpi {
// Used to access common engine functionality
- private static final Engine engine = new Engine("MessageDigest");
+ private static final Engine ENGINE = new Engine("MessageDigest");
// The provider
private Provider provider;
@@ -88,18 +88,16 @@
if (algorithm == null) {
throw new NullPointerException();
}
- MessageDigest result;
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- if (engine.spi instanceof MessageDigest) {
- result = (MessageDigest) engine.spi;
- result.algorithm = algorithm;
- result.provider = engine.provider;
- return result;
- }
- return new MessageDigestImpl((MessageDigestSpi) engine.spi,
- engine.provider, algorithm);
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ Object spi = sap.spi;
+ Provider provider = sap.provider;
+ if (spi instanceof MessageDigest) {
+ MessageDigest result = (MessageDigest) spi;
+ result.algorithm = algorithm;
+ result.provider = provider;
+ return result;
}
+ return new MessageDigestImpl((MessageDigestSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -156,19 +154,14 @@
if (algorithm == null) {
throw new NullPointerException();
}
- MessageDigest result;
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- if (engine.spi instanceof MessageDigest) {
- result = (MessageDigest) engine.spi;
- result.algorithm = algorithm;
- result.provider = provider;
- return result;
- }
- result = new MessageDigestImpl((MessageDigestSpi) engine.spi,
- provider, algorithm);
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ if (spi instanceof MessageDigest) {
+ MessageDigest result = (MessageDigest) spi;
+ result.algorithm = algorithm;
+ result.provider = provider;
return result;
}
+ return new MessageDigestImpl((MessageDigestSpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/java/security/Policy.java b/luni/src/main/java/java/security/Policy.java
index baaedfc..8a5934d 100644
--- a/luni/src/main/java/java/security/Policy.java
+++ b/luni/src/main/java/java/security/Policy.java
@@ -44,30 +44,31 @@
"setPolicy");
// The SecurityPermission required to get current Policy.
- static final SecurityPermission GET_POLICY = new SecurityPermission("getPolicy");
+ private static final SecurityPermission GET_POLICY = new SecurityPermission("getPolicy");
// The policy currently in effect.
+ // protected by Policy.class monitor.
private static Policy activePolicy;
// Store spi implementation service name
private static final String POLICYSERVICE = "Policy";
// Used to access common engine functionality
- private static Engine engine = new Engine(POLICYSERVICE);
+ private static final Engine ENGINE = new Engine(POLICYSERVICE);
- private String type;
+ private final String type;
- private Policy.Parameters params;
+ private final Policy.Parameters params;
- private Provider provider;
+ private final Provider provider;
// Store used spi implementation
- private PolicySpi spiImpl;
+ private final PolicySpi spiImpl;
private static final String CREATE_POLICY = "createPolicy.";
public Policy() {
- // default constructor
+ this(null, null, null, null);
}
private Policy(PolicySpi spi, Provider p, String t, Policy.Parameters para) {
@@ -97,22 +98,22 @@
* Note that the list of registered providers may be retrieved via the
* Security.getProviders() method.
*
- * @param type -
+ * @param type
* the specified Policy type. See Appendix A in the Java
* Cryptography Architecture API Specification & Reference for a
* list of standard Policy types.
- * @param params -
+ * @param params
* parameters for the Policy, which may be null.
* @return the new Policy object.
- * @throws NoSuchAlgorithmException -
+ * @throws NoSuchAlgorithmException
* if no Provider supports a PolicySpi implementation for the
* specified type.
- * @throws SecurityException -
+ * @throws SecurityException
* if the caller does not have permission to get a Policy
* instance for the specified type.
- * @throws NullPointerException -
+ * @throws NullPointerException
* if the specified type is null.
- * @throws IllegalArgumentException -
+ * @throws IllegalArgumentException
* if the specified parameters' type are not allowed by the
* PolicySpi implementation from the selected Provider.
*/
@@ -125,12 +126,8 @@
}
try {
- synchronized (engine) {
- engine.getInstance(type, params);
- return new PolicyDelegate((PolicySpi) engine.spi,
- engine.provider, type, params);
- }
-
+ Engine.SpiAndProvider sap = ENGINE.getInstance(type, params);
+ return new PolicyDelegate((PolicySpi) sap.spi, sap.provider, type, params);
} catch (NoSuchAlgorithmException e) {
if (e.getCause() == null) {
throw e;
@@ -147,27 +144,27 @@
* in the provider list via the Security.getProviders() method, otherwise
* NoSuchProviderException will be thrown.
*
- * @param type -
+ * @param type
* the specified Policy type. So far in Java 6, only 'JavaPolicy'
* supported.
- * @param params -
+ * @param params
* the Policy.Parameter object, which may be null.
- * @param provider -
+ * @param provider
* the provider.
* @return the new Policy object.
*
- * @throws NoSuchProviderException -
+ * @throws NoSuchProviderException
* if the specified provider is not registered in the security
* provider list.
- * @throws NoSuchAlgorithmException -
+ * @throws NoSuchAlgorithmException
* if the specified provider does not support a PolicySpi
* implementation for the specified type.
- * @throws SecurityException -
+ * @throws SecurityException
* if the caller does not have permission to get a Policy
* instance for the specified type.
- * @throws NullPointerException -
+ * @throws NullPointerException
* if the specified type is null.
- * @throws IllegalArgumentException -
+ * @throws IllegalArgumentException
* if the specified Provider is null, or if the specified
* parameters' type are not allowed by the PolicySpi
* implementation from the specified Provider.
@@ -195,25 +192,25 @@
* specified Provider object is returned. Note that the specified Provider
* object does not have to be registered in the provider list.
*
- * @param type -
+ * @param type
* the specified Policy type. So far in Java 6, only 'JavaPolicy'
* supported.
- * @param params -
+ * @param params
* the Policy.Parameter object, which may be null.
- * @param provider -
+ * @param provider
* the Policy service Provider.
* @return the new Policy object.
*
- * @throws NoSuchAlgorithmException -
+ * @throws NoSuchAlgorithmException
* if the specified Provider does not support a PolicySpi
* implementation for the specified type.
- * @throws IllegalArgumentException -
+ * @throws IllegalArgumentException
* if the specified Provider is null, or if the specified
* parameters' type are not allowed by the PolicySpi
* implementation from the specified Provider.
- * @throws NullPointerException -
+ * @throws NullPointerException
* if the specified type is null.
- * @throws SecurityException -
+ * @throws SecurityException
* if the caller does not have permission to get a Policy
* instance for the specified type.
*/
@@ -234,17 +231,15 @@
}
}
- private static Policy getInstanceImpl(String type, Policy.Parameters params, Provider provider) throws NoSuchAlgorithmException {
+ private static Policy getInstanceImpl(String type, Policy.Parameters params, Provider provider)
+ throws NoSuchAlgorithmException {
if (type == null) {
throw new NullPointerException();
}
try {
- synchronized (engine) {
- engine.getInstance(type, provider, params);
- return new PolicyDelegate((PolicySpi) engine.spi, provider,
- type, params);
- }
+ Object spi = ENGINE.getInstance(type, provider, params);
+ return new PolicyDelegate((PolicySpi) spi, provider, type, params);
} catch (NoSuchAlgorithmException e) {
if (e.getCause() == null) {
throw e;
@@ -484,8 +479,7 @@
try {
return (Policy) Class.forName(defaultClass, true,
ClassLoader.getSystemClassLoader()).newInstance();
- }
- catch (Exception e) {
+ } catch (Exception e) {
//TODO log error
//System.err.println("Error loading policy provider <"
// + defaultClass + "> : " + e
@@ -502,7 +496,9 @@
* Returns {@code true} if system policy provider is instantiated.
*/
static boolean isSet() {
- return activePolicy != null;
+ synchronized (Policy.class) {
+ return activePolicy != null;
+ }
}
/**
@@ -511,11 +507,13 @@
* so this method never returns <code>null</code>. <br>
* This method is synchronized with setPolicy()
*/
- static synchronized Policy getAccessiblePolicy() {
- if (activePolicy == null) {
- activePolicy = getDefaultProvider();
+ static Policy getAccessiblePolicy() {
+ synchronized (Policy.class) {
+ if (activePolicy == null) {
+ activePolicy = getDefaultProvider();
+ }
+ return activePolicy;
}
- return activePolicy;
}
/**
diff --git a/luni/src/main/java/java/security/SecureRandom.java b/luni/src/main/java/java/security/SecureRandom.java
index 16f175c..e56f297 100644
--- a/luni/src/main/java/java/security/SecureRandom.java
+++ b/luni/src/main/java/java/security/SecureRandom.java
@@ -17,7 +17,10 @@
package java.security;
+import java.nio.ByteOrder;
import java.util.Random;
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
import org.apache.harmony.security.fortress.Engine;
import org.apache.harmony.security.fortress.Services;
import org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl;
@@ -67,27 +70,19 @@
private static final long serialVersionUID = 4940670005562187L;
// The service name.
- private static final transient String SERVICE = "SecureRandom";
+ private static final String SERVICE = "SecureRandom";
// Used to access common engine functionality
- private static transient Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
- private Provider provider;
+ private final Provider provider;
- private SecureRandomSpi secureRandomSpi;
+ private final SecureRandomSpi secureRandomSpi;
- private String algorithm;
-
- private byte[] state;
-
- private byte[] randomBytes;
-
- private int randomBytesUsed;
-
- private long counter;
+ private final String algorithm;
// Internal SecureRandom used for getSeed(int)
- private static transient SecureRandom internalSecureRandom;
+ private static volatile SecureRandom internalSecureRandom;
/**
* Constructs a new {@code SecureRandom} that uses the default algorithm.
@@ -163,10 +158,9 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new SecureRandom((SecureRandomSpi)engine.spi, engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new SecureRandom((SecureRandomSpi) sap.spi, sap.provider,
+ algorithm);
}
/**
@@ -223,10 +217,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new SecureRandom((SecureRandomSpi)engine.spi, provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new SecureRandom((SecureRandomSpi) spi, provider, algorithm);
}
/**
@@ -266,16 +258,8 @@
if (seed == 0) { // skip call from Random
return;
}
- byte[] byteSeed = {
- (byte)((seed >> 56) & 0xFF),
- (byte)((seed >> 48) & 0xFF),
- (byte)((seed >> 40) & 0xFF),
- (byte)((seed >> 32) & 0xFF),
- (byte)((seed >> 24) & 0xFF),
- (byte)((seed >> 16) & 0xFF),
- (byte)((seed >> 8) & 0xFF),
- (byte)((seed) & 0xFF)
- };
+ byte[] byteSeed = new byte[SizeOf.LONG];
+ OSMemory.pokeLong(byteSeed, 0, seed, ByteOrder.BIG_ENDIAN);
setSeed(byteSeed);
}
@@ -330,10 +314,12 @@
* @return the seed bytes
*/
public static byte[] getSeed(int numBytes) {
- if (internalSecureRandom == null) {
- internalSecureRandom = new SecureRandom();
+ SecureRandom result = internalSecureRandom;
+ if (result == null) {
+ // single-check idiom
+ internalSecureRandom = result = new SecureRandom();
}
- return internalSecureRandom.generateSeed(numBytes);
+ return result.generateSeed(numBytes);
}
/**
diff --git a/luni/src/main/java/java/security/Security.java b/luni/src/main/java/java/security/Security.java
index c420769..65b5a3e 100644
--- a/luni/src/main/java/java/security/Security.java
+++ b/luni/src/main/java/java/security/Security.java
@@ -44,7 +44,7 @@
public final class Security {
// Security properties
- private static Properties secprops = new Properties();
+ private static final Properties secprops = new Properties();
// static initialization
// - load security properties files
diff --git a/luni/src/main/java/java/security/Signature.java b/luni/src/main/java/java/security/Signature.java
index f8fb2bb..d9e1e41 100644
--- a/luni/src/main/java/java/security/Signature.java
+++ b/luni/src/main/java/java/security/Signature.java
@@ -39,7 +39,7 @@
private static final String SERVICE = "Signature";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static Engine ENGINE = new Engine(SERVICE);
// The provider
private Provider provider;
@@ -101,19 +101,16 @@
if (algorithm == null) {
throw new NullPointerException();
}
- Signature result;
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- if (engine.spi instanceof Signature) {
- result = (Signature) engine.spi;
- result.algorithm = algorithm;
- result.provider = engine.provider;
- } else {
- result = new SignatureImpl((SignatureSpi) engine.spi,
- engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ Object spi = sap.spi;
+ Provider provider = sap.provider;
+ if (spi instanceof Signature) {
+ Signature result = (Signature) spi;
+ result.algorithm = algorithm;
+ result.provider = provider;
+ return result;
}
- return result;
+ return new SignatureImpl((SignatureSpi) spi, provider, algorithm);
}
/**
@@ -178,19 +175,14 @@
private static Signature getSignatureInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
- Signature result;
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- if (engine.spi instanceof Signature) {
- result = (Signature) engine.spi;
- result.algorithm = algorithm;
- result.provider = provider;
- } else {
- result = new SignatureImpl((SignatureSpi) engine.spi, provider,
- algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ if (spi instanceof Signature) {
+ Signature result = (Signature) spi;
+ result.algorithm = algorithm;
+ result.provider = provider;
+ return result;
}
- return result;
+ return new SignatureImpl((SignatureSpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/java/security/cert/CertPathBuilder.java b/luni/src/main/java/java/security/cert/CertPathBuilder.java
index 11a38cc..c2164db 100644
--- a/luni/src/main/java/java/security/cert/CertPathBuilder.java
+++ b/luni/src/main/java/java/security/cert/CertPathBuilder.java
@@ -35,7 +35,7 @@
private static final String SERVICE = "CertPathBuilder";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store default property name
private static final String PROPERTYNAME = "certpathbuilder.type";
@@ -48,7 +48,7 @@
private final Provider provider;
// Store spi implementation
- private CertPathBuilderSpi spiImpl;
+ private final CertPathBuilderSpi spiImpl;
// Store algorithm name
private final String algorithm;
@@ -105,11 +105,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new CertPathBuilder((CertPathBuilderSpi) engine.spi,
- engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new CertPathBuilder((CertPathBuilderSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -165,11 +162,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new CertPathBuilder((CertPathBuilderSpi) engine.spi, provider,
- algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new CertPathBuilder((CertPathBuilderSpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/java/security/cert/CertPathValidator.java b/luni/src/main/java/java/security/cert/CertPathValidator.java
index b73857f..49d2408 100644
--- a/luni/src/main/java/java/security/cert/CertPathValidator.java
+++ b/luni/src/main/java/java/security/cert/CertPathValidator.java
@@ -35,7 +35,7 @@
private static final String SERVICE = "CertPathValidator";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store default property name
private static final String PROPERTYNAME = "certpathvalidator.type";
@@ -104,11 +104,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new CertPathValidator((CertPathValidatorSpi) engine.spi,
- engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new CertPathValidator((CertPathValidatorSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -166,11 +163,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new CertPathValidator((CertPathValidatorSpi) engine.spi,
- provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new CertPathValidator((CertPathValidatorSpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/java/security/cert/CertStore.java b/luni/src/main/java/java/security/cert/CertStore.java
index 775236c..a8cbfee 100644
--- a/luni/src/main/java/java/security/cert/CertStore.java
+++ b/luni/src/main/java/java/security/cert/CertStore.java
@@ -37,7 +37,7 @@
private static final String SERVICE = "CertStore";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store default property name
private static final String PROPERTYNAME = "certstore.type";
@@ -101,11 +101,8 @@
throw new NullPointerException();
}
try {
- synchronized (engine) {
- engine.getInstance(type, params);
- return new CertStore((CertStoreSpi) engine.spi, engine.provider,
- type, params);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(type, params);
+ return new CertStore((CertStoreSpi) sap.spi, sap.provider, type, params);
} catch (NoSuchAlgorithmException e) {
Throwable th = e.getCause();
if (th == null) {
@@ -182,11 +179,8 @@
throw new NullPointerException();
}
try {
- synchronized (engine) {
- engine.getInstance(type, provider, params);
- return new CertStore((CertStoreSpi) engine.spi, provider, type,
- params);
- }
+ Object spi = ENGINE.getInstance(type, provider, params);
+ return new CertStore((CertStoreSpi) spi, provider, type, params);
} catch (NoSuchAlgorithmException e) {
Throwable th = e.getCause();
if (th == null) {
diff --git a/luni/src/main/java/java/security/cert/CertificateFactory.java b/luni/src/main/java/java/security/cert/CertificateFactory.java
index 6bef771..d89ee26 100644
--- a/luni/src/main/java/java/security/cert/CertificateFactory.java
+++ b/luni/src/main/java/java/security/cert/CertificateFactory.java
@@ -41,7 +41,7 @@
private static final String SERVICE = "CertificateFactory";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store used provider
private final Provider provider;
@@ -87,11 +87,8 @@
throw new NullPointerException();
}
try {
- synchronized (engine) {
- engine.getInstance(type, null);
- return new CertificateFactory((CertificateFactorySpi) engine.spi,
- engine.provider, type);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(type, null);
+ return new CertificateFactory((CertificateFactorySpi) sap.spi, sap.provider, type);
} catch (NoSuchAlgorithmException e) {
throw new CertificateException(e);
}
@@ -156,11 +153,8 @@
throw new NullPointerException();
}
try {
- synchronized (engine) {
- engine.getInstance(type, provider, null);
- return new CertificateFactory((CertificateFactorySpi) engine.spi,
- provider, type);
- }
+ Object spi = ENGINE.getInstance(type, provider, null);
+ return new CertificateFactory((CertificateFactorySpi) spi, provider, type);
} catch (NoSuchAlgorithmException e) {
throw new CertificateException(e.getMessage());
}
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 cdc064f..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
@@ -163,13 +163,13 @@
* <td>Multiply by 100 and show as percentage.</td>
* </tr>
* <tr valign="top" bgcolor="#eeeeff">
- * <td>{@code \u2030} ({@code \u2030})</td>
+ * <td>{@code \u2030} ({@code \u005Cu2030})</td>
* <td>Prefix or suffix</td>
* <td>Yes</td>
* <td>Multiply by 1000 and show as per mille.</td>
* </tr>
* <tr valign="top">
- * <td>{@code ¤} ({@code \u00A4})</td>
+ * <td>{@code \u00A4} ({@code \u005Cu00A4})</td>
* <td>Prefix or suffix</td>
* <td>No</td>
* <td>Currency sign, replaced by currency symbol. If doubled, replaced by
@@ -319,11 +319,11 @@
* <strong>Special Values</strong>
* <p>
* {@code NaN} is represented as a single character, typically
- * {@code \uFFFD}. This character is determined by the
+ * {@code \u005cuFFFD}. This character is determined by the
* {@link DecimalFormatSymbols} object. This is the only value for which the
* prefixes and suffixes are not used.
* <p>
- * Infinity is represented as a single character, typically {@code \u221E},
+ * Infinity is represented as a single character, typically {@code \u005cu221E},
* with the positive or negative prefixes and suffixes applied. The infinity
* character is determined by the {@link DecimalFormatSymbols} object. <a
* name="sci">
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 7202cb6..15b5b12 100644
--- a/luni/src/main/java/java/text/RuleBasedBreakIterator.java
+++ b/luni/src/main/java/java/text/RuleBasedBreakIterator.java
@@ -17,50 +17,29 @@
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).
*/
class RuleBasedBreakIterator extends BreakIterator {
- /*
- * Wrapping constructor.
- */
RuleBasedBreakIterator(NativeBreakIterator iterator) {
super(iterator);
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#current()
- */
- @Override
- public int current() {
+ @Override public int current() {
return wrapped.current();
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#first()
- */
- @Override
- public int first() {
+ @Override public int first() {
return wrapped.first();
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#following(int)
- */
- @Override
- public int following(int offset) {
+ @Override public int following(int offset) {
validateOffset(offset);
return wrapped.following(offset);
}
@@ -75,130 +54,58 @@
}
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#getText()
- */
- @Override
- public CharacterIterator getText() {
+ @Override public CharacterIterator getText() {
return wrapped.getText();
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#last()
- */
- @Override
- public int last() {
+ @Override public int last() {
return wrapped.last();
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#next()
- */
- @Override
- public int next() {
+ @Override public int next() {
return wrapped.next();
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#next(int)
- */
- @Override
- public int next(int n) {
+ @Override public int next(int n) {
return wrapped.next(n);
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#previous()
- */
- @Override
- public int previous() {
+ @Override public int previous() {
return wrapped.previous();
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#setText(java.text.CharacterIterator)
- */
- @Override
- public void setText(CharacterIterator newText) {
+ @Override public void setText(CharacterIterator newText) {
// call a method to check if null pointer
newText.current();
wrapped.setText(newText);
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#isBoundary(int)
- */
- @Override
- public boolean isBoundary(int offset) {
+ @Override public boolean isBoundary(int offset) {
validateOffset(offset);
return wrapped.isBoundary(offset);
}
- /*
- * (non-Javadoc)
- *
- * @see java.text.BreakIterator#preceding(int)
- */
- @Override
- public int preceding(int offset) {
+ @Override public int preceding(int offset) {
validateOffset(offset);
return wrapped.preceding(offset);
}
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object o) {
+ @Override public boolean equals(Object o) {
if (!(o instanceof RuleBasedBreakIterator)) {
return false;
}
return wrapped.equals(((RuleBasedBreakIterator) o).wrapped);
}
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
+ @Override public String toString() {
return wrapped.toString();
}
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
+ @Override public int hashCode() {
return wrapped.hashCode();
}
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#clone()
- */
- @Override
- public Object clone() {
+ @Override public Object clone() {
RuleBasedBreakIterator cloned = (RuleBasedBreakIterator) super.clone();
cloned.wrapped = (NativeBreakIterator) wrapped.clone();
return cloned;
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/ArrayDeque.java b/luni/src/main/java/java/util/ArrayDeque.java
index 95aadf0..feaac4d 100644
--- a/luni/src/main/java/java/util/ArrayDeque.java
+++ b/luni/src/main/java/java/util/ArrayDeque.java
@@ -526,7 +526,7 @@
throw new IllegalStateException();
}
int length = elements.length;
- int newLength = length << 1;
+ int newLength = length * 2;
// bigger than Integer.MAX_VALUE
if (newLength < 0) {
newLength = Integer.MAX_VALUE;
diff --git a/luni/src/main/java/java/util/Arrays.java b/luni/src/main/java/java/util/Arrays.java
index 791b86b..1b67927 100644
--- a/luni/src/main/java/java/util/Arrays.java
+++ b/luni/src/main/java/java/util/Arrays.java
@@ -2093,10 +2093,10 @@
/**
* Creates a {@code String} representation of the {@code boolean[]} passed.
- * The result is surrounded by brackets ({@code "[]"}), each
+ * The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
- * {@link String#valueOf(boolean)} and separated by {@code ", "}.
- * If the array is {@code null}, then {@code "null"} is returned.
+ * {@link String#valueOf(boolean)} and separated by {@code ", "}.
+ * If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code boolean} array to convert.
@@ -2123,10 +2123,10 @@
/**
* Creates a {@code String} representation of the {@code byte[]} passed. The
- * result is surrounded by brackets ({@code "[]"}), each element
+ * result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(int)} and
- * separated by {@code ", "}. If the array is {@code null}, then
- * {@code "null"} is returned.
+ * separated by {@code ", "}. If the array is {@code null}, then
+ * {@code "null"} is returned.
*
* @param array
* the {@code byte} array to convert.
@@ -2153,10 +2153,10 @@
/**
* Creates a {@code String} representation of the {@code char[]} passed. The
- * result is surrounded by brackets ({@code "[]"}), each element
+ * result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(char)} and
- * separated by {@code ", "}. If the array is {@code null}, then
- * {@code "null"} is returned.
+ * separated by {@code ", "}. If the array is {@code null}, then
+ * {@code "null"} is returned.
*
* @param array
* the {@code char} array to convert.
@@ -2183,10 +2183,10 @@
/**
* Creates a {@code String} representation of the {@code double[]} passed.
- * The result is surrounded by brackets ({@code "[]"}), each
+ * The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
- * {@link String#valueOf(double)} and separated by {@code ", "}.
- * If the array is {@code null}, then {@code "null"} is returned.
+ * {@link String#valueOf(double)} and separated by {@code ", "}.
+ * If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code double} array to convert.
@@ -2213,10 +2213,10 @@
/**
* Creates a {@code String} representation of the {@code float[]} passed.
- * The result is surrounded by brackets ({@code "[]"}), each
+ * The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
- * {@link String#valueOf(float)} and separated by {@code ", "}.
- * If the array is {@code null}, then {@code "null"} is returned.
+ * {@link String#valueOf(float)} and separated by {@code ", "}.
+ * If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code float} array to convert.
@@ -2243,10 +2243,10 @@
/**
* Creates a {@code String} representation of the {@code int[]} passed. The
- * result is surrounded by brackets ({@code "[]"}), each element
+ * result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(int)} and
- * separated by {@code ", "}. If the array is {@code null}, then
- * {@code "null"} is returned.
+ * separated by {@code ", "}. If the array is {@code null}, then
+ * {@code "null"} is returned.
*
* @param array
* the {@code int} array to convert.
@@ -2273,10 +2273,10 @@
/**
* Creates a {@code String} representation of the {@code long[]} passed. The
- * result is surrounded by brackets ({@code "[]"}), each element
+ * result is surrounded by brackets ({@code "[]"}), each element
* is converted to a {@code String} via the {@link String#valueOf(long)} and
- * separated by {@code ", "}. If the array is {@code null}, then
- * {@code "null"} is returned.
+ * separated by {@code ", "}. If the array is {@code null}, then
+ * {@code "null"} is returned.
*
* @param array
* the {@code long} array to convert.
@@ -2303,10 +2303,10 @@
/**
* Creates a {@code String} representation of the {@code short[]} passed.
- * The result is surrounded by brackets ({@code "[]"}), each
+ * The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
- * {@link String#valueOf(int)} and separated by {@code ", "}. If
- * the array is {@code null}, then {@code "null"} is returned.
+ * {@link String#valueOf(int)} and separated by {@code ", "}. If
+ * the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code short} array to convert.
@@ -2333,10 +2333,10 @@
/**
* Creates a {@code String} representation of the {@code Object[]} passed.
- * The result is surrounded by brackets ({@code "[]"}), each
+ * The result is surrounded by brackets ({@code "[]"}), each
* element is converted to a {@code String} via the
- * {@link String#valueOf(Object)} and separated by {@code ", "}.
- * If the array is {@code null}, then {@code "null"} is returned.
+ * {@link String#valueOf(Object)} and separated by {@code ", "}.
+ * If the array is {@code null}, then {@code "null"} is returned.
*
* @param array
* the {@code Object} array to convert.
diff --git a/luni/src/main/java/java/util/BitSet.java b/luni/src/main/java/java/util/BitSet.java
index e1b9341..23a1d3d 100644
--- a/luni/src/main/java/java/util/BitSet.java
+++ b/luni/src/main/java/java/util/BitSet.java
@@ -257,7 +257,7 @@
/**
* Retrieves the bits starting from {@code fromIndex} to {@code toIndex} and returns
- * back a new bitset made of these bits. Grows the {@code BitSet} if {@code toIndex > size}.
+ * back a new bitset made of these bits. Grows the {@code BitSet} if {@code toIndex > size}.
*
* @param fromIndex
* inclusive beginning position.
diff --git a/luni/src/main/java/java/util/Calendar.java b/luni/src/main/java/java/util/Calendar.java
index 780f647..01b0343 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
@@ -738,7 +738,7 @@
* if {@code field} is {@code DST_OFFSET} or {@code
* ZONE_OFFSET}.
*/
- abstract public void add(int field, int value);
+ public abstract void add(int field, int value);
/**
* Returns whether the {@code Date} specified by this {@code Calendar} instance is after the {@code Date}
@@ -979,7 +979,7 @@
* the field.
* @return the greatest minimum value of the specified field.
*/
- abstract public int getGreatestMinimum(int field);
+ public abstract int getGreatestMinimum(int field);
/**
* Constructs a new instance of the {@code Calendar} subclass appropriate for the
@@ -1042,7 +1042,7 @@
* the field number.
* @return the smallest maximum value of the specified field.
*/
- abstract public int getLeastMaximum(int field);
+ public abstract int getLeastMaximum(int field);
/**
* Gets the greatest maximum value of the specified field. This returns the
@@ -1052,7 +1052,7 @@
* the field.
* @return the greatest maximum value of the specified field.
*/
- abstract public int getMaximum(int field);
+ public abstract int getMaximum(int field);
/**
* Gets the minimal days in the first week of the year.
@@ -1071,7 +1071,7 @@
* the field number.
* @return the smallest minimum value of the specified field.
*/
- abstract public int getMinimum(int field);
+ public abstract int getMinimum(int field);
/**
* Gets the time of this {@code Calendar} as a {@code Date} object.
@@ -1197,7 +1197,7 @@
* @param increment
* {@code true} to increment the field, {@code false} to decrement.
*/
- abstract public void roll(int field, boolean increment);
+ public abstract void roll(int field, boolean increment);
/**
* Sets a field to the specified value.
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/HashMap.java b/luni/src/main/java/java/util/HashMap.java
index 1e5bd0e..4a4e6f6 100644
--- a/luni/src/main/java/java/util/HashMap.java
+++ b/luni/src/main/java/java/util/HashMap.java
@@ -529,7 +529,7 @@
if (newCapacity <= oldCapacity) {
return;
}
- if (newCapacity == oldCapacity << 1) {
+ if (newCapacity == oldCapacity * 2) {
doubleCapacity();
return;
}
@@ -575,7 +575,7 @@
if (oldCapacity == MAXIMUM_CAPACITY) {
return oldTable;
}
- int newCapacity = oldCapacity << 1;
+ int newCapacity = oldCapacity * 2;
HashMapEntry<K, V>[] newTable = makeTable(newCapacity);
if (size == 0) {
return newTable;
diff --git a/luni/src/main/java/java/util/Hashtable.java b/luni/src/main/java/java/util/Hashtable.java
index d260df2..03e80a9 100644
--- a/luni/src/main/java/java/util/Hashtable.java
+++ b/luni/src/main/java/java/util/Hashtable.java
@@ -451,7 +451,7 @@
rehash(); // Does nothing!!
- if (newCapacity == oldCapacity << 1) {
+ if (newCapacity == oldCapacity * 2) {
doubleCapacity();
return;
}
@@ -508,7 +508,7 @@
if (oldCapacity == MAXIMUM_CAPACITY) {
return oldTable;
}
- int newCapacity = oldCapacity << 1;
+ int newCapacity = oldCapacity * 2;
HashtableEntry<K, V>[] newTable = makeTable(newCapacity);
if (size == 0) {
return newTable;
diff --git a/luni/src/main/java/java/util/IdentityHashMap.java b/luni/src/main/java/java/util/IdentityHashMap.java
index 9678b9d..53d3f09 100644
--- a/luni/src/main/java/java/util/IdentityHashMap.java
+++ b/luni/src/main/java/java/util/IdentityHashMap.java
@@ -495,7 +495,7 @@
}
private void rehash() {
- int newlength = elementData.length << 1;
+ int newlength = elementData.length * 2;
if (newlength == 0) {
newlength = 1;
}
diff --git a/luni/src/main/java/java/util/Locale.java b/luni/src/main/java/java/util/Locale.java
index 79e148f..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;
@@ -408,8 +408,8 @@
* to {@code locale}. The exact output form depends on whether this locale
* corresponds to a specific language, country and variant, such as:
* {@code English}, {@code English (United States)}, {@code English (United
- * States,Computer)}, {@code anglais (États-Unis)}, {@code anglais
- * (États-Unis,informatique)}.
+ * States,Computer)}, {@code anglais (États-Unis)}, {@code anglais
+ * (États-Unis,informatique)}.
*/
public String getDisplayName(Locale locale) {
int count = 0;
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 0245329..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();
@@ -445,9 +442,9 @@
* The {@code Scanner}'s search will never go more than {@code horizon} code points from current
* position. The position of {@code horizon} does have an effect on the result of the
* match. For example, when the input is "123" and current position is at zero,
- * {@code findWithinHorizon(Pattern.compile("\\p{Digit}{3}"), 2)}
- * will return {@code null}. While
- * {@code findWithinHorizon(Pattern.compile("\\p{Digit}{3}"), 3)}
+ * <code>findWithinHorizon(Pattern.compile("\\p{Digit}{3}"), 2)</code>
+ * will return {@code null}, while
+ * <code>findWithinHorizon(Pattern.compile("\\p{Digit}{3}"), 3)</code>
* will return {@code "123"}. {@code horizon} is treated as a transparent,
* non-anchoring bound. (refer to
* {@link Matcher#useTransparentBounds(boolean)} and
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/TimSort.java b/luni/src/main/java/java/util/TimSort.java
index 79dc377..928d564 100644
--- a/luni/src/main/java/java/util/TimSort.java
+++ b/luni/src/main/java/java/util/TimSort.java
@@ -509,7 +509,7 @@
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
lastOfs = ofs;
- ofs = (ofs << 1) + 1;
+ ofs = (ofs * 2) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
@@ -524,7 +524,7 @@
final int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
lastOfs = ofs;
- ofs = (ofs << 1) + 1;
+ ofs = (ofs * 2) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
@@ -580,7 +580,7 @@
int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
lastOfs = ofs;
- ofs = (ofs << 1) + 1;
+ ofs = (ofs * 2) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
@@ -596,7 +596,7 @@
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
lastOfs = ofs;
- ofs = (ofs << 1) + 1;
+ ofs = (ofs * 2) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
diff --git a/luni/src/main/java/java/util/UUID.java b/luni/src/main/java/java/util/UUID.java
index e2d7da1..8a39ead 100644
--- a/luni/src/main/java/java/util/UUID.java
+++ b/luni/src/main/java/java/util/UUID.java
@@ -20,9 +20,11 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
+import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
+import org.apache.harmony.luni.platform.OSMemory;
/**
* UUID is an immutable representation of a 128-bit universally unique
@@ -119,34 +121,15 @@
* @return an UUID instance.
*/
public static UUID randomUUID() {
- byte[] data;
+ byte[] data = new byte[16];
// lock on the class to protect lazy init
synchronized (UUID.class) {
if (rng == null) {
rng = new SecureRandom();
}
}
- rng.nextBytes(data = new byte[16]);
- long msb = (data[0] & 0xFFL) << 56;
- msb |= (data[1] & 0xFFL) << 48;
- msb |= (data[2] & 0xFFL) << 40;
- msb |= (data[3] & 0xFFL) << 32;
- msb |= (data[4] & 0xFFL) << 24;
- msb |= (data[5] & 0xFFL) << 16;
- msb |= (data[6] & 0x0FL) << 8;
- msb |= (0x4L << 12); // set the version to 4
- msb |= (data[7] & 0xFFL);
-
- long lsb = (data[8] & 0x3FL) << 56;
- lsb |= (0x2L << 62); // set the variant to bits 01
- lsb |= (data[9] & 0xFFL) << 48;
- lsb |= (data[10] & 0xFFL) << 40;
- lsb |= (data[11] & 0xFFL) << 32;
- lsb |= (data[12] & 0xFFL) << 24;
- lsb |= (data[13] & 0xFFL) << 16;
- lsb |= (data[14] & 0xFFL) << 8;
- lsb |= (data[15] & 0xFFL);
- return new UUID(msb, lsb);
+ rng.nextBytes(data);
+ return makeUuid(data, 4);
}
/**
@@ -162,34 +145,24 @@
if (name == null) {
throw new NullPointerException();
}
-
- byte[] hash;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
- hash = md.digest(name);
+ return makeUuid(md.digest(name), 3);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
+ }
- long msb = (hash[0] & 0xFFL) << 56;
- msb |= (hash[1] & 0xFFL) << 48;
- msb |= (hash[2] & 0xFFL) << 40;
- msb |= (hash[3] & 0xFFL) << 32;
- msb |= (hash[4] & 0xFFL) << 24;
- msb |= (hash[5] & 0xFFL) << 16;
- msb |= (hash[6] & 0x0FL) << 8;
- msb |= (0x3L << 12); // set the version to 3
- msb |= (hash[7] & 0xFFL);
-
- long lsb = (hash[8] & 0x3FL) << 56;
- lsb |= (0x2L << 62); // set the variant to bits 01
- lsb |= (hash[9] & 0xFFL) << 48;
- lsb |= (hash[10] & 0xFFL) << 40;
- lsb |= (hash[11] & 0xFFL) << 32;
- lsb |= (hash[12] & 0xFFL) << 24;
- lsb |= (hash[13] & 0xFFL) << 16;
- lsb |= (hash[14] & 0xFFL) << 8;
- lsb |= (hash[15] & 0xFFL);
+ private static UUID makeUuid(byte[] hash, int version) {
+ long msb = OSMemory.peekLong(hash, 0, ByteOrder.BIG_ENDIAN);
+ long lsb = OSMemory.peekLong(hash, 8, ByteOrder.BIG_ENDIAN);
+ // Set the version field.
+ msb &= ~(0xfL << 12);
+ msb |= ((long) version) << 12;
+ // Set the variant field to 2. Note that the variant field is variable-width,
+ // so supporting other variants is not just a matter of changing the constant 2 below!
+ lsb &= ~(0x3L << 62);
+ lsb |= 2L << 62;
return new UUID(msb, lsb);
}
@@ -227,13 +200,10 @@
}
long m1 = Long.parseLong(uuid.substring(0, position[0]), 16);
- long m2 = Long.parseLong(uuid.substring(position[0] + 1, position[1]),
- 16);
- long m3 = Long.parseLong(uuid.substring(position[1] + 1, position[2]),
- 16);
+ long m2 = Long.parseLong(uuid.substring(position[0] + 1, position[1]), 16);
+ long m3 = Long.parseLong(uuid.substring(position[1] + 1, position[2]), 16);
- long lsb1 = Long.parseLong(
- uuid.substring(position[2] + 1, position[3]), 16);
+ long lsb1 = Long.parseLong(uuid.substring(position[2] + 1, position[3]), 16);
long lsb2 = Long.parseLong(uuid.substring(position[3] + 1), 16);
long msb = (m1 << 32) | (m2 << 16) | m3;
diff --git a/luni/src/main/java/java/util/WeakHashMap.java b/luni/src/main/java/java/util/WeakHashMap.java
index 48da8cb..6417679 100644
--- a/luni/src/main/java/java/util/WeakHashMap.java
+++ b/luni/src/main/java/java/util/WeakHashMap.java
@@ -638,7 +638,7 @@
}
private void rehash() {
- int length = elementData.length << 1;
+ int length = elementData.length * 2;
if (length == 0) {
length = 1;
}
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/jar/Manifest.java b/luni/src/main/java/java/util/jar/Manifest.java
index 618234f..e7476cf 100644
--- a/luni/src/main/java/java/util/jar/Manifest.java
+++ b/luni/src/main/java/java/util/jar/Manifest.java
@@ -24,13 +24,13 @@
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
+import java.nio.charset.Charsets;
import java.nio.charset.CoderResult;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.harmony.luni.util.InputStreamHelper;
-import org.apache.harmony.luni.util.ThreadLocalCache;
/**
* The {@code Manifest} class is used to obtain attribute information for a
@@ -317,20 +317,17 @@
* If an error occurs writing the {@code Manifest}.
*/
static void write(Manifest manifest, OutputStream out) throws IOException {
- CharsetEncoder encoder = ThreadLocalCache.utf8Encoder.get();
- ByteBuffer buffer = ThreadLocalCache.byteBuffer.get();
+ CharsetEncoder encoder = Charsets.UTF_8.newEncoder();
+ ByteBuffer buffer = ByteBuffer.allocate(LINE_LENGTH_LIMIT);
- String version = manifest.mainAttributes
- .getValue(Attributes.Name.MANIFEST_VERSION);
+ String version = manifest.mainAttributes.getValue(Attributes.Name.MANIFEST_VERSION);
if (version != null) {
- writeEntry(out, Attributes.Name.MANIFEST_VERSION, version, encoder,
- buffer);
+ writeEntry(out, Attributes.Name.MANIFEST_VERSION, version, encoder, buffer);
Iterator<?> entries = manifest.mainAttributes.keySet().iterator();
while (entries.hasNext()) {
Attributes.Name name = (Attributes.Name) entries.next();
if (!name.equals(Attributes.Name.MANIFEST_VERSION)) {
- writeEntry(out, name, manifest.mainAttributes
- .getValue(name), encoder, buffer);
+ writeEntry(out, name, manifest.mainAttributes.getValue(name), encoder, buffer);
}
}
}
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/AbstractPreferences.java b/luni/src/main/java/java/util/prefs/AbstractPreferences.java
index 57d8fb0..34073a1 100644
--- a/luni/src/main/java/java/util/prefs/AbstractPreferences.java
+++ b/luni/src/main/java/java/util/prefs/AbstractPreferences.java
@@ -91,9 +91,6 @@
* Instance fields (private)
* -----------------------------------------------------------
*/
- /** Marker class for 'lock' field. */
- private static class Lock {}
-
/**
* The object used to lock this node.
*/
@@ -156,7 +153,7 @@
cachedNode = new HashMap<String, AbstractPreferences>();
nodeName = name;
parentPref = parent;
- lock = new Lock();
+ lock = new Object();
userNode = root.userNode;
}
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/GZIPInputStream.java b/luni/src/main/java/java/util/zip/GZIPInputStream.java
index cd51b25..c52bf72 100644
--- a/luni/src/main/java/java/util/zip/GZIPInputStream.java
+++ b/luni/src/main/java/java/util/zip/GZIPInputStream.java
@@ -20,6 +20,8 @@
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.ByteOrder;
+import org.apache.harmony.luni.platform.OSMemory;
/**
* The {@code GZIPInputStream} class is used to read data stored in the GZIP
@@ -79,8 +81,8 @@
super(is, new Inflater(true), size);
byte[] header = new byte[10];
readFully(header, 0, header.length);
- int magic = getShort(header, 0);
- if (magic != GZIP_MAGIC) {
+ short magic = OSMemory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN);
+ if (magic != (short) GZIP_MAGIC) {
throw new IOException(String.format("unknown format (magic number %x)", magic));
}
int flags = header[3];
@@ -93,7 +95,7 @@
if (hcrc) {
crc.update(header, 0, 2);
}
- int length = getShort(header, 0);
+ int length = OSMemory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN) & 0xffff;
while (length > 0) {
int max = length > buf.length ? buf.length : length;
int result = in.read(buf, 0, max);
@@ -114,8 +116,8 @@
}
if (hcrc) {
readFully(header, 0, 2);
- int crc16 = getShort(header, 0);
- if ((crc.getValue() & 0xffff) != crc16) {
+ short crc16 = OSMemory.peekShort(header, 0, ByteOrder.LITTLE_ENDIAN);
+ if ((short) crc.getValue() != crc16) {
throw new IOException("CRC mismatch");
}
crc.reset();
@@ -131,19 +133,6 @@
super.close();
}
- private long getLong(byte[] buffer, int off) {
- long l = 0;
- l |= (buffer[off] & 0xFF);
- l |= (buffer[off + 1] & 0xFF) << 8;
- l |= (buffer[off + 2] & 0xFF) << 16;
- l |= ((long) (buffer[off + 3] & 0xFF)) << 24;
- return l;
- }
-
- private int getShort(byte[] buffer, int off) {
- return (buffer[off] & 0xFF) | ((buffer[off + 1] & 0xFF) << 8);
- }
-
/**
* Reads and decompresses GZIP data from the underlying stream into the
* given buffer.
@@ -197,16 +186,15 @@
System.arraycopy(buf, len - size, b, 0, copySize);
readFully(b, copySize, trailerSize - copySize);
- if (getLong(b, 0) != crc.getValue()) {
+ if (OSMemory.peekInt(b, 0, ByteOrder.LITTLE_ENDIAN) != (int) crc.getValue()) {
throw new IOException("CRC mismatch");
}
- if ((int) getLong(b, 4) != inf.getTotalOut()) {
+ if (OSMemory.peekInt(b, 4, ByteOrder.LITTLE_ENDIAN) != inf.getTotalOut()) {
throw new IOException("Size mismatch");
}
}
- private void readFully(byte[] buffer, int offset, int length)
- throws IOException {
+ private void readFully(byte[] buffer, int offset, int length) throws IOException {
int result;
while (length > 0) {
result = in.read(buffer, offset, length);
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/InflaterInputStream.java b/luni/src/main/java/java/util/zip/InflaterInputStream.java
index 5136e2c..94c195c 100644
--- a/luni/src/main/java/java/util/zip/InflaterInputStream.java
+++ b/luni/src/main/java/java/util/zip/InflaterInputStream.java
@@ -25,7 +25,7 @@
/**
* This class provides an implementation of {@code FilterInputStream} that
- * uncompresses data that was compressed using the <i>DEFLATE</i> algorithm
+ * decompresses data that was compressed using the <i>DEFLATE</i> algorithm
* (see <a href="http://www.gzip.org/algorithm.txt">specification</a>).
* Basically it wraps the {@code Inflater} class and takes care of the
* buffering.
@@ -83,7 +83,7 @@
* @param is
* the {@code InputStream} to read data from.
* @param inflater
- * the specific {@code Inflater} for uncompressing data.
+ * the specific {@code Inflater} for decompressing data.
*/
public InflaterInputStream(InputStream is, Inflater inflater) {
this(is, inflater, BUF_SIZE);
@@ -96,7 +96,7 @@
* @param is
* the {@code InputStream} to read data from.
* @param inflater
- * the specific {@code Inflater} for uncompressing data.
+ * the specific {@code Inflater} for decompressing data.
* @param bsize
* the size to be used for the internal buffer.
*/
diff --git a/luni/src/main/java/java/util/zip/ZipEntry.java b/luni/src/main/java/java/util/zip/ZipEntry.java
index d99b414..0c123f8 100644
--- a/luni/src/main/java/java/util/zip/ZipEntry.java
+++ b/luni/src/main/java/java/util/zip/ZipEntry.java
@@ -21,10 +21,13 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
+import java.nio.ByteOrder;
import java.nio.charset.Charsets;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
+import libcore.io.BufferIterator;
+import libcore.io.HeapBufferIterator;
/**
* An instance of {@code ZipEntry} represents an entry within a <i>ZIP-archive</i>.
@@ -318,13 +321,16 @@
}
/**
- * Returns a shallow copy of this entry.
- *
- * @return a copy of this entry.
+ * Returns a deep copy of this zip entry.
*/
- @Override
- public Object clone() {
- return new ZipEntry(this);
+ @Override public Object clone() {
+ try {
+ ZipEntry result = (ZipEntry) super.clone();
+ result.extra = extra != null ? extra.clone() : null;
+ return result;
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError(e);
+ }
}
/**
@@ -344,8 +350,7 @@
*
* On exit, "in" will be positioned at the start of the next entry.
*/
- ZipEntry(LittleEndianReader ler, InputStream in) throws IOException {
-
+ ZipEntry(byte[] hdrBuf, InputStream in) throws IOException {
/*
* We're seeing performance issues when we call readShortLE and
* readIntLE, so we're going to read the entire header at once
@@ -357,33 +362,27 @@
* problems induced by sign extension.
*/
- byte[] hdrBuf = ler.hdrBuf;
myReadFully(in, hdrBuf);
- long sig = (hdrBuf[0] & 0xff) | ((hdrBuf[1] & 0xff) << 8) |
- ((hdrBuf[2] & 0xff) << 16) | ((hdrBuf[3] << 24) & 0xffffffffL);
+ BufferIterator it = HeapBufferIterator.iterator(hdrBuf, 0, hdrBuf.length, ByteOrder.LITTLE_ENDIAN);
+
+ int sig = it.readInt();
if (sig != CENSIG) {
throw new ZipException("Central Directory Entry not found");
}
- compressionMethod = (hdrBuf[10] & 0xff) | ((hdrBuf[11] & 0xff) << 8);
- time = (hdrBuf[12] & 0xff) | ((hdrBuf[13] & 0xff) << 8);
- modDate = (hdrBuf[14] & 0xff) | ((hdrBuf[15] & 0xff) << 8);
- crc = (hdrBuf[16] & 0xff) | ((hdrBuf[17] & 0xff) << 8)
- | ((hdrBuf[18] & 0xff) << 16)
- | ((hdrBuf[19] << 24) & 0xffffffffL);
- compressedSize = (hdrBuf[20] & 0xff) | ((hdrBuf[21] & 0xff) << 8)
- | ((hdrBuf[22] & 0xff) << 16)
- | ((hdrBuf[23] << 24) & 0xffffffffL);
- size = (hdrBuf[24] & 0xff) | ((hdrBuf[25] & 0xff) << 8)
- | ((hdrBuf[26] & 0xff) << 16)
- | ((hdrBuf[27] << 24) & 0xffffffffL);
- nameLen = (hdrBuf[28] & 0xff) | ((hdrBuf[29] & 0xff) << 8);
- int extraLen = (hdrBuf[30] & 0xff) | ((hdrBuf[31] & 0xff) << 8);
- int commentLen = (hdrBuf[32] & 0xff) | ((hdrBuf[33] & 0xff) << 8);
- mLocalHeaderRelOffset = (hdrBuf[42] & 0xff) | ((hdrBuf[43] & 0xff) << 8)
- | ((hdrBuf[44] & 0xff) << 16)
- | ((hdrBuf[45] << 24) & 0xffffffffL);
+ it.seek(10);
+ compressionMethod = it.readShort();
+ time = it.readShort();
+ modDate = it.readShort();
+ crc = it.readInt();
+ compressedSize = it.readInt();
+ size = it.readInt();
+ nameLen = it.readShort();
+ int extraLen = it.readShort();
+ int commentLen = it.readShort();
+ it.seek(42);
+ mLocalHeaderRelOffset = it.readInt();
byte[] nameBytes = new byte[nameLen];
myReadFully(in, nameBytes);
@@ -422,50 +421,4 @@
len -= count;
}
}
-
- /*
- * Read a four-byte int in little-endian order.
- */
- static long readIntLE(RandomAccessFile raf) throws IOException {
- int b0 = raf.read();
- int b1 = raf.read();
- int b2 = raf.read();
- int b3 = raf.read();
-
- if (b3 < 0) {
- throw new EOFException("in ZipEntry.readIntLE(RandomAccessFile)");
- }
- return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); // ATTENTION: DOES SIGN EXTENSION: IS THIS WANTED?
- }
-
- static class LittleEndianReader {
- private byte[] b = new byte[4];
- byte[] hdrBuf = new byte[CENHDR];
-
- /*
- * Read a two-byte short in little-endian order.
- */
- int readShortLE(InputStream in) throws IOException {
- if (in.read(b, 0, 2) == 2) {
- return (b[0] & 0XFF) | ((b[1] & 0XFF) << 8);
- } else {
- throw new EOFException("in ZipEntry.readShortLE(InputStream)");
- }
- }
-
- /*
- * Read a four-byte int in little-endian order.
- */
- long readIntLE(InputStream in) throws IOException {
- if (in.read(b, 0, 4) == 4) {
- return ( ((b[0] & 0XFF))
- | ((b[1] & 0XFF) << 8)
- | ((b[2] & 0XFF) << 16)
- | ((b[3] & 0XFF) << 24))
- & 0XFFFFFFFFL; // Here for sure NO sign extension is wanted.
- } else {
- throw new EOFException("in ZipEntry.readIntLE(InputStream)");
- }
- }
- }
}
diff --git a/luni/src/main/java/java/util/zip/ZipFile.java b/luni/src/main/java/java/util/zip/ZipFile.java
index 8f70aeb..61f3afc 100644
--- a/luni/src/main/java/java/util/zip/ZipFile.java
+++ b/luni/src/main/java/java/util/zip/ZipFile.java
@@ -17,16 +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.
@@ -80,10 +86,9 @@
private RandomAccessFile mRaf;
- private final ZipEntry.LittleEndianReader ler = new ZipEntry.LittleEndianReader();
+ private final LinkedHashMap<String, ZipEntry> mEntries = new LinkedHashMap<String, ZipEntry>();
- 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.
@@ -133,6 +138,7 @@
mRaf = new RandomAccessFile(fileName, "r");
readCentralDir();
+ guard.open("close");
}
/**
@@ -149,7 +155,9 @@
@Override protected void finalize() throws IOException {
try {
- close();
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
} finally {
try {
super.finalize();
@@ -166,6 +174,7 @@
* if an IOException occurs.
*/
public void close() throws IOException {
+ guard.close();
RandomAccessFile raf = mRaf;
if (raf != null) { // Only close initialized instances
@@ -249,27 +258,24 @@
* @throws IllegalStateException if this ZIP file has been closed.
*/
public InputStream getInputStream(ZipEntry entry) throws IOException {
- /*
- * Make sure this ZipEntry is in this Zip file. We run it through
- * the name lookup.
- */
+ // Make sure this ZipEntry is in this Zip file. We run it through the name lookup.
entry = getEntry(entry.getName());
if (entry == null) {
return null;
}
- /*
- * Create a ZipInputStream at the right part of the file.
- */
+ // Create an InputStream at the right part of the file.
RandomAccessFile raf = mRaf;
synchronized (raf) {
// We don't know the entry data's start position. All we have is the
// position of the entry's local header. At position 28 we find the
// length of the extra data. In some cases this length differs from
// the one coming in the central header.
- RAFStream rafstrm = new RAFStream(raf,
- entry.mLocalHeaderRelOffset + 28);
- int localExtraLenOrWhatever = ler.readShortLE(rafstrm);
+ RAFStream rafstrm = new RAFStream(raf, entry.mLocalHeaderRelOffset + 28);
+ DataInputStream is = new DataInputStream(rafstrm);
+ int localExtraLenOrWhatever = Short.reverseBytes(is.readShort());
+ is.close();
+
// Skip the name and this "extra" data or whatever it is:
rafstrm.skip(entry.nameLen + localExtraLenOrWhatever);
rafstrm.mLength = rafstrm.mOffset + entry.compressedSize;
@@ -334,9 +340,10 @@
stopOffset = 0;
}
+ final int ENDHEADERMAGIC = 0x06054b50;
while (true) {
mRaf.seek(scanOffset);
- if (ZipEntry.readIntLE(mRaf) == 101010256L) {
+ if (Integer.reverseBytes(mRaf.readInt()) == ENDHEADERMAGIC) {
break;
}
@@ -346,38 +353,30 @@
}
}
- /*
- * 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());
- BufferedInputStream bin = 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);
- int diskNumber = ler.readShortLE(bin);
- int diskWithCentralDir = ler.readShortLE(bin);
- int numEntries = ler.readShortLE(bin);
- int totalNumEntries = ler.readShortLE(bin);
- /*centralDirSize =*/ ler.readIntLE(bin);
- long centralDirOffset = ler.readIntLE(bin);
- /*commentLen =*/ ler.readShortLE(bin);
+ // 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) {
+ 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);
- bin = new BufferedInputStream(rafs, 4096);
- for (int i = 0; i < numEntries; i++) {
- ZipEntry newEntry = new ZipEntry(ler, bin);
+ // 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) {
+ ZipEntry newEntry = new ZipEntry(hdrBuf, bin);
mEntries.put(newEntry.getName(), newEntry);
}
}
diff --git a/luni/src/main/java/java/util/zip/ZipInputStream.java b/luni/src/main/java/java/util/zip/ZipInputStream.java
index 87b566f..673a132 100644
--- a/luni/src/main/java/java/util/zip/ZipInputStream.java
+++ b/luni/src/main/java/java/util/zip/ZipInputStream.java
@@ -21,13 +21,16 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
+import java.nio.ByteOrder;
import java.nio.charset.ModifiedUtf8;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
+import libcore.base.Streams;
+import org.apache.harmony.luni.platform.OSMemory;
/**
* 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 +127,7 @@
// Ensure all entry bytes are read
Exception failure = null;
try {
- skip(Long.MAX_VALUE);
+ Streams.skipAll(this);
} catch (Exception e) {
failure = e;
}
@@ -171,13 +174,13 @@
private void readAndVerifyDataDescriptor(int inB, int out) throws IOException {
if (hasDD) {
in.read(hdrBuf, 0, EXTHDR);
- long sig = getLong(hdrBuf, 0);
+ long sig = OSMemory.peekInt(hdrBuf, 0, ByteOrder.LITTLE_ENDIAN);
if (sig != EXTSIG) {
throw new ZipException(String.format("unknown format (EXTSIG=%x)", sig));
}
- currentEntry.crc = getLong(hdrBuf, EXTCRC);
- currentEntry.compressedSize = getLong(hdrBuf, EXTSIZ);
- currentEntry.size = getLong(hdrBuf, EXTLEN);
+ currentEntry.crc = OSMemory.peekInt(hdrBuf, EXTCRC, ByteOrder.LITTLE_ENDIAN);
+ currentEntry.compressedSize = OSMemory.peekInt(hdrBuf, EXTSIZ, ByteOrder.LITTLE_ENDIAN);
+ currentEntry.size = OSMemory.peekInt(hdrBuf, EXTLEN, ByteOrder.LITTLE_ENDIAN);
}
if (currentEntry.crc != crc.getValue()) {
throw new ZipException("CRC mismatch");
@@ -209,7 +212,7 @@
return null;
}
}
- long hdr = getLong(hdrBuf, 0);
+ long hdr = OSMemory.peekInt(hdrBuf, 0, ByteOrder.LITTLE_ENDIAN);
if (hdr == CENSIG) {
entriesEnd = true;
return null;
@@ -226,26 +229,26 @@
throw new EOFException();
}
}
- int version = getShort(hdrBuf, 0) & 0xff;
+ int version = OSMemory.peekShort(hdrBuf, 0, ByteOrder.LITTLE_ENDIAN) & 0xff;
if (version > ZIPLocalHeaderVersionNeeded) {
throw new ZipException("Cannot read local header version " + version);
}
- int flags = getShort(hdrBuf, LOCFLG - LOCVER);
+ int flags = OSMemory.peekShort(hdrBuf, LOCFLG - LOCVER, ByteOrder.LITTLE_ENDIAN);
hasDD = ((flags & ZipFile.GPBF_DATA_DESCRIPTOR_FLAG) != 0);
- int cetime = getShort(hdrBuf, LOCTIM - LOCVER);
- int cemodDate = getShort(hdrBuf, LOCTIM - LOCVER + 2);
- int cecompressionMethod = getShort(hdrBuf, LOCHOW - LOCVER);
+ int cetime = OSMemory.peekShort(hdrBuf, LOCTIM - LOCVER, ByteOrder.LITTLE_ENDIAN);
+ int cemodDate = OSMemory.peekShort(hdrBuf, LOCTIM - LOCVER + 2, ByteOrder.LITTLE_ENDIAN);
+ int cecompressionMethod = OSMemory.peekShort(hdrBuf, LOCHOW - LOCVER, ByteOrder.LITTLE_ENDIAN);
long cecrc = 0, cecompressedSize = 0, cesize = -1;
if (!hasDD) {
- cecrc = getLong(hdrBuf, LOCCRC - LOCVER);
- cecompressedSize = getLong(hdrBuf, LOCSIZ - LOCVER);
- cesize = getLong(hdrBuf, LOCLEN - LOCVER);
+ cecrc = OSMemory.peekInt(hdrBuf, LOCCRC - LOCVER, ByteOrder.LITTLE_ENDIAN);
+ cecompressedSize = OSMemory.peekInt(hdrBuf, LOCSIZ - LOCVER, ByteOrder.LITTLE_ENDIAN);
+ cesize = OSMemory.peekInt(hdrBuf, LOCLEN - LOCVER, ByteOrder.LITTLE_ENDIAN);
}
- int flen = getShort(hdrBuf, LOCNAM - LOCVER);
+ int flen = OSMemory.peekShort(hdrBuf, LOCNAM - LOCVER, ByteOrder.LITTLE_ENDIAN);
if (flen == 0) {
throw new ZipException("Entry is not named");
}
- int elen = getShort(hdrBuf, LOCEXT - LOCVER);
+ int elen = OSMemory.peekShort(hdrBuf, LOCEXT - LOCVER, ByteOrder.LITTLE_ENDIAN);
count = 0;
if (flen > nameBuf.length) {
@@ -298,15 +301,16 @@
@Override
public int read(byte[] buffer, int start, int length) throws IOException {
checkClosed();
- if (inf.finished() || currentEntry == null) {
- return -1;
- }
// avoid int overflow, check null buffer
if (start > buffer.length || length < 0 || start < 0
|| buffer.length - start < length) {
throw new ArrayIndexOutOfBoundsException();
}
+ if (inf.finished() || currentEntry == null) {
+ return -1;
+ }
+
if (currentEntry.compressionMethod == STORED) {
int csize = (int) currentEntry.size;
if (inRead >= csize) {
@@ -349,34 +353,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();
@@ -395,19 +371,6 @@
return new ZipEntry(name);
}
- private int getShort(byte[] buffer, int off) {
- return (buffer[off] & 0xFF) | ((buffer[off + 1] & 0xFF) << 8);
- }
-
- private long getLong(byte[] buffer, int off) {
- long l = 0;
- l |= (buffer[off] & 0xFF);
- l |= (buffer[off + 1] & 0xFF) << 8;
- l |= (buffer[off + 2] & 0xFF) << 16;
- l |= ((long) (buffer[off + 3] & 0xFF)) << 24;
- return l;
- }
-
private void checkClosed() throws IOException {
if (closed) {
throw new IOException("Stream is closed");
diff --git a/luni/src/main/java/javax/crypto/Cipher.java b/luni/src/main/java/javax/crypto/Cipher.java
index 20dca98..7d5f9ed 100644
--- a/luni/src/main/java/javax/crypto/Cipher.java
+++ b/luni/src/main/java/javax/crypto/Cipher.java
@@ -107,7 +107,7 @@
/**
* Used to access common engine functionality.
*/
- private static final Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
/**
* The provider.
@@ -264,53 +264,60 @@
boolean needSetPadding = false;
boolean needSetMode = false;
+ Object engineSpi = null;
+ Provider engineProvider = provider;
if (transf[1] == null && transf[2] == null) { // "algorithm"
if (provider == null) {
- engine.getInstance(transf[0], null);
+ Engine.SpiAndProvider sap = ENGINE.getInstance(transf[0], null);
+ engineSpi = sap.spi;
+ engineProvider = sap.provider;
} else {
- engine.getInstance(transf[0], provider, null);
+ engineSpi = ENGINE.getInstance(transf[0], provider, null);
}
} else {
- String[] searhOrder = {
- transf[0] + "/" + transf[1] + "/" + transf[2], // "algorithm/mode/padding"
- transf[0] + "/" + transf[1], // "algorithm/mode"
- transf[0] + "//" + transf[2], // "algorithm//padding"
- transf[0] // "algorithm"
+ String[] searchOrder = {
+ transf[0] + "/" + transf[1] + "/" + transf[2], // "algorithm/mode/padding"
+ transf[0] + "/" + transf[1], // "algorithm/mode"
+ transf[0] + "//" + transf[2], // "algorithm//padding"
+ transf[0] // "algorithm"
};
int i;
- for (i = 0; i < searhOrder.length; i++) {
+ for (i = 0; i < searchOrder.length; i++) {
try {
if (provider == null) {
- engine.getInstance(searhOrder[i], null);
+ Engine.SpiAndProvider sap = ENGINE.getInstance(searchOrder[i], null);
+ engineSpi = sap.spi;
+ engineProvider = sap.provider;
} else {
- engine.getInstance(searhOrder[i], provider, null);
+ engineSpi = ENGINE.getInstance(searchOrder[i], provider, null);
}
break;
} catch (NoSuchAlgorithmException e) {
- if ( i == searhOrder.length-1) {
+ if (i == searchOrder.length-1) {
throw new NoSuchAlgorithmException(transformation);
}
}
}
switch (i) {
- case 1: // "algorithm/mode"
- needSetPadding = true;
- break;
- case 2: // "algorithm//padding"
- needSetMode = true;
- break;
- case 3: // "algorithm"
- needSetPadding = true;
- needSetMode = true;
+ case 1: // "algorithm/mode"
+ needSetPadding = true;
+ break;
+ case 2: // "algorithm//padding"
+ needSetMode = true;
+ break;
+ case 3: // "algorithm"
+ needSetPadding = true;
+ needSetMode = true;
}
}
- CipherSpi cspi;
- try {
- cspi = (CipherSpi) engine.spi;
- } catch (ClassCastException e) {
- throw new NoSuchAlgorithmException(e);
+ if (engineSpi == null || engineProvider == null) {
+ throw new NoSuchAlgorithmException(transformation);
}
- Cipher c = new Cipher(cspi, engine.provider, transformation);
+ if (!(engineSpi instanceof CipherSpi)) {
+ throw new NoSuchAlgorithmException(engineSpi.getClass().getName());
+ }
+ CipherSpi cspi = (CipherSpi) engineSpi;
+ Cipher c = new Cipher(cspi, engineProvider, transformation);
if (needSetMode) {
c.spiImpl.engineSetMode(transf[1]);
}
@@ -513,7 +520,8 @@
}
private void checkMode(int mode) {
- if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE && mode != UNWRAP_MODE && mode != WRAP_MODE) {
+ if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE
+ && mode != UNWRAP_MODE && mode != WRAP_MODE) {
throw new InvalidParameterException("Invalid mode: " + mode);
}
}
@@ -801,9 +809,11 @@
// decipherOnly (8) }
if (keyUsage != null) {
if (opmode == ENCRYPT_MODE && (!keyUsage[7])) {
- throw new InvalidKeyException("The public key in the certificate cannot be used for ENCRYPT_MODE");
+ throw new InvalidKeyException("The public key in the certificate "
+ + "cannot be used for ENCRYPT_MODE");
} else if (opmode == DECRYPT_MODE && (!keyUsage[8])) {
- throw new InvalidKeyException("The public key in the certificate cannot be used for DECRYPT_MODE");
+ throw new InvalidKeyException("The public key in the certificate "
+ + "cannot be used for DECRYPT_MODE");
}
}
}
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/crypto/ExemptionMechanism.java b/luni/src/main/java/javax/crypto/ExemptionMechanism.java
index fe7e553..2ac4994 100644
--- a/luni/src/main/java/javax/crypto/ExemptionMechanism.java
+++ b/luni/src/main/java/javax/crypto/ExemptionMechanism.java
@@ -36,7 +36,7 @@
public class ExemptionMechanism {
// Used to access common engine functionality
- private static final Engine engine = new Engine("ExemptionMechanism");
+ private static final Engine ENGINE = new Engine("ExemptionMechanism");
// Store used provider
private final Provider provider;
@@ -100,11 +100,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new ExemptionMechanism((ExemptionMechanismSpi) engine.spi,
- engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new ExemptionMechanism((ExemptionMechanismSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -167,11 +164,8 @@
if (provider == null) {
throw new IllegalArgumentException("provider == null");
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new ExemptionMechanism((ExemptionMechanismSpi) engine.spi,
- provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new ExemptionMechanism((ExemptionMechanismSpi) spi, provider, algorithm);
}
/**
@@ -373,6 +367,8 @@
try {
super.finalize();
} catch (Throwable t) {
+ // for consistency with the RI, we must override Object.finalize() to
+ // remove the throws clause.
throw new AssertionError(t);
}
}
diff --git a/luni/src/main/java/javax/crypto/KeyAgreement.java b/luni/src/main/java/javax/crypto/KeyAgreement.java
index 8df7447..9c5d86c 100644
--- a/luni/src/main/java/javax/crypto/KeyAgreement.java
+++ b/luni/src/main/java/javax/crypto/KeyAgreement.java
@@ -36,10 +36,10 @@
public class KeyAgreement {
// Used to access common engine functionality
- private static final Engine engine = new Engine("KeyAgreement");
+ private static final Engine ENGINE = new Engine("KeyAgreement");
// Store SecureRandom
- private static final SecureRandom rndm = new SecureRandom();
+ private static final SecureRandom RANDOM = new SecureRandom();
// Store used provider
private final Provider provider;
@@ -101,11 +101,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new KeyAgreement((KeyAgreementSpi) engine.spi, engine.provider,
- algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new KeyAgreement((KeyAgreementSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -166,11 +163,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new KeyAgreement((KeyAgreementSpi) engine.spi, provider,
- algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new KeyAgreement((KeyAgreementSpi) spi, provider, algorithm);
}
/**
@@ -183,7 +177,7 @@
* agreement.
*/
public final void init(Key key) throws InvalidKeyException {
- spiImpl.engineInit(key, rndm);//new SecureRandom());
+ spiImpl.engineInit(key, RANDOM);//new SecureRandom());
}
/**
@@ -220,7 +214,7 @@
*/
public final void init(Key key, AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
- spiImpl.engineInit(key, params, rndm);//new SecureRandom());
+ spiImpl.engineInit(key, params, RANDOM);//new SecureRandom());
}
/**
diff --git a/luni/src/main/java/javax/crypto/KeyGenerator.java b/luni/src/main/java/javax/crypto/KeyGenerator.java
index 915662c..77b1a82 100644
--- a/luni/src/main/java/javax/crypto/KeyGenerator.java
+++ b/luni/src/main/java/javax/crypto/KeyGenerator.java
@@ -34,10 +34,10 @@
public class KeyGenerator {
// Used to access common engine functionality
- private static final Engine engine = new Engine("KeyGenerator");
+ private static final Engine ENGINE = new Engine("KeyGenerator");
// Store SecureRandom
- private static final SecureRandom rndm = new SecureRandom();
+ private static final SecureRandom RANDOM = new SecureRandom();
// Store used provider
private final Provider provider;
@@ -100,11 +100,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new KeyGenerator((KeyGeneratorSpi) engine.spi, engine.provider,
- algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new KeyGenerator((KeyGeneratorSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -163,11 +160,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new KeyGenerator((KeyGeneratorSpi) engine.spi, provider,
- algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new KeyGenerator((KeyGeneratorSpi) spi, provider, algorithm);
}
/**
@@ -191,7 +185,7 @@
*/
public final void init(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
- spiImpl.engineInit(params, rndm);//new SecureRandom());
+ spiImpl.engineInit(params, RANDOM);//new SecureRandom());
}
/**
@@ -219,7 +213,7 @@
* the size of the key (in bits).
*/
public final void init(int keysize) {
- spiImpl.engineInit(keysize, rndm);//new SecureRandom());
+ spiImpl.engineInit(keysize, RANDOM);//new SecureRandom());
}
/**
diff --git a/luni/src/main/java/javax/crypto/Mac.java b/luni/src/main/java/javax/crypto/Mac.java
index 1e98db8..1a05b59 100644
--- a/luni/src/main/java/javax/crypto/Mac.java
+++ b/luni/src/main/java/javax/crypto/Mac.java
@@ -36,7 +36,7 @@
public class Mac implements Cloneable {
//Used to access common engine functionality
- private static final Engine engine = new Engine("Mac");
+ private static final Engine ENGINE = new Engine("Mac");
// Store used provider
private final Provider provider;
@@ -103,10 +103,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new Mac((MacSpi) engine.spi, engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new Mac((MacSpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -167,10 +165,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new Mac((MacSpi) engine.spi, provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new Mac((MacSpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/javax/crypto/SecretKeyFactory.java b/luni/src/main/java/javax/crypto/SecretKeyFactory.java
index 05dc1ba..5e47abe1 100644
--- a/luni/src/main/java/javax/crypto/SecretKeyFactory.java
+++ b/luni/src/main/java/javax/crypto/SecretKeyFactory.java
@@ -42,7 +42,7 @@
public class SecretKeyFactory {
// Used to access common engine functionality
- private static final Engine engine = new Engine("SecretKeyFactory");
+ private static final Engine ENGINE = new Engine("SecretKeyFactory");
// Store used provider
private final Provider provider;
@@ -105,11 +105,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new SecretKeyFactory((SecretKeyFactorySpi) engine.spi,
- engine.provider, algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new SecretKeyFactory((SecretKeyFactorySpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -170,11 +167,8 @@
if (algorithm == null) {
throw new NullPointerException();
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new SecretKeyFactory((SecretKeyFactorySpi) engine.spi, provider,
- algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new SecretKeyFactory((SecretKeyFactorySpi) spi, provider, algorithm);
}
/**
diff --git a/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java b/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java
index 21b9b59..c5c9196 100644
--- a/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java
+++ b/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java
@@ -37,7 +37,7 @@
private static final String SERVICE = "KeyManagerFactory";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store default property name
private static final String PROPERTY_NAME = "ssl.KeyManagerFactory.algorithm";
@@ -76,11 +76,8 @@
if (algorithm == null) {
throw new NullPointerException("algorithm is null");
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new KeyManagerFactory((KeyManagerFactorySpi) engine.spi, engine.provider,
- algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new KeyManagerFactory((KeyManagerFactorySpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -138,10 +135,8 @@
if (algorithm == null) {
throw new NullPointerException("algorithm is null");
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new KeyManagerFactory((KeyManagerFactorySpi) engine.spi, provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new KeyManagerFactory((KeyManagerFactorySpi) spi, provider, algorithm);
}
// Store used provider
@@ -163,8 +158,8 @@
* @param algorithm
* the key management algorithm name.
*/
- protected KeyManagerFactory(KeyManagerFactorySpi factorySpi, Provider provider, String algorithm) {
- super();
+ protected KeyManagerFactory(KeyManagerFactorySpi factorySpi, Provider provider,
+ String algorithm) {
this.provider = provider;
this.algorithm = algorithm;
this.spiImpl = factorySpi;
@@ -216,7 +211,8 @@
* @throws InvalidAlgorithmParameterException
* if an error occurs.
*/
- public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException {
+ public final void init(ManagerFactoryParameters spec)
+ throws InvalidAlgorithmParameterException {
spiImpl.engineInit(spec);
}
diff --git a/luni/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java b/luni/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
index 195eb43..f7fe7e8 100644
--- a/luni/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
+++ b/luni/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
@@ -41,7 +41,6 @@
* the key store builder.
*/
public KeyStoreBuilderParameters(KeyStore.Builder builder) {
- super();
ksbuilders = Collections.singletonList(builder);
}
@@ -55,7 +54,6 @@
* if the specified list is empty.
*/
public KeyStoreBuilderParameters(List<KeyStore.Builder> parameters) {
- super();
if (parameters == null) {
throw new NullPointerException("Builders list is null");
}
diff --git a/luni/src/main/java/javax/net/ssl/SSLContext.java b/luni/src/main/java/javax/net/ssl/SSLContext.java
index 5299771..9097bb9 100644
--- a/luni/src/main/java/javax/net/ssl/SSLContext.java
+++ b/luni/src/main/java/javax/net/ssl/SSLContext.java
@@ -95,10 +95,8 @@
if (protocol == null) {
throw new NullPointerException("protocol is null");
}
- synchronized (ENGINE) {
- ENGINE.getInstance(protocol, null);
- return new SSLContext((SSLContextSpi) ENGINE.spi, ENGINE.provider, protocol);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(protocol, null);
+ return new SSLContext((SSLContextSpi) sap.spi, sap.provider, protocol);
}
/**
@@ -158,10 +156,8 @@
if (protocol == null) {
throw new NullPointerException("protocol is null");
}
- synchronized (ENGINE) {
- ENGINE.getInstance(protocol, provider, null);
- return new SSLContext((SSLContextSpi) ENGINE.spi, provider, protocol);
- }
+ Object spi = ENGINE.getInstance(protocol, provider, null);
+ return new SSLContext((SSLContextSpi) spi, provider, protocol);
}
private final Provider provider;
diff --git a/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java b/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java
index 896a486..04633a4 100644
--- a/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java
+++ b/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java
@@ -37,7 +37,7 @@
private static final String SERVICE = "TrustManagerFactory";
// Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
+ private static final Engine ENGINE = new Engine(SERVICE);
// Store default property name
private static final String PROPERTYNAME = "ssl.TrustManagerFactory.algorithm";
@@ -75,11 +75,8 @@
if (algorithm == null) {
throw new NullPointerException("algorithm is null");
}
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new TrustManagerFactory((TrustManagerFactorySpi) engine.spi, engine.provider,
- algorithm);
- }
+ Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ return new TrustManagerFactory((TrustManagerFactorySpi) sap.spi, sap.provider, algorithm);
}
/**
@@ -137,10 +134,8 @@
if (algorithm == null) {
throw new NullPointerException("algorithm is null");
}
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new TrustManagerFactory((TrustManagerFactorySpi) engine.spi, provider, algorithm);
- }
+ Object spi = ENGINE.getInstance(algorithm, provider, null);
+ return new TrustManagerFactory((TrustManagerFactorySpi) spi, provider, algorithm);
}
// Store used provider
@@ -211,7 +206,8 @@
* @throws InvalidAlgorithmParameterException
* if the initialization fails.
*/
- public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException {
+ public final void init(ManagerFactoryParameters spec)
+ throws InvalidAlgorithmParameterException {
spiImpl.engineInit(spec);
}
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/libcore/base/CollectionUtils.java b/luni/src/main/java/libcore/base/CollectionUtils.java
new file mode 100644
index 0000000..322cc9e
--- /dev/null
+++ b/luni/src/main/java/libcore/base/CollectionUtils.java
@@ -0,0 +1,76 @@
+/*
+ * 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.base;
+
+import java.lang.ref.Reference;
+import java.util.Iterator;
+
+public final class CollectionUtils {
+ private CollectionUtils() {}
+
+ /**
+ * Returns an iterator over the values referenced by the elements of {@code
+ * iterable}.
+ *
+ * @param trim true to remove reference objects from the iterable after
+ * their referenced values have been cleared.
+ */
+ public static <T> Iterable<T> dereferenceIterable(
+ final Iterable<? extends Reference<T>> iterable, final boolean trim) {
+ return new Iterable<T>() {
+ public Iterator<T> iterator() {
+ return new Iterator<T>() {
+ private final Iterator<? extends Reference<T>> delegate = iterable.iterator();
+ private boolean removeIsOkay;
+ private T next;
+
+ private void computeNext() {
+ removeIsOkay = false;
+ while (next == null && delegate.hasNext()) {
+ next = delegate.next().get();
+ if (trim && next == null) {
+ delegate.remove();
+ }
+ }
+ }
+
+ @Override public boolean hasNext() {
+ computeNext();
+ return next != null;
+ }
+
+ @Override public T next() {
+ if (!hasNext()) {
+ throw new IllegalStateException();
+ }
+ T result = next;
+ removeIsOkay = true;
+ next = null;
+ return result;
+ }
+
+ public void remove() {
+ if (!removeIsOkay) {
+ throw new IllegalStateException();
+ }
+ delegate.remove();
+ }
+ };
+ }
+ };
+ }
+}
diff --git a/luni/src/main/java/libcore/base/Streams.java b/luni/src/main/java/libcore/base/Streams.java
index 6d38e4f..e746389 100644
--- a/luni/src/main/java/libcore/base/Streams.java
+++ b/luni/src/main/java/libcore/base/Streams.java
@@ -16,6 +16,7 @@
package libcore.base;
+import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicReference;
@@ -25,6 +26,33 @@
private Streams() {}
+ /**
+ * Implements {@link java.io.DataInputStream#readFully(byte[], int, int)}.
+ */
+ public static void readFully(InputStream in, byte[] dst, int offset, int byteCount) throws IOException {
+ if (byteCount == 0) {
+ return;
+ }
+ if (in == null) {
+ throw new NullPointerException("in == null");
+ }
+ if (dst == null) {
+ throw new NullPointerException("dst == null");
+ }
+ if ((offset | byteCount) < 0 || offset > dst.length - byteCount) {
+ throw new IndexOutOfBoundsException("offset=" + offset + " byteCount=" + byteCount +
+ " dst.length=" + dst.length);
+ }
+ while (byteCount > 0) {
+ int bytesRead = in.read(dst, offset, byteCount);
+ if (bytesRead < 0) {
+ throw new EOFException();
+ }
+ offset += bytesRead;
+ byteCount -= bytesRead;
+ }
+ }
+
public static void skipAll(InputStream in) throws IOException {
do {
in.skip(Long.MAX_VALUE);
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
new file mode 100644
index 0000000..7f3ad47
--- /dev/null
+++ b/luni/src/main/java/libcore/io/BufferIterator.java
@@ -0,0 +1,62 @@
+/*
+ * 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;
+
+/**
+ * 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 abstract class BufferIterator {
+ /**
+ * Seeks to the absolute position {@code offset}, measured in bytes from the start.
+ */
+ public abstract void seek(int offset);
+
+ /**
+ * Skips forwards or backwards {@code byteCount} bytes from the current position.
+ */
+ 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 abstract void readByteArray(byte[] dst, int dstOffset, int byteCount);
+
+ /**
+ * Returns the byte at the current position, and advances the current position one byte.
+ */
+ public abstract byte readByte();
+
+ /**
+ * Returns the 32-bit int at the current position, and advances the current position four bytes.
+ */
+ 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 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..ab44b99
--- /dev/null
+++ b/luni/src/main/java/libcore/io/HeapBufferIterator.java
@@ -0,0 +1,86 @@
+/*
+ * 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 seek(int offset) {
+ position = offset;
+ }
+
+ 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 30c48c9..29a64ba 100644
--- a/luni/src/main/java/libcore/io/IoUtils.java
+++ b/luni/src/main/java/libcore/io/IoUtils.java
@@ -19,6 +19,8 @@
import java.io.Closeable;
import java.io.FileDescriptor;
import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.net.Socket;
public final class IoUtils {
private IoUtils() {
@@ -42,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);
@@ -71,4 +85,19 @@
* Sets 'fd' to be blocking or non-blocking, according to the state of 'blocking'.
*/
public static native void setBlocking(FileDescriptor fd, boolean blocking) throws IOException;
+
+ /**
+ * Returns the contents of 'path' as a byte array.
+ */
+ public static byte[] readFileAsByteArray(String path) throws IOException {
+ RandomAccessFile f = null;
+ try {
+ f = new RandomAccessFile(path, "r");
+ byte[] buf = new byte[(int) f.length()];
+ f.readFully(buf);
+ return buf;
+ } finally {
+ IoUtils.closeQuietly(f);
+ }
+ }
}
diff --git a/luni/src/main/java/libcore/io/MemoryMappedFile.java b/luni/src/main/java/libcore/io/MemoryMappedFile.java
new file mode 100644
index 0000000..10ef8f0
--- /dev/null
+++ b/luni/src/main/java/libcore/io/MemoryMappedFile.java
@@ -0,0 +1,100 @@
+/*
+ * 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.io.Closeable;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.nio.ByteOrder;
+import java.nio.NioUtils;
+import java.nio.channels.FileChannel;
+import org.apache.harmony.luni.platform.OSMemory;
+
+/**
+ * A memory-mapped file. Use {@link #mmap} to map a file, {@link #close} to unmap a file,
+ * and either {@link #bigEndianIterator} or {@link #littleEndianIterator} to get a seekable
+ * {@link BufferIterator} over the mapped data.
+ */
+public final class MemoryMappedFile implements Closeable {
+ private int address;
+
+ // Until we have 64-bit address spaces, we only need an int for 'size'.
+ private final int size;
+
+ private MemoryMappedFile(int address, int size) {
+ this.address = address;
+ this.size = size;
+ }
+
+ public static MemoryMappedFile mmap(FileChannel fc, FileChannel.MapMode mapMode, long start, long size) throws IOException {
+ return mmap(NioUtils.getFd(fc), mapMode, start, size);
+ }
+
+ public static MemoryMappedFile mmap(FileDescriptor fd, FileChannel.MapMode mapMode, long start, long size) throws IOException {
+ return mmap(IoUtils.getFd(fd), mapMode, start, size);
+ }
+
+ private static MemoryMappedFile mmap(int fd, FileChannel.MapMode mapMode, long start, long size) throws IOException {
+ if (start < 0) {
+ throw new IllegalArgumentException("start < 0: " + start);
+ }
+ if (size <= 0) {
+ throw new IllegalArgumentException("size <= 0: " + size);
+ }
+ if ((start + size) > Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("(start + size) > Integer.MAX_VALUE");
+ }
+ int address = OSMemory.mmap(fd, start, size, mapMode);
+ return new MemoryMappedFile(address, (int) size);
+ }
+
+ /**
+ * Unmaps this memory-mapped file using munmap(2). This is a no-op if close has already been
+ * called. Note that this class does <i>not</i> use finalization; you must call {@code close}
+ * yourself.
+ *
+ * Calling this method invalidates any iterators over this {@code MemoryMappedFile}. It is an
+ * error to use such an iterator after calling {@code close}.
+ */
+ public synchronized void close() throws IOException {
+ if (address != 0) {
+ OSMemory.munmap(address, size);
+ address = 0;
+ }
+ }
+
+ /**
+ * Returns a new iterator that treats the mapped data as big-endian.
+ */
+ public BufferIterator bigEndianIterator() {
+ 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 NioBufferIterator(address, size, ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN);
+ }
+
+ /**
+ * Returns the size in bytes of the memory-mapped region.
+ */
+ public int size() {
+ return size;
+ }
+}
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..4a44c97
--- /dev/null
+++ b/luni/src/main/java/libcore/io/NioBufferIterator.java
@@ -0,0 +1,75 @@
+/*
+ * 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 seek(int offset) {
+ position = offset;
+ }
+
+ 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/file/FileURLConnection.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/file/FileURLConnection.java
index 10386d2..3fb49fd 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/file/FileURLConnection.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/file/FileURLConnection.java
@@ -80,7 +80,8 @@
// use -1 for the contentLength
} else {
is = new BufferedInputStream(new FileInputStream(f));
- length = is.available();
+ long lengthAsLong = f.length();
+ length = lengthAsLong <= Integer.MAX_VALUE ? (int) lengthAsLong : Integer.MAX_VALUE;
}
connected = true;
}
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/Header.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.java
deleted file mode 100644
index 50ca102..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/Header.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 org.apache.harmony.luni.internal.net.www.protocol.http;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.SortedMap;
-import java.util.TreeMap;
-import java.util.logging.Logger;
-
-/**
- * The general structure for request / response header. It is essentially
- * constructed by hashtable with key indexed in a vector for position lookup.
- */
-public class Header implements Cloneable {
- private ArrayList<String> props;
-
- private SortedMap<String, LinkedList<String>> keyTable;
-
- private String statusLine;
-
- /**
- * A generic header structure. Used mostly for request / response header.
- * The key/value pair of the header may be inserted for later use. The key
- * is stored in an array for indexed slot access.
- */
- public Header() {
- super();
- this.props = new ArrayList<String>(20);
- this.keyTable = new TreeMap<String, LinkedList<String>>(
- String.CASE_INSENSITIVE_ORDER);
- }
-
- /**
- * The alternative constructor which sets the input map as its initial
- * keyTable.
- *
- * @param map
- * the initial keyTable as a map
- */
- public Header(Map<String, List<String>> map) {
- this(); // initialize fields
- for (Entry<String, List<String>> next : map.entrySet()) {
- String key = next.getKey();
- List<String> value = next.getValue();
- LinkedList<String> linkedList = new LinkedList<String>();
- for (String element : value) {
- linkedList.add(element);
- props.add(key);
- props.add(element);
- }
- keyTable.put(key, linkedList);
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Object clone() {
- try {
- Header clone = (Header) super.clone();
- clone.props = (ArrayList<String>) props.clone();
- clone.keyTable = new TreeMap<String, LinkedList<String>>(
- String.CASE_INSENSITIVE_ORDER);
- for (Map.Entry<String, LinkedList<String>> next : this.keyTable
- .entrySet()) {
- LinkedList<String> v = (LinkedList<String>) next.getValue()
- .clone();
- clone.keyTable.put(next.getKey(), v);
- }
- return clone;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
- }
- }
-
- /**
- * Add a field with the specified value.
- *
- * @param key
- * @param value
- */
- public void add(String key, String value) {
- if (key == null) {
- throw new NullPointerException();
- }
- if (value == null) {
- /*
- * Given null values, the RI sends a malformed header line like
- * "Accept\r\n". For platform compatibility and HTTP compliance, we
- * print a warning and ignore null values.
- */
- Logger.getAnonymousLogger().warning(
- "Ignoring HTTP header field " + key + " because its value is null.");
- return;
- }
- LinkedList<String> list = keyTable.get(key);
- if (list == null) {
- list = new LinkedList<String>();
- keyTable.put(key, list);
- }
- list.add(value);
- props.add(key);
- props.add(value);
- }
-
- public void removeAll(String key) {
- keyTable.remove(key);
-
- for (int i = 0; i < props.size(); i += 2) {
- if (key.equals(props.get(i))) {
- props.remove(i); // key
- props.remove(i); // value
- }
- }
- }
-
- public void addAll(String key, List<String> headers) {
- for (String header : headers) {
- add(key, header);
- }
- }
-
- public void addIfAbsent(String key, String value) {
- if (get(key) == null) {
- add(key, value);
- }
- }
-
- /**
- * Set a field with the specified value. If the field is not found, it is
- * added. If the field is found, the existing value(s) are overwritten.
- *
- * @param key
- * @param value
- */
- public void set(String key, String value) {
- removeAll(key);
- add(key, value);
- }
-
- /**
- * Provides an unmodifiable map with all String header names mapped to their
- * String values. The map keys are Strings and the values are unmodifiable
- * Lists of Strings.
- *
- * @return an unmodifiable map of the headers
- *
- * @since 1.4
- */
- public Map<String, List<String>> getFieldMap() {
- Map<String, List<String>> result = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); // android-changed
- for (Map.Entry<String, LinkedList<String>> next : keyTable.entrySet()) {
- List<String> v = next.getValue();
- result.put(next.getKey(), Collections.unmodifiableList(v));
- }
- return Collections.unmodifiableMap(result);
- }
-
- /**
- * Returns the element at <code>pos</code>, null if no such element
- * exist.
- *
- * @return java.lang.String the value of the key
- * @param pos
- * int the position to look for
- */
- public String get(int pos) {
- if (pos >= 0 && pos < props.size() / 2) {
- return props.get(pos * 2 + 1);
- }
- return null;
- }
-
- /**
- * Returns the key of this header at <code>pos</code>, null if there are
- * fewer keys in the header
- *
- *
- * @return the key the desired position
- * @param pos
- * the position to look for
- */
- public String getKey(int pos) {
- if (pos >= 0 && pos < props.size() / 2) {
- return props.get(pos * 2);
- }
- return null;
- }
-
- /**
- * Returns the value corresponding to the specified key, or null.
- */
- public String get(String key) {
- LinkedList<String> result = keyTable.get(key);
- if (result == null) {
- return null;
- }
- return result.getLast();
- }
-
- /**
- * Returns the number of keys stored in this header
- *
- * @return the number of keys.
- */
- public int length() {
- return props.size() / 2;
- }
-
- /**
- * Sets the status line in the header request example: GET / HTTP/1.1
- * response example: HTTP/1.1 200 OK
- *
- * @param statusLine
- */
- public void setStatusLine(String statusLine) {
- this.statusLine = statusLine;
- /*
- * we add the status line to the list of headers so that it is
- * accessible from java.net.HttpURLConnection.getResponseCode() which
- * calls
- * org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHeaderField(0)
- * to get it
- */
- props.add(0, null);
- props.add(1, statusLine);
- }
-
- /**
- * Gets the status line in the header request example: GET / HTTP/1.1
- * response example: HTTP/1.1 200 OK
- *
- * @return the status line
- */
- public String getStatusLine() {
- return statusLine;
- }
-}
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..1d2b089 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;
/**
@@ -65,14 +65,14 @@
* TODO: add a hidden method so that Socket.tryAllAddresses can does this for us
*/
Socket socketCandidate = null;
- InetAddress[] addresses = InetAddress.getAllByName(config.hostName);
+ InetAddress[] addresses = InetAddress.getAllByName(config.socketHost);
for (int i = 0; i < addresses.length; i++) {
socketCandidate = (config.proxy != null && config.proxy.type() != Proxy.Type.HTTP)
? new Socket(config.proxy)
: new Socket();
try {
socketCandidate.connect(
- new InetSocketAddress(addresses[i], config.hostPort), connectTimeout);
+ new InetSocketAddress(addresses[i], config.socketPort), connectTimeout);
break;
} catch (IOException e) {
if (i == addresses.length - 1) {
@@ -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 {
@@ -173,19 +155,19 @@
if (sslSocket == null) {
// create the wrapper over connected socket
SSLSocket unverifiedSocket = (SSLSocket) sslSocketFactory.createSocket(socket,
- address.uri.getHost(), address.uri.getEffectivePort(), true /* autoClose */);
+ address.uriHost, address.uriPort, true /* autoClose */);
// tlsTolerant mimics Chrome's behavior
if (tlsTolerant && unverifiedSocket instanceof OpenSSLSocketImpl) {
OpenSSLSocketImpl openSslSocket = (OpenSSLSocketImpl) unverifiedSocket;
openSslSocket.setEnabledCompressionMethods(new String[] { "ZLIB"});
openSslSocket.setUseSessionTickets(true);
- openSslSocket.setHostname(address.hostName);
+ openSslSocket.setHostname(address.socketHost);
// use SSLSocketFactory default enabled protocols
} else {
unverifiedSocket.setEnabledProtocols(new String [] { "SSLv3" });
}
- if (!hostnameVerifier.verify(address.uri.getHost(), unverifiedSocket.getSession())) {
- throw new IOException("Hostname '" + address.uri.getHost() + "' was not verified");
+ if (!hostnameVerifier.verify(address.uriHost, unverifiedSocket.getSession())) {
+ throw new IOException("Hostname '" + address.uriHost + "' was not verified");
}
sslSocket = unverifiedSocket;
}
@@ -238,19 +220,26 @@
&& !socket.isOutputShutdown();
}
+ /**
+ * This address has two parts: the address we connect to directly and the
+ * origin address of the resource. These are the same unless a proxy is
+ * being used.
+ */
public static final class Address {
- private final URI uri;
private final Proxy proxy;
private final boolean requiresTunnel;
- private final String hostName;
- private final int hostPort;
+ private final String uriHost;
+ private final int uriPort;
+ private final String socketHost;
+ private final int socketPort;
public Address(URI uri) {
- this.uri = uri;
this.proxy = null;
this.requiresTunnel = false;
- this.hostName = uri.getHost();
- this.hostPort = uri.getEffectivePort();
+ this.uriHost = uri.getHost();
+ this.uriPort = uri.getEffectivePort();
+ this.socketHost = uriHost;
+ this.socketPort = uriPort;
}
/**
@@ -260,9 +249,10 @@
* the higher-level protocol.
*/
public Address(URI uri, Proxy proxy, boolean requiresTunnel) {
- this.uri = uri;
this.proxy = proxy;
this.requiresTunnel = requiresTunnel;
+ this.uriHost = uri.getHost();
+ this.uriPort = uri.getEffectivePort();
SocketAddress proxyAddress = proxy.address();
if (!(proxyAddress instanceof InetSocketAddress)) {
@@ -270,15 +260,16 @@
proxyAddress.getClass());
}
InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
- this.hostName = proxySocketAddress.getHostName();
- this.hostPort = proxySocketAddress.getPort();
+ this.socketHost = proxySocketAddress.getHostName();
+ this.socketPort = proxySocketAddress.getPort();
}
@Override public boolean equals(Object other) {
if (other instanceof Address) {
Address that = (Address) other;
return Objects.equal(this.proxy, that.proxy)
- && this.uri.equals(that.uri)
+ && this.uriHost.equals(that.uriHost)
+ && this.uriPort == that.uriPort
&& this.requiresTunnel == that.requiresTunnel;
}
return false;
@@ -286,7 +277,8 @@
@Override public int hashCode() {
int result = 17;
- result = 31 * result + uri.hashCode();
+ result = 31 * result + uriHost.hashCode();
+ result = 31 * result + uriPort;
result = 31 * result + (proxy != null ? proxy.hashCode() : 0);
result = 31 * result + (requiresTunnel ? 1 : 0);
return result;
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpHeaders.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpHeaders.java
new file mode 100644
index 0000000..1d02097
--- /dev/null
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpHeaders.java
@@ -0,0 +1,211 @@
+/*
+ * 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.luni.internal.net.www.protocol.http;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+import java.util.logging.Logger;
+
+/**
+ * The HTTP status and header lines of a single HTTP message. This class
+ * maintains the order of the header lines within the HTTP message.
+ */
+public final class HttpHeaders implements Cloneable {
+
+ private static final Comparator<String> HEADER_COMPARATOR = new Comparator<String>() {
+ @Override public int compare(String a, String b) {
+ if (a == b) {
+ return 0;
+ } else if (a == null) {
+ return -1;
+ } else if (b == null) {
+ return 1;
+ } else {
+ return String.CASE_INSENSITIVE_ORDER.compare(a, b);
+ }
+ }
+ };
+
+ private final List<String> alternatingKeysAndValues = new ArrayList<String>(20);
+ private String statusLine;
+
+ public HttpHeaders() {}
+
+ public HttpHeaders(HttpHeaders copyFrom) {
+ statusLine = copyFrom.statusLine;
+ alternatingKeysAndValues.addAll(copyFrom.alternatingKeysAndValues);
+ }
+
+ public void setStatusLine(String statusLine) {
+ this.statusLine = statusLine;
+ }
+
+ public String getStatusLine() {
+ return statusLine;
+ }
+
+ /**
+ * Add a field with the specified value.
+ */
+ public void add(String key, String value) {
+ if (key == null) {
+ throw new IllegalArgumentException("key == null");
+ }
+ if (value == null) {
+ /*
+ * Given null values, the RI sends a malformed header line like
+ * "Accept\r\n". For platform compatibility and HTTP compliance, we
+ * print a warning and ignore null values.
+ */
+ Logger.getAnonymousLogger().warning(
+ "Ignoring HTTP header field " + key + " because its value is null.");
+ return;
+ }
+ alternatingKeysAndValues.add(key);
+ alternatingKeysAndValues.add(value);
+ }
+
+ public void removeAll(String key) {
+ for (int i = 0; i < alternatingKeysAndValues.size(); i += 2) {
+ if (key.equalsIgnoreCase(alternatingKeysAndValues.get(i))) {
+ alternatingKeysAndValues.remove(i); // key
+ alternatingKeysAndValues.remove(i); // value
+ }
+ }
+ }
+
+ public void addAll(String key, List<String> headers) {
+ for (String header : headers) {
+ add(key, header);
+ }
+ }
+
+ public void addIfAbsent(String key, String value) {
+ if (get(key) == null) {
+ add(key, value);
+ }
+ }
+
+ /**
+ * Set a field with the specified value. If the field is not found, it is
+ * added. If the field is found, the existing values are replaced.
+ */
+ public void set(String key, String value) {
+ removeAll(key);
+ add(key, value);
+ }
+
+ /**
+ * Returns the number of header lines.
+ */
+ public int length() {
+ return alternatingKeysAndValues.size() / 2;
+ }
+
+ /**
+ * Returns the key at {@code position} or null if that is out of range.
+ */
+ public String getKey(int index) {
+ int keyIndex = index * 2;
+ if (keyIndex < 0 || keyIndex >= alternatingKeysAndValues.size()) {
+ return null;
+ }
+ return alternatingKeysAndValues.get(keyIndex);
+ }
+
+ /**
+ * Returns the value at {@code index} or null if that is out of range.
+ */
+ public String getValue(int index) {
+ int valueIndex = index * 2 + 1;
+ if (valueIndex < 0 || valueIndex >= alternatingKeysAndValues.size()) {
+ return null;
+ }
+ return alternatingKeysAndValues.get(valueIndex);
+ }
+
+ /**
+ * Returns the last value corresponding to the specified key, or null.
+ */
+ public String get(String key) {
+ for (int i = alternatingKeysAndValues.size() - 2; i >= 0; i -= 2) {
+ if (key.equalsIgnoreCase(alternatingKeysAndValues.get(i))) {
+ return alternatingKeysAndValues.get(i + 1);
+ }
+ }
+ return null;
+ }
+
+ public String toHeaderString() {
+ StringBuilder result = new StringBuilder(256);
+ result.append(statusLine).append("\r\n");
+ for (int i = 0; i < alternatingKeysAndValues.size(); i += 2) {
+ result.append(alternatingKeysAndValues.get(i)).append(": ")
+ .append(alternatingKeysAndValues.get(i + 1)).append("\r\n");
+ }
+ result.append("\r\n");
+ return result.toString();
+ }
+
+ /**
+ * Returns an immutable map containing each field to its list of values. The
+ * status line is mapped to null.
+ */
+ public Map<String, List<String>> toMultimap() {
+ Map<String, List<String>> result = new TreeMap<String, List<String>>(HEADER_COMPARATOR);
+ for (int i = 0; i < alternatingKeysAndValues.size(); i += 2) {
+ String key = alternatingKeysAndValues.get(i);
+ String value = alternatingKeysAndValues.get(i + 1);
+
+ List<String> allValues = new ArrayList<String>();
+ List<String> otherValues = result.get(key);
+ if (otherValues != null) {
+ allValues.addAll(otherValues);
+ }
+ allValues.add(value);
+ result.put(key, Collections.unmodifiableList(allValues));
+ }
+ if (statusLine != null) {
+ result.put(null, Collections.unmodifiableList(Collections.singletonList(statusLine)));
+ }
+ return Collections.unmodifiableMap(result);
+ }
+
+ /**
+ * Creates a header from the given map of fields to values. If present, the
+ * null key's last element will be used to set the status line.
+ */
+ public static HttpHeaders fromMultimap(Map<String, List<String>> map) {
+ HttpHeaders result = new HttpHeaders();
+ for (Entry<String, List<String>> entry : map.entrySet()) {
+ String key = entry.getKey();
+ List<String> values = entry.getValue();
+ if (key != null) {
+ result.addAll(key, values);
+ } else if (!values.isEmpty()) {
+ result.setStatusLine(values.get(values.size() - 1));
+ }
+ }
+ return result;
+ }
+}
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpURLConnectionImpl.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpURLConnectionImpl.java
index dffe6e6..5cd2f15 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpURLConnectionImpl.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpURLConnectionImpl.java
@@ -17,6 +17,7 @@
package org.apache.harmony.luni.internal.net.www.protocol.http;
+import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
@@ -102,6 +103,14 @@
public static final int DEFAULT_CHUNK_LENGTH = 1024;
+ /**
+ * The maximum number of bytes to buffer when sending a header and a request
+ * body. When the header and body can be sent in a single write, the request
+ * completes sooner. In one WiFi benchmark, using a large enough buffer sped
+ * up some uploads by half.
+ */
+ private static final int MAX_REQUEST_BUFFER_LENGTH = 32768;
+
private final int defaultPort;
/**
@@ -115,12 +124,21 @@
private InputStream socketIn;
private OutputStream socketOut;
- private InputStream responseBodyIn;
+ /**
+ * This stream buffers the request header and the request body when their
+ * combined size is less than MAX_REQUEST_BUFFER_LENGTH. By combining them
+ * we can save socket writes, which in turn saves a packet transmission.
+ * This is socketOut if the request size is large or unknown.
+ */
+ private OutputStream requestOut;
+
private AbstractHttpOutputStream requestBodyOut;
+ private InputStream responseBodyIn;
+
private ResponseCache responseCache;
- private CacheResponse cacheResponse;
+ protected CacheResponse cacheResponse;
private CacheRequest cacheRequest;
@@ -142,12 +160,12 @@
// the destination URI
private URI uri;
- private static Header defaultRequestHeader = new Header();
+ private static HttpHeaders defaultRequestHeader = new HttpHeaders();
- private final Header requestHeader;
+ private final HttpHeaders requestHeader;
/** Null until a response is received from the network or the cache */
- private Header responseHeader;
+ private HttpHeaders responseHeader;
private int redirectionCount;
@@ -168,19 +186,13 @@
protected HttpURLConnectionImpl(URL url, int port) {
super(url);
defaultPort = port;
- requestHeader = (Header) defaultRequestHeader.clone();
+ requestHeader = new HttpHeaders(defaultRequestHeader);
- try {
- uri = url.toURI();
- } catch (URISyntaxException e) {
- // do nothing.
- }
- responseCache = AccessController
- .doPrivileged(new PrivilegedAction<ResponseCache>() {
- public ResponseCache run() {
- return ResponseCache.getDefault();
- }
- });
+ responseCache = AccessController.doPrivileged(new PrivilegedAction<ResponseCache>() {
+ public ResponseCache run() {
+ return ResponseCache.getDefault();
+ }
+ });
}
/**
@@ -216,25 +228,20 @@
public void makeConnection() throws IOException {
connected = true;
- if (connection != null) {
+ if (connection != null || responseBodyIn != null) {
return;
}
+ try {
+ uri = url.toURI();
+ } catch (URISyntaxException e) {
+ throw new IOException(e);
+ }
+
if (getFromCache()) {
return;
}
- /*
- * URL.toURI() throws if it has illegal characters. Since we don't mind
- * illegal characters for proxy selection, just create the minimal URI.
- */
- try {
- uri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(),
- null, null);
- } catch (URISyntaxException e1) {
- throw new IOException(e1.getMessage());
- }
-
// try to determine: to use the proxy or not
if (proxy != null) {
// try to make the connection to the proxy
@@ -290,29 +297,46 @@
*/
protected void setUpTransportIO(HttpConnection connection) throws IOException {
socketOut = connection.getOutputStream();
+ requestOut = socketOut;
socketIn = connection.getInputStream();
}
/**
- * Returns true if the input streams are prepared to return data from the
- * cache.
+ * Attempts to load the response headers and body from the response cache.
+ * Returns true if the request was satisfied by the cache.
*/
private boolean getFromCache() throws IOException {
if (!useCaches || responseCache == null || hasTriedCache) {
- return (hasTriedCache && socketIn != null);
+ return false;
}
hasTriedCache = true;
- cacheResponse = responseCache.get(uri, method, requestHeader.getFieldMap());
- if (cacheResponse == null) {
- return socketIn != null; // TODO: if this is non-null, why are we calling getFromCache?
+ CacheResponse candidate = responseCache.get(uri, method, requestHeader.toMultimap());
+ if (!acceptCacheResponse(candidate)) {
+ return false;
}
- Map<String, List<String>> headersMap = cacheResponse.getHeaders();
- if (headersMap != null) {
- responseHeader = new Header(headersMap);
+ Map<String, List<String>> headersMap = candidate.getHeaders();
+ if (headersMap == null) {
+ return false;
}
- socketIn = responseBodyIn = cacheResponse.getBody();
- return socketIn != null;
+ InputStream cacheBodyIn = candidate.getBody();
+ if (cacheBodyIn == null) {
+ return false;
+ }
+
+ cacheResponse = candidate;
+ responseHeader = HttpHeaders.fromMultimap(headersMap);
+ parseStatusLine();
+ responseBodyIn = cacheBodyIn;
+ return true;
+ }
+
+ /**
+ * Returns true if {@code cacheResponse} is sufficient to forgo a network
+ * request. HTTPS connections require secure cache responses.
+ */
+ protected boolean acceptCacheResponse(CacheResponse cacheResponse) {
+ return cacheResponse != null;
}
private void maybeCache() throws IOException {
@@ -328,7 +352,7 @@
return;
}
// Offer this request to the cache.
- cacheRequest = responseCache.put(uri, this);
+ cacheRequest = responseCache.put(uri, getConnectionForCaching());
}
/**
@@ -370,12 +394,12 @@
}
/*
- * Clear "socketIn" and "socketOut" to ensure that no further I/O
- * attempts from this instance make their way to the underlying
- * connection (which may get recycled).
+ * Ensure that no further I/O attempts from this instance make their way
+ * to the underlying connection (which may get recycled).
*/
- socketIn = null;
socketOut = null;
+ socketIn = null;
+ requestOut = null;
}
/**
@@ -398,6 +422,9 @@
responseCode = -1;
responseMessage = null;
cacheRequest = null;
+ uri = null;
+ cacheResponse = null;
+ hasTriedCache = false;
} finally {
intermediateResponse = false;
}
@@ -421,27 +448,16 @@
}
/**
- * Returns the value of the field at position <code>pos<code>.
- * Returns <code>null</code> if there is fewer than <code>pos</code> fields
- * in the response header.
- *
- * @return java.lang.String The value of the field
- * @param pos int the position of the field from the top
- *
- * @see #getHeaderField(String)
- * @see #getHeaderFieldKey
+ * Returns the value of the field at {@code position}. Returns null if there
+ * are fewer than {@code position} headers.
*/
@Override
- public String getHeaderField(int pos) {
+ public String getHeaderField(int position) {
try {
getInputStream();
- } catch (IOException e) {
- // ignore
+ } catch (IOException ignored) {
}
- if (null == responseHeader) {
- return null;
- }
- return responseHeader.get(pos);
+ return responseHeader != null ? responseHeader.getValue(position) : null;
}
/**
@@ -462,26 +478,21 @@
public String getHeaderField(String key) {
try {
getInputStream();
- } catch (IOException e) {
- // ignore
+ } catch (IOException ignored) {
}
- if (null == responseHeader) {
+ if (responseHeader == null) {
return null;
}
- return responseHeader.get(key);
+ return key == null ? responseHeader.getStatusLine() : responseHeader.get(key);
}
@Override
- public String getHeaderFieldKey(int pos) {
+ public String getHeaderFieldKey(int position) {
try {
getInputStream();
- } catch (IOException e) {
- // ignore
+ } catch (IOException ignored) {
}
- if (null == responseHeader) {
- return null;
- }
- return responseHeader.getKey(pos);
+ return responseHeader != null ? responseHeader.getKey(position) : null;
}
@Override
@@ -490,7 +501,7 @@
retrieveResponse();
} catch (IOException ignored) {
}
- return responseHeader != null ? responseHeader.getFieldMap() : null;
+ return responseHeader != null ? responseHeader.toMultimap() : null;
}
@Override
@@ -498,7 +509,7 @@
if (connected) {
throw new IllegalStateException("Cannot access request header fields after connection is set");
}
- return requestHeader.getFieldMap();
+ return requestHeader.toMultimap();
}
@Override
@@ -528,7 +539,7 @@
return responseBodyIn;
}
- private InputStream initContentStream() throws IOException {
+ private void initContentStream() throws IOException {
InputStream transferStream = getTransferStream();
if (transparentGzip && "gzip".equalsIgnoreCase(responseHeader.get("Content-Encoding"))) {
/*
@@ -540,7 +551,6 @@
} else {
responseBodyIn = transferStream;
}
- return responseBodyIn;
}
private InputStream getTransferStream() throws IOException {
@@ -623,12 +633,13 @@
}
if (fixedContentLength != -1) {
- writeRequestHeaders(socketOut);
- requestBodyOut = new FixedLengthOutputStream(socketOut, fixedContentLength);
+ writeRequestHeaders(fixedContentLength);
+ requestBodyOut = new FixedLengthOutputStream(requestOut, fixedContentLength);
} else if (sendChunked) {
- writeRequestHeaders(socketOut);
- requestBodyOut = new ChunkedOutputStream(socketOut, chunkLength);
+ writeRequestHeaders(-1);
+ requestBodyOut = new ChunkedOutputStream(requestOut, chunkLength);
} else if (contentLength != -1) {
+ writeRequestHeaders(contentLength);
requestBodyOut = new RetryableOutputStream(contentLength);
} else {
requestBodyOut = new RetryableOutputStream();
@@ -644,7 +655,7 @@
@Override
public String getRequestProperty(String field) {
- if (null == field) {
+ if (field == null) {
return null;
}
return requestHeader.get(field);
@@ -684,12 +695,11 @@
private void readResponseHeaders() throws IOException {
do {
- responseCode = -1;
- responseMessage = null;
- responseHeader = new Header();
+ responseHeader = new HttpHeaders();
responseHeader.setStatusLine(readLine(socketIn).trim());
readHeaders();
- } while (parseResponseCode() == HTTP_CONTINUE);
+ parseStatusLine();
+ } while (responseCode == HTTP_CONTINUE);
}
/**
@@ -727,16 +737,20 @@
return responseCode;
}
- private int parseResponseCode() {
- // Response Code Sample : "HTTP/1.0 200 OK"
+ private void parseStatusLine() {
+ httpVersion = 1;
+ responseCode = -1;
+ responseMessage = null;
+
+ // Status line sample: "HTTP/1.0 200 OK"
String response = responseHeader.getStatusLine();
if (response == null || !response.startsWith("HTTP/")) {
- return -1;
+ return;
}
response = response.trim();
int mark = response.indexOf(" ") + 1;
if (mark == 0) {
- return -1;
+ return;
}
if (response.charAt(mark - 2) != '1') {
httpVersion = 0;
@@ -749,7 +763,6 @@
if (last + 1 <= response.length()) {
responseMessage = response.substring(last + 1);
}
- return responseCode;
}
void readHeaders() throws IOException {
@@ -767,7 +780,7 @@
CookieHandler cookieHandler = CookieHandler.getDefault();
if (cookieHandler != null) {
- cookieHandler.put(uri, responseHeader.getFieldMap());
+ cookieHandler.put(uri, responseHeader.toMultimap());
}
}
@@ -782,21 +795,19 @@
* <strong>after</strong> the output stream has been written to and closed.
* This ensures that the {@code Content-Length} header receives the proper
* value.
+ *
+ * @param contentLength the number of bytes in the request body, or -1 if
+ * the request body length is unknown.
*/
- private void writeRequestHeaders(OutputStream out) throws IOException {
- Header header = prepareRequestHeaders();
+ private void writeRequestHeaders(int contentLength) throws IOException {
+ byte[] headerBytes = prepareRequestHeaders().toHeaderString().getBytes(Charsets.ISO_8859_1);
- StringBuilder result = new StringBuilder(256);
- result.append(header.getStatusLine()).append("\r\n");
- for (int i = 0; i < header.length(); i++) {
- String key = header.getKey(i);
- String value = header.get(i);
- if (key != null) {
- result.append(key).append(": ").append(value).append("\r\n");
- }
+ if (contentLength != -1
+ && headerBytes.length + contentLength <= MAX_REQUEST_BUFFER_LENGTH) {
+ requestOut = new BufferedOutputStream(socketOut, headerBytes.length + contentLength);
}
- result.append("\r\n");
- out.write(result.toString().getBytes(Charsets.ISO_8859_1));
+
+ requestOut.write(headerBytes);
sentRequestHeaders = true;
}
@@ -807,14 +818,14 @@
* <p>This client doesn't specify a default {@code Accept} header because it
* doesn't know what content types the application is interested in.
*/
- private Header prepareRequestHeaders() throws IOException {
+ private HttpHeaders prepareRequestHeaders() throws IOException {
/*
* If we're establishing an HTTPS tunnel with CONNECT (RFC 2817 5.2),
* send only the minimum set of headers. This avoids sending potentially
* sensitive data like HTTP cookies to the proxy unencrypted.
*/
if (method == CONNECT) {
- Header proxyHeader = new Header();
+ HttpHeaders proxyHeader = new HttpHeaders();
proxyHeader.setStatusLine(getStatusLine());
// always set Host and User-Agent
@@ -877,7 +888,7 @@
CookieHandler cookieHandler = CookieHandler.getDefault();
if (cookieHandler != null) {
Map<String, List<String>> allCookieHeaders
- = cookieHandler.get(uri, requestHeader.getFieldMap());
+ = cookieHandler.get(uri, requestHeader.toMultimap());
for (Map.Entry<String, List<String>> entry : allCookieHeaders.entrySet()) {
String key = entry.getKey();
if ("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key)) {
@@ -1004,6 +1015,15 @@
}
/**
+ * Returns this connection in a form suitable for use by the response cache.
+ * If this returns an HTTPS connection, only secure cache responses will be
+ * honored.
+ */
+ protected HttpURLConnection getConnectionForCaching() {
+ return this;
+ }
+
+ /**
* Aggressively tries to get the final HTTP response, potentially making
* many HTTP requests in the process in order to cope with redirects and
* authentication.
@@ -1017,34 +1037,10 @@
while (true) {
makeConnection();
- // if we can get a response from the cache, we're done
- if (cacheResponse != null) {
- // TODO: how does this interact with redirects? Consider processing the headers so
- // that a redirect is never returned.
- return;
+ if (cacheResponse == null) {
+ getFromNetwork();
}
- if (!sentRequestHeaders) {
- writeRequestHeaders(socketOut);
- }
-
- if (requestBodyOut != null) {
- requestBodyOut.close();
- if (requestBodyOut instanceof RetryableOutputStream) {
- ((RetryableOutputStream) requestBodyOut).writeToSocket(socketOut);
- }
- }
-
- socketOut.flush();
-
- readResponseHeaders();
-
- if (hasResponseBody()) {
- maybeCache(); // reentrant. this calls into user code which may call back into this!
- }
-
- initContentStream();
-
Retry retry = processResponseHeaders();
if (retry == Retry.NONE) {
@@ -1071,6 +1067,33 @@
}
}
+ private void getFromNetwork() throws IOException {
+ if (!sentRequestHeaders) {
+ int contentLength = requestBodyOut instanceof RetryableOutputStream
+ ? ((RetryableOutputStream) requestBodyOut).contentLength()
+ : -1;
+ writeRequestHeaders(contentLength);
+ }
+
+ if (requestBodyOut != null) {
+ requestBodyOut.close();
+ if (requestBodyOut instanceof RetryableOutputStream) {
+ ((RetryableOutputStream) requestBodyOut).writeToSocket(requestOut);
+ }
+ }
+
+ requestOut.flush();
+ requestOut = socketOut;
+
+ readResponseHeaders();
+
+ if (hasResponseBody()) {
+ maybeCache(); // reentrant. this calls into user code which may call back into this!
+ }
+
+ initContentStream();
+ }
+
enum Retry {
NONE,
SAME_CONNECTION,
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/https/HttpsURLConnectionImpl.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java
index c7210f5..95c985f 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java
@@ -19,8 +19,11 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.Proxy;
+import java.net.SecureCacheResponse;
import java.net.URL;
import java.security.Permission;
import java.security.Principal;
@@ -62,30 +65,52 @@
@Override
public String getCipherSuite() {
+ SecureCacheResponse cacheResponse = httpsEngine.getCacheResponse();
+ if (cacheResponse != null) {
+ return cacheResponse.getCipherSuite();
+ }
checkConnected();
return sslSocket.getSession().getCipherSuite();
}
@Override
public Certificate[] getLocalCertificates() {
+ SecureCacheResponse cacheResponse = httpsEngine.getCacheResponse();
+ if (cacheResponse != null) {
+ List<Certificate> result = cacheResponse.getLocalCertificateChain();
+ return result != null ? result.toArray(new Certificate[result.size()]) : null;
+ }
checkConnected();
return sslSocket.getSession().getLocalCertificates();
}
@Override
public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
+ SecureCacheResponse cacheResponse = httpsEngine.getCacheResponse();
+ if (cacheResponse != null) {
+ List<Certificate> result = cacheResponse.getServerCertificateChain();
+ return result != null ? result.toArray(new Certificate[result.size()]) : null;
+ }
checkConnected();
return sslSocket.getSession().getPeerCertificates();
}
@Override
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ SecureCacheResponse cacheResponse = httpsEngine.getCacheResponse();
+ if (cacheResponse != null) {
+ return cacheResponse.getPeerPrincipal();
+ }
checkConnected();
return sslSocket.getSession().getPeerPrincipal();
}
@Override
public Principal getLocalPrincipal() {
+ SecureCacheResponse cacheResponse = httpsEngine.getCacheResponse();
+ if (cacheResponse != null) {
+ return cacheResponse.getLocalPrincipal();
+ }
checkConnected();
return sslSocket.getSession().getLocalPrincipal();
}
@@ -380,6 +405,11 @@
private void makeSslConnection(boolean tlsTolerant) throws IOException {
super.makeConnection();
+ // if we got a response from the cache, we're done
+ if (cacheResponse != null) {
+ return;
+ }
+
// make SSL Tunnel
if (requiresTunnel()) {
String originalMethod = method;
@@ -400,6 +430,10 @@
setUpTransportIO(connection);
}
+ public SecureCacheResponse getCacheResponse() {
+ return (SecureCacheResponse) cacheResponse;
+ }
+
@Override protected void setUpTransportIO(HttpConnection connection) throws IOException {
if (!requiresTunnel() && sslSocket == null) {
return; // don't initialize streams that won't be used
@@ -411,6 +445,14 @@
return usingProxy();
}
+ @Override protected HttpURLConnection getConnectionForCaching() {
+ return HttpsURLConnectionImpl.this;
+ }
+
+ @Override protected boolean acceptCacheResponse(CacheResponse cacheResponse) {
+ return cacheResponse instanceof SecureCacheResponse;
+ }
+
@Override protected String requestString() {
if (!usingProxy()) {
return super.requestString();
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/internal/util/ZoneInfo.java b/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfo.java
index c4ba36a..3a70767 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfo.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfo.java
@@ -38,17 +38,6 @@
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335,
};
- private static String nullName(byte[] bytes, int begin) {
- if (begin < 0) {
- return null;
- }
- int end = begin;
- while (end < bytes.length && bytes[end] != 0) {
- ++end;
- }
- return new String(bytes, begin, end - begin, Charsets.US_ASCII);
- }
-
private int mRawOffset;
private final int[] mTransitions;
@@ -56,50 +45,24 @@
private final byte[] mTypes;
private final byte[] mIsDsts;
private final boolean mUseDst;
- private final String mDaylightName;
- private final String mStandardName;
- ZoneInfo(String name, int[] transitions, byte[] type, int[] gmtoff, byte[] isdst,
- byte[] abbreviationIndexes, byte[] abbreviationList) {
+ ZoneInfo(String name, int[] transitions, byte[] type, int[] gmtoff, byte[] isdst) {
mTransitions = transitions;
mTypes = type;
mGmtOffs = gmtoff;
mIsDsts = isdst;
setID(name);
- // Find the latest GMT and non-GMT offsets for their abbreviations
-
- int lastdst;
- for (lastdst = mTransitions.length - 1; lastdst >= 0; lastdst--) {
- if (mIsDsts[mTypes[lastdst] & 0xFF] != 0) {
- break;
- }
- }
-
+ // Use the latest non-daylight offset (if any) as the raw offset.
int laststd;
for (laststd = mTransitions.length - 1; laststd >= 0; laststd--) {
if (mIsDsts[mTypes[laststd] & 0xFF] == 0) {
break;
}
}
-
- if (lastdst >= 0) {
- mDaylightName = nullName(abbreviationList, abbreviationIndexes[mTypes[lastdst] & 0xFF]);
- } else {
- mDaylightName = null;
- }
- if (laststd >= 0) {
- mStandardName = nullName(abbreviationList, abbreviationIndexes[mTypes[laststd] & 0xFF]);
- } else {
- mStandardName = null;
- }
-
- // Use the latest non-DST offset if any as the raw offset
-
if (laststd < 0) {
laststd = 0;
}
-
if (laststd >= mTypes.length) {
mRawOffset = mGmtOffs[0];
} else {
@@ -231,20 +194,17 @@
return false;
}
ZoneInfo other = (ZoneInfo) obj;
- return Objects.equal(mDaylightName, other.mDaylightName)
- && Objects.equal(mStandardName, other.mStandardName)
- && hasSameRules(other);
+ return getID().equals(other.getID()) && hasSameRules(other);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((mDaylightName == null) ? 0 : mDaylightName.hashCode());
+ result = prime * result + getID().hashCode();
result = prime * result + Arrays.hashCode(mGmtOffs);
result = prime * result + Arrays.hashCode(mIsDsts);
result = prime * result + mRawOffset;
- result = prime * result + ((mStandardName == null) ? 0 : mStandardName.hashCode());
result = prime * result + Arrays.hashCode(mTransitions);
result = prime * result + Arrays.hashCode(mTypes);
result = prime * result + (mUseDst ? 1231 : 1237);
@@ -253,7 +213,7 @@
@Override
public String toString() {
- return getClass().getName() +
- "[\"" + mStandardName + "\",mRawOffset=" + mRawOffset + ",mUseDst=" + mUseDst + "]";
+ return getClass().getName() + "[" + getID() + ",mRawOffset=" + mRawOffset +
+ ",mUseDst=" + mUseDst + "]";
}
}
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java b/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java
index c44044c..264a9a0 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java
@@ -20,13 +20,15 @@
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-import java.nio.channels.FileChannel;
+import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
+import libcore.io.BufferIterator;
import libcore.io.IoUtils;
+import libcore.io.MemoryMappedFile;
/**
* A class used to initialize the time zone database. This implementation uses the
@@ -72,7 +74,7 @@
readIndex();
}
- private static ByteBuffer mappedData = mapData();
+ private static final MemoryMappedFile allZoneData = mapData();
private ZoneInfoDB() {}
@@ -81,16 +83,11 @@
* present or is unreadable, we assume a version of "2007h".
*/
private static String readVersion() {
- RandomAccessFile versionFile = null;
try {
- versionFile = new RandomAccessFile(ZONE_DIRECTORY_NAME + "zoneinfo.version", "r");
- byte[] buf = new byte[(int) versionFile.length()];
- versionFile.readFully(buf);
- return new String(buf, 0, buf.length, Charsets.ISO_8859_1).trim();
+ byte[] bytes = IoUtils.readFileAsByteArray(ZONE_DIRECTORY_NAME + "zoneinfo.version");
+ return new String(bytes, 0, bytes.length, Charsets.ISO_8859_1).trim();
} catch (IOException ex) {
throw new RuntimeException(ex);
- } finally {
- IoUtils.closeQuietly(versionFile);
}
}
@@ -105,76 +102,80 @@
* All this code assumes strings are US-ASCII.
*/
private static void readIndex() {
- RandomAccessFile indexFile = null;
+ RandomAccessFile file = null;
+ MemoryMappedFile mappedFile = null;
try {
- indexFile = new RandomAccessFile(INDEX_FILE_NAME, "r");
-
- // The database reserves 40 bytes for each id.
- final int SIZEOF_TZNAME = 40;
- // The database uses 32-bit (4 byte) integers.
- final int SIZEOF_TZINT = 4;
-
- byte[] idBytes = new byte[SIZEOF_TZNAME];
-
- int numEntries = (int) (indexFile.length() / (SIZEOF_TZNAME + 3*SIZEOF_TZINT));
-
- char[] idChars = new char[numEntries * SIZEOF_TZNAME];
- int[] idEnd = new int[numEntries];
- int idOffset = 0;
-
- byteOffsets = new int[numEntries];
- rawUtcOffsets = new int[numEntries];
-
- for (int i = 0; i < numEntries; i++) {
- indexFile.readFully(idBytes);
- byteOffsets[i] = indexFile.readInt();
- int length = indexFile.readInt();
- if (length < 44) {
- throw new AssertionError("length in index file < sizeof(tzhead)");
- }
- rawUtcOffsets[i] = indexFile.readInt();
-
- // Don't include null chars in the String
- int len = idBytes.length;
- for (int j = 0; j < len; j++) {
- if (idBytes[j] == 0) {
- break;
- }
- idChars[idOffset++] = (char) (idBytes[j] & 0xFF);
- }
-
- idEnd[i] = idOffset;
- }
-
- // We create one string containing all the ids, and then break that into substrings.
- // This way, all ids share a single char[] on the heap.
- String allIds = new String(idChars, 0, idOffset);
- ids = new String[numEntries];
- for (int i = 0; i < numEntries; i++) {
- ids[i] = allIds.substring(i == 0 ? 0 : idEnd[i - 1], idEnd[i]);
- }
+ file = new RandomAccessFile(INDEX_FILE_NAME, "r");
+ mappedFile = MemoryMappedFile.mmap(file.getFD(), MapMode.READ_ONLY, 0, file.length());
+ readIndex(mappedFile);
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
- IoUtils.closeQuietly(indexFile);
+ IoUtils.closeQuietly(mappedFile);
+ IoUtils.closeQuietly(file);
+ }
+ }
+
+ private static void readIndex(MemoryMappedFile mappedFile) throws IOException {
+ BufferIterator it = mappedFile.bigEndianIterator();
+
+ // The database reserves 40 bytes for each id.
+ final int SIZEOF_TZNAME = 40;
+ // The database uses 32-bit (4 byte) integers.
+ final int SIZEOF_TZINT = 4;
+
+ byte[] idBytes = new byte[SIZEOF_TZNAME];
+ int numEntries = (int) (mappedFile.size() / (SIZEOF_TZNAME + 3*SIZEOF_TZINT));
+
+ char[] idChars = new char[numEntries * SIZEOF_TZNAME];
+ int[] idEnd = new int[numEntries];
+ int idOffset = 0;
+
+ byteOffsets = new int[numEntries];
+ rawUtcOffsets = new int[numEntries];
+
+ for (int i = 0; i < numEntries; i++) {
+ it.readByteArray(idBytes, 0, idBytes.length);
+ byteOffsets[i] = it.readInt();
+ int length = it.readInt();
+ if (length < 44) {
+ throw new AssertionError("length in index file < sizeof(tzhead)");
+ }
+ rawUtcOffsets[i] = it.readInt();
+
+ // Don't include null chars in the String
+ int len = idBytes.length;
+ for (int j = 0; j < len; j++) {
+ if (idBytes[j] == 0) {
+ break;
+ }
+ idChars[idOffset++] = (char) (idBytes[j] & 0xFF);
+ }
+
+ idEnd[i] = idOffset;
+ }
+
+ // We create one string containing all the ids, and then break that into substrings.
+ // This way, all ids share a single char[] on the heap.
+ String allIds = new String(idChars, 0, idOffset);
+ ids = new String[numEntries];
+ for (int i = 0; i < numEntries; i++) {
+ ids[i] = allIds.substring(i == 0 ? 0 : idEnd[i - 1], idEnd[i]);
}
}
/**
* Rather than open, read, and close the big data file each time we look up a time zone,
- * we map the big data file during startup, and then just use the ByteBuffer.
+ * we map the big data file during startup, and then just use the MemoryMappedFile.
*
* At the moment, this "big" data file is about 160 KiB. At some point, that will be small
* enough that we'll just keep the byte[] in memory.
*/
- private static ByteBuffer mapData() {
+ private static MemoryMappedFile mapData() {
RandomAccessFile file = null;
try {
file = new RandomAccessFile(ZONE_FILE_NAME, "r");
- FileChannel channel = file.getChannel();
- ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
- buffer.order(ByteOrder.BIG_ENDIAN);
- return buffer;
+ return MemoryMappedFile.mmap(file.getFD(), MapMode.READ_ONLY, 0, file.length());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
@@ -188,49 +189,40 @@
if (index < 0) {
return null;
}
- int start = byteOffsets[index];
- // We duplicate the ByteBuffer to allow unsynchronized access to this shared data,
- // despite Buffer's implicit position.
- ByteBuffer data = mappedData.duplicate();
- data.position(start);
+ BufferIterator data = allZoneData.bigEndianIterator();
+ data.skip(byteOffsets[index]);
// Variable names beginning tzh_ correspond to those in "tzfile.h".
// Check tzh_magic.
- if (data.getInt() != 0x545a6966) { // "TZif"
+ if (data.readInt() != 0x545a6966) { // "TZif"
return null;
}
// Skip the uninteresting part of the header.
- data.position(start + 32);
+ data.skip(28);
// Read the sizes of the arrays we're about to read.
- int tzh_timecnt = data.getInt();
- int tzh_typecnt = data.getInt();
- int tzh_charcnt = data.getInt();
+ int tzh_timecnt = data.readInt();
+ int tzh_typecnt = data.readInt();
+
+ data.skip(4); // Skip tzh_charcnt.
int[] transitions = new int[tzh_timecnt];
- for (int i = 0; i < tzh_timecnt; ++i) {
- transitions[i] = data.getInt();
- }
+ data.readIntArray(transitions, 0, transitions.length);
byte[] type = new byte[tzh_timecnt];
- data.get(type);
+ data.readByteArray(type, 0, type.length);
int[] gmtOffsets = new int[tzh_typecnt];
byte[] isDsts = new byte[tzh_typecnt];
- byte[] abbreviationIndexes = new byte[tzh_typecnt];
for (int i = 0; i < tzh_typecnt; ++i) {
- gmtOffsets[i] = data.getInt();
- isDsts[i] = data.get();
- abbreviationIndexes[i] = data.get();
+ gmtOffsets[i] = data.readInt();
+ isDsts[i] = data.readByte();
+ data.skip(1); // Skip abbreviation index.
}
- byte[] abbreviationList = new byte[tzh_charcnt];
- data.get(abbreviationList);
-
- return new ZoneInfo(id, transitions, type, gmtOffsets, isDsts,
- abbreviationIndexes, abbreviationList);
+ return new ZoneInfo(id, transitions, type, gmtOffsets, isDsts);
}
public static String[] getAvailableIDs() {
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 a210a0b..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;
@@ -28,7 +29,6 @@
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
-import org.apache.harmony.luni.platform.INetworkSystem;
import org.apache.harmony.luni.platform.Platform;
/**
@@ -43,19 +43,11 @@
private static final int SO_BROADCAST = 32;
- static final int TCP_NODELAY = 4;
-
final static int IP_MULTICAST_TTL = 17;
- private byte[] ipaddress = { 0, 0, 0, 0 };
-
- private INetworkSystem netImpl = Platform.getNetworkSystem();
-
private volatile boolean isNativeConnected;
- private boolean streaming = true;
-
- private boolean shutdownInput;
+ private final CloseGuard guard = CloseGuard.get();
/**
* used to keep address to which the socket was connected to at the native
@@ -69,6 +61,9 @@
super();
this.fd = fd;
this.localPort = localPort;
+ if (fd.valid()) {
+ guard.open("close");
+ }
}
public PlainDatagramSocketImpl() {
@@ -78,40 +73,38 @@
@Override
public void bind(int port, InetAddress addr) throws SocketException {
- netImpl.bind(fd, addr, port);
- if (0 != port) {
+ Platform.NETWORK.bind(fd, addr, port);
+ if (port != 0) {
localPort = port;
} else {
- localPort = netImpl.getSocketLocalPort(fd);
+ localPort = Platform.NETWORK.getSocketLocalPort(fd);
}
try {
- // Ignore failures
setOption(SO_BROADCAST, Boolean.TRUE);
- } catch (IOException e) {
+ } catch (IOException ignored) {
}
}
@Override
- public void close() {
- synchronized (fd) {
- if (fd.valid()) {
- try {
- netImpl.close(fd);
- } catch (IOException e) {
- }
- fd = new FileDescriptor();
- }
+ public synchronized void close() {
+ guard.close();
+ try {
+ Platform.NETWORK.close(fd);
+ } catch (IOException ignored) {
}
}
@Override
public void create() throws SocketException {
- netImpl.socket(fd, false);
+ Platform.NETWORK.socket(fd, false);
}
@Override protected void finalize() throws Throwable {
try {
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
close();
} finally {
super.finalize();
@@ -119,12 +112,12 @@
}
public Object getOption(int optID) throws SocketException {
- return netImpl.getSocketOption(fd, optID);
+ return Platform.NETWORK.getSocketOption(fd, optID);
}
@Override
public int getTimeToLive() throws IOException {
- return ((Integer) getOption(IP_MULTICAST_TTL)).intValue();
+ return (Integer) getOption(IP_MULTICAST_TTL);
}
@Override
@@ -164,12 +157,12 @@
byte[] bytes = new byte[0];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
int result = peekData(packet);
- netImpl.setInetAddress(sender, packet.getAddress().getAddress());
+ Platform.NETWORK.setInetAddress(sender, packet.getAddress().getAddress());
return result;
}
private void doRecv(DatagramPacket pack, boolean peek) throws IOException {
- netImpl.recv(fd, pack, pack.getData(), pack.getOffset(), pack.getLength(), peek,
+ Platform.NETWORK.recv(fd, pack, pack.getData(), pack.getOffset(), pack.getLength(), peek,
isNativeConnected);
if (isNativeConnected) {
updatePacketRecvAddress(pack);
@@ -191,11 +184,12 @@
public void send(DatagramPacket packet) throws IOException {
int port = isNativeConnected ? 0 : packet.getPort();
InetAddress address = isNativeConnected ? null : packet.getAddress();
- netImpl.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 {
- netImpl.setSocketOption(fd, optID, val);
+ Platform.NETWORK.setSocketOption(fd, optID, val);
}
@Override
@@ -210,7 +204,7 @@
@Override
public void connect(InetAddress inetAddr, int port) throws SocketException {
- netImpl.connect(fd, inetAddr, port, 0);
+ Platform.NETWORK.connect(fd, inetAddr, port, 0);
// if we get here then we are connected at the native level
try {
@@ -227,10 +221,8 @@
@Override
public void disconnect() {
try {
- netImpl.disconnectDatagram(fd);
- } catch (Exception e) {
- // there is currently no way to return an error so just eat any
- // exception
+ Platform.NETWORK.disconnectDatagram(fd);
+ } catch (Exception ignored) {
}
connectedPort = -1;
connectedAddress = null;
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 2a36fee..18f6d6d 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;
@@ -31,9 +32,10 @@
import java.net.SocketImpl;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
+import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedAction;
-import org.apache.harmony.luni.platform.INetworkSystem;
+import org.apache.harmony.luni.platform.OSMemory;
import org.apache.harmony.luni.platform.Platform;
/**
@@ -49,16 +51,19 @@
private static Field fdField;
- protected INetworkSystem netImpl = Platform.getNetworkSystem();
-
private boolean streaming = true;
private boolean shutdownInput;
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) {
@@ -76,6 +81,9 @@
this.localport = localport;
this.address = addr;
this.port = port;
+ if (fd.valid()) {
+ guard.open("close");
+ }
}
@Override
@@ -89,7 +97,7 @@
try {
if (newImpl instanceof PlainSocketImpl) {
PlainSocketImpl newPlainSocketImpl = (PlainSocketImpl) newImpl;
- netImpl.accept(fd, newImpl, newPlainSocketImpl.getFileDescriptor());
+ Platform.NETWORK.accept(fd, newImpl, newPlainSocketImpl.getFileDescriptor());
} else {
// if newImpl is not an instance of PlainSocketImpl, use
// reflection to get/set protected fields.
@@ -97,7 +105,7 @@
fdField = getSocketImplField("fd");
}
FileDescriptor newFd = (FileDescriptor) fdField.get(newImpl);
- netImpl.accept(fd, newImpl, newFd);
+ Platform.NETWORK.accept(fd, newImpl, newFd);
}
} catch (IllegalAccessException e) {
// empty
@@ -149,28 +157,24 @@
if (shutdownInput) {
return 0;
}
- return Platform.getFileSystem().ioctlAvailable(fd);
+ return Platform.FILE_SYSTEM.ioctlAvailable(fd);
}
@Override
protected void bind(InetAddress address, int port) throws IOException {
- netImpl.bind(fd, address, port);
+ Platform.NETWORK.bind(fd, address, port);
this.address = address;
if (port != 0) {
this.localport = port;
} else {
- this.localport = netImpl.getSocketLocalPort(fd);
+ this.localport = Platform.NETWORK.getSocketLocalPort(fd);
}
}
@Override
- protected void close() throws IOException {
- synchronized (fd) {
- if (fd.valid()) {
- netImpl.close(fd);
- fd = new FileDescriptor();
- }
- }
+ protected synchronized void close() throws IOException {
+ guard.close();
+ Platform.NETWORK.close(fd);
}
@Override
@@ -201,7 +205,7 @@
if (streaming && usingSocks()) {
socksConnect(anAddr, aPort, 0);
} else {
- netImpl.connect(fd, normalAddr, aPort, timeout);
+ Platform.NETWORK.connect(fd, normalAddr, aPort, timeout);
}
} catch (ConnectException e) {
throw new ConnectException(anAddr + ":" + aPort + " - " + e.getMessage());
@@ -213,11 +217,14 @@
@Override
protected void create(boolean streaming) throws IOException {
this.streaming = streaming;
- netImpl.socket(fd, streaming);
+ Platform.NETWORK.socket(fd, streaming);
}
@Override protected void finalize() throws Throwable {
try {
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
close();
} finally {
super.finalize();
@@ -232,7 +239,7 @@
@Override
public Object getOption(int optID) throws SocketException {
- return netImpl.getSocketOption(fd, optID);
+ return Platform.NETWORK.getSocketOption(fd, optID);
}
@Override
@@ -248,12 +255,12 @@
// server during the bind.
return;
}
- netImpl.listen(fd, backlog);
+ Platform.NETWORK.listen(fd, backlog);
}
@Override
public void setOption(int optID, Object val) throws SocketException {
- netImpl.setSocketOption(fd, optID, val);
+ Platform.NETWORK.setSocketOption(fd, optID, val);
}
/**
@@ -290,7 +297,7 @@
private void socksConnect(InetAddress applicationServerAddress,
int applicationServerPort, int timeout) throws IOException {
try {
- netImpl.connect(fd, socksGetServerAddress(), socksGetServerPort(), timeout);
+ Platform.NETWORK.connect(fd, socksGetServerAddress(), socksGetServerPort(), timeout);
} catch (Exception e) {
throw new SocketException("SOCKS connection failed: " + e);
}
@@ -333,7 +340,7 @@
@Override
protected void shutdownInput() throws IOException {
shutdownInput = true;
- netImpl.shutdownInput(fd);
+ Platform.NETWORK.shutdownInput(fd);
}
/**
@@ -341,7 +348,7 @@
*/
@Override
protected void shutdownOutput() throws IOException {
- netImpl.shutdownOutput(fd);
+ Platform.NETWORK.shutdownOutput(fd);
}
/**
@@ -349,7 +356,7 @@
*/
private void socksBind() throws IOException {
try {
- netImpl.connect(fd, socksGetServerAddress(), socksGetServerPort(), 0);
+ Platform.NETWORK.connect(fd, socksGetServerAddress(), socksGetServerPort(), 0);
} catch (Exception e) {
throw new IOException("Unable to connect to SOCKS server: " + e);
}
@@ -366,8 +373,7 @@
Socks4Message reply = socksReadReply();
if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
- throw new IOException(reply.getErrorString(reply
- .getCommandOrResult()));
+ throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
}
// A peculiarity of socks 4 - if the address returned is 0, use the
@@ -379,28 +385,16 @@
// currently the Socks4Message.getIP() only returns int,
// so only works with IPv4 4byte addresses
byte[] replyBytes = new byte[4];
- intToBytes(reply.getIP(), replyBytes, 0);
+ OSMemory.pokeInt(replyBytes, 0, reply.getIP(), ByteOrder.BIG_ENDIAN);
address = InetAddress.getByAddress(replyBytes);
}
localport = reply.getPort();
}
- private static void intToBytes(int value, byte[] bytes, int start) {
- /*
- * Shift the int so the current byte is right-most Use a byte mask of
- * 255 to single out the last byte.
- */
- bytes[start] = (byte) ((value >> 24) & 255);
- bytes[start + 1] = (byte) ((value >> 16) & 255);
- bytes[start + 2] = (byte) ((value >> 8) & 255);
- bytes[start + 3] = (byte) (value & 255);
- }
-
/**
* Send a SOCKS V4 request.
*/
- private void socksSendRequest(int command, InetAddress address, int port)
- throws IOException {
+ private void socksSendRequest(int command, InetAddress address, int port) throws IOException {
Socks4Message request = new Socks4Message();
request.setCommandOrResult(command);
request.setPort(port);
@@ -444,18 +438,14 @@
@Override
protected void sendUrgentData(int value) throws IOException {
- netImpl.sendUrgentData(fd, (byte) value);
- }
-
- FileDescriptor getFD() {
- return fd;
+ Platform.NETWORK.sendUrgentData(fd, (byte) value);
}
int read(byte[] buffer, int offset, int count) throws IOException {
if (shutdownInput) {
return -1;
}
- int read = netImpl.read(fd, buffer, offset, count);
+ int read = Platform.NETWORK.read(fd, buffer, offset, count);
// Return of zero bytes for a blocking socket means a timeout occurred
if (read == 0) {
throw new SocketTimeoutException();
@@ -469,9 +459,9 @@
int write(byte[] buffer, int offset, int count) throws IOException {
if (streaming) {
- return netImpl.write(fd, buffer, offset, count);
+ return Platform.NETWORK.write(fd, buffer, offset, count);
} else {
- return netImpl.send(fd, buffer, offset, count, port, address);
+ return Platform.NETWORK.send(fd, buffer, offset, count, port, address);
}
}
}
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/net/Socks4Message.java b/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java
index efd0fce..065e205 100644
--- a/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java
+++ b/luni/src/main/java/org/apache/harmony/luni/net/Socks4Message.java
@@ -17,7 +17,9 @@
package org.apache.harmony.luni.net;
+import java.nio.ByteOrder;
import java.nio.charset.Charsets;
+import org.apache.harmony.luni.platform.OSMemory;
class Socks4Message {
static final int COMMAND_CONNECT = 1;
@@ -76,21 +78,21 @@
* Returns the request's port number.
*/
public int getPort() {
- return getInt16(INDEX_PORT);
+ return OSMemory.peekShort(buffer, INDEX_PORT, ByteOrder.BIG_ENDIAN);
}
/**
* Set the request's port number.
*/
public void setPort(int port) {
- setInt16(INDEX_PORT, port);
+ OSMemory.pokeShort(buffer, INDEX_PORT, (short) port, ByteOrder.BIG_ENDIAN);
}
/**
* Returns the IP address of the request as an integer.
*/
public int getIP() {
- return getInt32(INDEX_IP);
+ return OSMemory.peekInt(buffer, INDEX_IP, ByteOrder.BIG_ENDIAN);
}
/**
@@ -178,22 +180,6 @@
}
/**
- * Get a 16 bit integer from the buffer at the offset given.
- */
- private int getInt16(int offset) {
- return (((buffer[offset] & 0xFF) << 8) + (buffer[offset + 1] & 0xFF));
- }
-
- /**
- * Get a 32 bit integer from the buffer at the offset given.
- */
- private int getInt32(int offset) {
- return ((buffer[offset + 3] & 0xFF)
- + ((buffer[offset + 2] & 0xFF) << 8)
- + ((buffer[offset + 1] & 0xFF) << 16) + ((buffer[offset + 0] & 0xFF) << 24));
- }
-
- /**
* Get a String from the buffer at the offset given. The method reads until
* it encounters a null value or reaches the maxLength given.
*/
@@ -214,14 +200,6 @@
}
/**
- * Put a 16 bit integer into the buffer at the offset given.
- */
- private void setInt16(int offset, int value) {
- buffer[offset] = (byte) (value >>> 8 & 0xFF);
- buffer[offset + 1] = (byte) (value & 0xFF);
- }
-
- /**
* Put a string into the buffer at the offset given.
*/
private void setString(int offset, int maxLength, String theString) {
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/IFileSystem.java b/luni/src/main/java/org/apache/harmony/luni/platform/IFileSystem.java
index 08f1453..2100cef 100644
--- a/luni/src/main/java/org/apache/harmony/luni/platform/IFileSystem.java
+++ b/luni/src/main/java/org/apache/harmony/luni/platform/IFileSystem.java
@@ -98,7 +98,7 @@
/**
* Returns the granularity for virtual memory allocation.
*/
- public int getAllocGranularity() throws IOException;
+ public int getAllocGranularity();
public int open(String path, int mode) throws FileNotFoundException;
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/INetworkSystem.java b/luni/src/main/java/org/apache/harmony/luni/platform/INetworkSystem.java
index 24a42db..682ec3a 100644
--- a/luni/src/main/java/org/apache/harmony/luni/platform/INetworkSystem.java
+++ b/luni/src/main/java/org/apache/harmony/luni/platform/INetworkSystem.java
@@ -140,6 +140,10 @@
public void setSocketOption(FileDescriptor fd, int opt, Object optVal)
throws SocketException;
+ /**
+ * It is an error to close the same file descriptor from multiple threads
+ * concurrently.
+ */
public void close(FileDescriptor fd) throws IOException;
// TODO: change the single caller so that recv/recvDirect
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/MappedPlatformAddress.java b/luni/src/main/java/org/apache/harmony/luni/platform/MappedPlatformAddress.java
deleted file mode 100644
index 52894b7..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/platform/MappedPlatformAddress.java
+++ /dev/null
@@ -1,56 +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.
- */
-
-// BEGIN android-note
-// address length was changed from long to int for performance reasons.
-// END android-note
-
-package org.apache.harmony.luni.platform;
-
-public class MappedPlatformAddress extends PlatformAddress {
- MappedPlatformAddress(int address, long size) {
- super(address, size);
- }
-
- public final void mmapLoad() {
- memorySpy.rangeCheck(this, 0, (int) size * SIZEOF_JBYTE);
- OSMemory.load(osaddr, size);
- }
-
- public final boolean mmapIsLoaded() {
- memorySpy.rangeCheck(this, 0, (int) size * SIZEOF_JBYTE);
- return OSMemory.isLoaded(osaddr, size);
- }
-
- public final void mmapFlush() {
- memorySpy.rangeCheck(this, 0, (int) size * SIZEOF_JBYTE);
- OSMemory.flush(osaddr, size);
- }
-
- public final void free() {
- if (memorySpy.free(this)){
- OSMemory.unmap(osaddr, size);
- }
- }
-
- public PlatformAddress duplicate() {
- return PlatformAddressFactory.mapOn(osaddr, size);
- }
-
- public final PlatformAddress offsetBytes(int offset) {
- return PlatformAddressFactory.mapOn(osaddr + offset, size - offset);
- }
-}
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 6d4aa40..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
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// address length was changed from long to int for performance reasons.
-// END android-note
-
package org.apache.harmony.luni.platform;
import java.io.IOException;
@@ -26,30 +22,128 @@
import java.nio.channels.FileChannel.MapMode;
/**
- * This class enables direct access to OS memory.
+ * This class enables direct access to memory.
+ *
+ * @hide - we should move this in with the NIO stuff it supports, and make it package-private again
*/
-final class OSMemory {
- /**
- * Defines the natural byte order for this machine.
- */
- public static final ByteOrder NATIVE_ORDER = ByteOrder.nativeOrder();
+public final class OSMemory {
+ private OSMemory() { }
- private OSMemory() {
+ /**
+ * Used to optimize nio heap buffer bulk get operations. 'dst' must be a primitive array.
+ * 'dstOffset' is measured in units of 'sizeofElements' bytes.
+ */
+ public static native void unsafeBulkGet(Object dst, int dstOffset, int byteCount,
+ byte[] src, int srcOffset, int sizeofElements, boolean swap);
+
+ /**
+ * Used to optimize nio heap buffer bulk put operations. 'src' must be a primitive array.
+ * 'srcOffset' is measured in units of 'sizeofElements' bytes.
+ */
+ 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);
+ }
}
/**
- * Allocates and returns a pointer to space for a memory block of
- * <code>length</code> bytes. The space is uninitialized and may be larger
- * than the number of bytes requested; however, the guaranteed usable memory
- * block is exactly <code>length</code> bytes int.
- *
- * @param length
- * number of bytes requested.
- * @return the address of the start of the memory block.
- * @throws OutOfMemoryError
- * if the request cannot be satisfied.
+ * Returns the address of byteCount bytes of memory. Unlike the corresponding C library
+ * function, the memory returned has been zero-initialized.
*/
- public static native int malloc(int length) throws OutOfMemoryError;
+ public static native int malloc(int byteCount) throws OutOfMemoryError;
/**
* Deallocates space for a memory block that was previously allocated by a
@@ -67,24 +161,6 @@
public static native void free(int address);
/**
- * Places <code>value</code> into first <code>length</code> bytes of the
- * memory block starting at <code>address</code>.
- * <p>
- * The behavior is unspecified if
- * <code>(address ... address + length)</code> is not wholly within the
- * range that was previously allocated using <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the address of the first memory location.
- * @param value
- * the byte value to set at each location.
- * @param length
- * the number of byte-length locations to set.
- */
- public static native void memset(int address, byte value, long length);
-
- /**
* Copies <code>length</code> bytes from <code>srcAddress</code> to
* <code>destAddress</code>. Where any part of the source memory block
* and the destination memory block overlap <code>memmove()</code> ensures
@@ -107,395 +183,31 @@
*/
public static native void memmove(int destAddress, int srcAddress, long length);
- /**
- * Copies <code>length</code> bytes from the memory block at
- * <code>address</code> into the byte array <code>bytes</code> starting
- * at element <code>offset</code> within the byte array.
- * <p>
- * The behavior of this method is undefined if the range
- * <code>(address ... address + length)</code> is not within a memory
- * block that was allocated using {@link #malloc(int) malloc(int)}.
- * </p>
- *
- * @param address
- * the address of the OS memory block from which to copy bytes.
- * @param bytes
- * the byte array into which to copy the bytes.
- * @param offset
- * the index of the first element in <code>bytes</code> that
- * will be overwritten.
- * @param length
- * the total number of bytes to copy into the byte array.
- * @throws NullPointerException
- * if <code>bytes</code> is <code>null</code>.
- * @throws IndexOutOfBoundsException
- * if <code>offset + length > bytes.length</code>.
- */
- public static native void getByteArray(int address, byte[] bytes, int offset,
- int length) throws NullPointerException, IndexOutOfBoundsException;
+ public static native byte peekByte(int address);
+ public static native int peekInt(int address, boolean swap);
+ public static native long peekLong(int address, boolean swap);
+ public static native short peekShort(int address, boolean swap);
- /**
- * Copies <code>length</code> bytes from the byte array <code>bytes</code>
- * into the memory block at <code>address</code>, starting at element
- * <code>offset</code> within the byte array.
- * <p>
- * The behavior of this method is undefined if the range
- * <code>(address ... address + length)</code> is not within a memory
- * block that was allocated using {@link #malloc(int) malloc(int)}.
- * </p>
- *
- * @param address
- * the address of the OS memory block into which to copy the
- * bytes.
- * @param bytes
- * the byte array from which to copy the bytes.
- * @param offset
- * the index of the first element in <code>bytes</code> that
- * will be read.
- * @param length
- * the total number of bytes to copy from <code>bytes</code>
- * into the memory block.
- * @throws NullPointerException
- * if <code>bytes</code> is <code>null</code>.
- * @throws IndexOutOfBoundsException
- * if <code>offset + length > bytes.length</code>.
- */
- public static native void setByteArray(int address, byte[] bytes, int offset,
- int length) throws NullPointerException, IndexOutOfBoundsException;
+ public static native void peekByteArray(int address, byte[] dst, int dstOffset, int byteCount);
+ public static native void peekCharArray(int address, char[] dst, int dstOffset, int charCount, boolean swap);
+ public static native void peekDoubleArray(int address, double[] dst, int dstOffset, int doubleCount, boolean swap);
+ public static native void peekFloatArray(int address, float[] dst, int dstOffset, int floatCount, boolean swap);
+ public static native void peekIntArray(int address, int[] dst, int dstOffset, int intCount, boolean swap);
+ public static native void peekLongArray(int address, long[] dst, int dstOffset, int longCount, boolean swap);
+ public static native void peekShortArray(int address, short[] dst, int dstOffset, int shortCount, boolean swap);
- /**
- * Copies <code>length</code> shorts from the short array <code>shorts</code>
- * into the memory block at <code>address</code>, starting at element
- * <code>offset</code> within the short array.
- * <p>
- * The behavior of this method is undefined if the range
- * <code>(address ... address + 2*length)</code> is not within a memory
- * block that was allocated using {@link #malloc(int) malloc(int)}.
- * </p>
- *
- * @param address
- * the address of the OS memory block into which to copy the
- * shorts.
- * @param shorts
- * the short array from which to copy the shorts.
- * @param offset
- * the index of the first element in <code>shorts</code> that
- * will be read.
- * @param length
- * the total number of shorts to copy from <code>shorts</code>
- * into the memory block.
- * @param swap
- * true if the shorts should be written in reverse byte order.
- * @throws NullPointerException
- * if <code>bytes</code> is <code>null</code>.
- * @throws IndexOutOfBoundsException
- * if <code>offset + length > bytes.length</code>.
- */
- public static native void setShortArray(int address, short[] shorts, int offset,
- int length, boolean swap) throws NullPointerException,
- IndexOutOfBoundsException;
+ public static native void pokeByte(int address, byte value);
+ public static native void pokeInt(int address, int value, boolean swap);
+ public static native void pokeLong(int address, long value, boolean swap);
+ public static native void pokeShort(int address, short value, boolean swap);
- /**
- * Copies <code>length</code> ints from the int array <code>ints</code>
- * into the memory block at <code>address</code>, starting at element
- * <code>offset</code> within the int array.
- * <p>
- * The behavior of this method is undefined if the range
- * <code>(address ... address + 2*length)</code> is not within a memory
- * block that was allocated using {@link #malloc(int) malloc(int)}.
- * </p>
- *
- * @param address
- * the address of the OS memory block into which to copy the
- * ints.
- * @param ints
- * the int array from which to copy the ints.
- * @param offset
- * the index of the first element in <code>ints</code> that
- * will be read.
- * @param length
- * the total number of ints to copy from <code>ints</code>
- * into the memory block.
- * @param swap
- * true if the ints should be written in reverse byte order.
- * @throws NullPointerException
- * if <code>bytes</code> is <code>null</code>.
- * @throws IndexOutOfBoundsException
- * if <code>offset + length > bytes.length</code>.
- */
- public static native void setIntArray(int address, int[] ints, int offset,
- int length, boolean swap) throws NullPointerException,
- IndexOutOfBoundsException;
-
- public static native void setFloatArray(int address, float[] floats, int offset,
- int length, boolean swap) throws NullPointerException,
- IndexOutOfBoundsException;
-
- /**
- * Gets the value of the single byte at the given address.
- * <p>
- * The behavior is unspecified if <code>address</code> is not in the range
- * that was previously allocated using <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the byte.
- * @return the byte value.
- */
- public static native byte getByte(int address);
-
- /**
- * Sets the given single byte value at the given address.
- * <p>
- * The behavior is unspecified if <code>address</code> is not in the range
- * that was previously allocated using <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the address at which to set the byte value.
- * @param value
- * the value to set.
- */
- public static native void setByte(int address, byte value);
-
- /**
- * Gets the value of the signed two-byte integer stored in platform byte
- * order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 2)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the two-byte value.
- * @return the value of the two-byte integer as a Java <code>short</code>.
- */
- public static native short getShort(int address);
-
- public static short getShort(int address, ByteOrder byteOrder) {
- return (byteOrder == NATIVE_ORDER)
- ? getShort(address)
- : Short.reverseBytes(getShort(address));
- }
-
- /**
- * Sets the value of the signed two-byte integer at the given address in
- * platform byte order.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 2)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the two-byte value.
- * @param value
- * the value of the two-byte integer as a Java <code>short</code>.
- */
- public static native void setShort(int address, short value);
-
- public static void setShort(int address, short value, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- setShort(address, value);
- } else {
- setShort(address, Short.reverseBytes(value));
- }
- }
-
- /**
- * Gets the value of the signed four-byte integer stored in platform
- * byte-order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 4)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the four-byte value.
- * @return the value of the four-byte integer as a Java <code>int</code>.
- */
- public static native int getInt(int address);
-
- public static int getInt(int address, ByteOrder byteOrder) {
- return (byteOrder == NATIVE_ORDER)
- ? getInt(address)
- : Integer.reverseBytes(getInt(address));
- }
-
- /**
- * Sets the value of the signed four-byte integer at the given address in
- * platform byte order.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 4)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the four-byte value.
- * @param value
- * the value of the four-byte integer as a Java <code>int</code>.
- */
- public static native void setInt(int address, int value);
-
- public static void setInt(int address, int value, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- setInt(address, value);
- } else {
- setInt(address, Integer.reverseBytes(value));
- }
- }
-
- /**
- * Gets the value of the signed eight-byte integer stored in platform byte
- * order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 8)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the eight-byte value.
- * @return the value of the eight-byte integer as a Java <code>long</code>.
- */
- public static native long getLong(int address);
-
- public static long getLong(int address, ByteOrder byteOrder) {
- return (byteOrder == NATIVE_ORDER)
- ? getLong(address)
- : Long.reverseBytes(getLong(address));
- }
-
- /**
- * Sets the value of the signed eight-byte integer at the given address in
- * the platform byte order.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 8)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the eight-byte value.
- * @param value
- * the value of the eight-byte integer as a Java
- * <code>long</code>.
- */
- public static native void setLong(int address, long value);
-
- public static void setLong(int address, long value, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- setLong(address, value);
- } else {
- setLong(address, Long.reverseBytes(value));
- }
- }
-
- /**
- * Gets the value of the IEEE754-format four-byte float stored in platform
- * byte order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 4)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the eight-byte value.
- * @return the value of the four-byte float as a Java <code>float</code>.
- */
- public static native float getFloat(int address);
-
- public static float getFloat(int address, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- return getFloat(address);
- }
- int floatBits = Integer.reverseBytes(getInt(address));
- return Float.intBitsToFloat(floatBits);
- }
-
- /**
- * Sets the value of the IEEE754-format four-byte float stored in platform
- * byte order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 4)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the eight-byte value.
- * @param value
- * the value of the four-byte float as a Java <code>float</code>.
- */
- public static native void setFloat(int address, float value);
-
- public static void setFloat(int address, float value, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- setFloat(address, value);
- } else {
- int floatBits = Float.floatToIntBits(value);
- setInt(address, Integer.reverseBytes(floatBits));
- }
- }
-
- /**
- * Gets the value of the IEEE754-format eight-byte float stored in platform
- * byte order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 8)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the eight-byte value.
- * @return the value of the eight-byte float as a Java <code>double</code>.
- */
- public static native double getDouble(int address);
-
- public static double getDouble(int address, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- return getDouble(address);
- }
- long doubleBits = Long.reverseBytes(getLong(address));
- return Double.longBitsToDouble(doubleBits);
- }
-
- /**
- * Sets the value of the IEEE754-format eight-byte float store in platform
- * byte order at the given address.
- * <p>
- * The behavior is unspecified if <code>(address ... address + 8)</code>
- * is not wholly within the range that was previously allocated using
- * <code>malloc()</code>.
- * </p>
- *
- * @param address
- * the platform address of the start of the eight-byte value.
- * @param value
- * the value of the eight-byte float as a Java
- * <code>double</code>.
- */
- public static native void setDouble(int address, double value);
-
- public static void setDouble(int address, double value, ByteOrder byteOrder) {
- if (byteOrder == NATIVE_ORDER) {
- setDouble(address, value);
- } else {
- long doubleBits = Double.doubleToLongBits(value);
- setLong(address, Long.reverseBytes(doubleBits));
- }
- }
-
- // "get uintptr_t"
- public static native int getAddress(int address);
-
- // "put uintptr_t"
- public static native void setAddress(int address, int value);
+ public static native void pokeByteArray(int address, byte[] src, int offset, int count);
+ public static native void pokeCharArray(int address, char[] src, int offset, int count, boolean swap);
+ public static native void pokeDoubleArray(int address, double[] src, int offset, int count, boolean swap);
+ public static native void pokeFloatArray(int address, float[] src, int offset, int count, boolean swap);
+ public static native void pokeIntArray(int address, int[] src, int offset, int count, boolean swap);
+ public static native void pokeLongArray(int address, long[] src, int offset, int count, boolean swap);
+ public static native void pokeShortArray(int address, short[] src, int offset, int count, boolean swap);
private static native int mmapImpl(int fd, long offset, long size, int mapMode);
@@ -512,13 +224,12 @@
}
return mmapImpl(fd, offset, size, intMode);
}
- // END android-changed
- public static native void unmap(int addr, long size);
+ public static native void munmap(int addr, long size);
public static native void load(int addr, long size);
public static native boolean isLoaded(int addr, long size);
- public static native void flush(int addr, long size);
+ public static native void msync(int addr, long size);
}
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/Platform.java b/luni/src/main/java/org/apache/harmony/luni/platform/Platform.java
index 62725f5..fb9caf9 100644
--- a/luni/src/main/java/org/apache/harmony/luni/platform/Platform.java
+++ b/luni/src/main/java/org/apache/harmony/luni/platform/Platform.java
@@ -35,41 +35,13 @@
* @see INetworkSystem
*/
public class Platform {
- // Note: for now, we're always wrapping the filesystem with
- // BlockGuard. In the future we intend to measure this and, with
- // the arriving of upcoming method call Dalvik improvements,
- // remove a lot of the static caching in RandomAccessFile, etc.,
- // at which point we can make getFileSystem() return an unwrapped
- // filesystem in some cases so RandomAccessFiles created on
- // BlockGuard-policy-free threads have no extra overhead. But for
- // now they do: ThreadLocal lookups will be done on most VFS
- // operations, which should be relatively less than the speed of
- // the flash.
+ // BlockGuard-policy-free threads should have no extra overhead, but for
+ // now they do because ThreadLocal lookups will be done on most operations, which
+ // should be relatively less than the speed of the operation.
// TODO: measure & fix if needed.
- private static final IFileSystem FILE_SYSTEM =
+ public static final IFileSystem FILE_SYSTEM =
new BlockGuard.WrappedFileSystem(OSFileSystem.getOSFileSystem());
- private static final INetworkSystem NETWORK_SYSTEM =
+ public static final INetworkSystem NETWORK =
new BlockGuard.WrappedNetworkSystem(OSNetworkSystem.getOSNetworkSystem());
-
- /**
- * Checks to ensure that whoever is asking for the OS component is running
- * on the system classpath.
- */
- private static final void accessCheck() {
- if (VMStack.getCallingClassLoader() != null) {
- throw new SecurityException();
- }
- }
-
- public static IFileSystem getFileSystem() {
- accessCheck();
- return FILE_SYSTEM;
- }
-
- public static INetworkSystem getNetworkSystem() {
- accessCheck();
- // TODO: use BlockGuard here too, like in getFileSystem() above.
- return NETWORK_SYSTEM;
- }
}
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/PlatformAddress.java b/luni/src/main/java/org/apache/harmony/luni/platform/PlatformAddress.java
deleted file mode 100644
index 5dd0337..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/platform/PlatformAddress.java
+++ /dev/null
@@ -1,295 +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.
- */
-
-// BEGIN android-note
-// address length was changed from long to int for performance reasons.
-// END android-note
-
-package org.apache.harmony.luni.platform;
-
-import java.nio.ByteOrder;
-
-/**
- * The platform address class is an unsafe virtualization of an OS memory block.
- */
-public class PlatformAddress implements Comparable {
- public static final int SIZEOF_JBYTE = 1;
- public static final int SIZEOF_JSHORT = 2;
- public static final int SIZEOF_JINT = 4;
- public static final int SIZEOF_JSIZE = 4;
- public static final int SIZEOF_JFLOAT = 4;
- public static final int SIZEOF_JLONG = 8;
- public static final int SIZEOF_JDOUBLE = 8;
-
- /**
- * This final field defines the sentinel for an unknown address value.
- */
- static final int UNKNOWN = -1;
-
- /**
- * NULL is the canonical address with address value zero.
- */
- public static final PlatformAddress NULL = new PlatformAddress(0, 0);
-
- /**
- * INVALID is the canonical address with an invalid value
- * (i.e. a non-address).
- */
- public static final PlatformAddress INVALID = new PlatformAddress(UNKNOWN, UNKNOWN);
-
- public static final RuntimeMemorySpy memorySpy = new RuntimeMemorySpy();
-
- final int osaddr;
-
- final long size;
-
- PlatformAddress(int address, long size) {
- super();
- osaddr = address;
- this.size = size;
- }
-
- /**
- * Sending auto free to an address means that, when this subsystem has
- * allocated the memory, it will automatically be freed when this object is
- * collected by the garbage collector if the memory has not already been
- * freed explicitly.
- *
- */
- public final void autoFree() {
- memorySpy.autoFree(this);
- }
-
- public PlatformAddress duplicate() {
- return PlatformAddressFactory.on(osaddr, size);
- }
-
- public PlatformAddress offsetBytes(int offset) {
- return PlatformAddressFactory.on(osaddr + offset, size - offset);
- }
-
- public final void moveTo(PlatformAddress dst, long numBytes) {
- OSMemory.memmove(dst.osaddr, osaddr, numBytes);
- }
-
- public final boolean equals(Object other) {
- return (other instanceof PlatformAddress)
- && (((PlatformAddress) other).osaddr == osaddr);
- }
-
- public final int hashCode() {
- return (int) osaddr;
- }
-
- public final boolean isNULL() {
- return this == NULL;
- }
-
- public void free() {
- // Memory spys can veto the basic free if they determine the memory was
- // not allocated.
- if (memorySpy.free(this)) {
- OSMemory.free(osaddr);
- }
- }
-
- public final void setAddress(int offset, PlatformAddress address) {
- OSMemory.setAddress(osaddr + offset, address.osaddr);
- }
-
- public final PlatformAddress getAddress(int offset) {
- int addr = getInt(offset);
- return PlatformAddressFactory.on(addr);
- }
-
- public final void setByte(int offset, byte value) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JBYTE);
- OSMemory.setByte(osaddr + offset, value);
- }
-
- public final void setByteArray(int offset, byte[] bytes, int bytesOffset,
- int length) {
- memorySpy.rangeCheck(this, offset, length * SIZEOF_JBYTE);
- OSMemory.setByteArray(osaddr + offset, bytes, bytesOffset, length);
- }
-
- // BEGIN android-added
- public final void setShortArray(int offset, short[] shorts,
- int shortsOffset, int length, boolean swap) {
- memorySpy.rangeCheck(this, offset, length * SIZEOF_JSHORT);
- OSMemory.setShortArray(osaddr + offset, shorts, shortsOffset, length,
- swap);
- }
-
- public final void setIntArray(int offset, int[] ints,
- int intsOffset, int length, boolean swap) {
- memorySpy.rangeCheck(this, offset, length * SIZEOF_JINT);
- OSMemory.setIntArray(osaddr + offset, ints, intsOffset, length, swap);
- }
-
- public final void setFloatArray(int offset, float[] floats,
- int floatsOffset, int length, boolean swap) {
- memorySpy.rangeCheck(this, offset, length * SIZEOF_JFLOAT);
- OSMemory.setFloatArray(
- osaddr + offset, floats, floatsOffset, length, swap);
- }
- // END android-added
-
- public final byte getByte(int offset) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JBYTE);
- return OSMemory.getByte(osaddr + offset);
- }
-
- public final void getByteArray(int offset, byte[] bytes, int bytesOffset,
- int length) {
- memorySpy.rangeCheck(this, offset, length * SIZEOF_JBYTE);
- OSMemory.getByteArray(osaddr + offset, bytes, bytesOffset, length);
- }
-
- public final void setShort(int offset, short value, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JSHORT);
- OSMemory.setShort(osaddr + offset, value, order);
- }
-
- public final void setShort(int offset, short value) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JSHORT);
- OSMemory.setShort(osaddr + offset, value);
- }
-
- public final short getShort(int offset, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JSHORT);
- return OSMemory.getShort(osaddr + offset, order);
- }
-
- public final short getShort(int offset) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JSHORT);
- return OSMemory.getShort(osaddr + offset);
- }
-
- public final void setInt(int offset, int value, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JINT);
- OSMemory.setInt(osaddr + offset, value, order);
- }
-
- public final void setInt(int offset, int value) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JINT);
- OSMemory.setInt(osaddr + offset, value);
- }
-
- public final int getInt(int offset, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JINT);
- return OSMemory.getInt(osaddr + offset, order);
- }
-
- public final int getInt(int offset) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JINT);
- return OSMemory.getInt(osaddr + offset);
- }
-
- public final void setLong(int offset, long value, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JLONG);
- OSMemory.setLong(osaddr + offset, value, order);
- }
-
- public final void setLong(int offset, long value) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JLONG);
- OSMemory.setLong(osaddr + offset, value);
- }
-
- public final long getLong(int offset, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JLONG);
- return OSMemory.getLong(osaddr + offset, order);
- }
-
- public final long getLong(int offset) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JLONG);
- return OSMemory.getLong(osaddr + offset);
- }
-
- public final void setFloat(int offset, float value, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JFLOAT);
- OSMemory.setFloat(osaddr + offset, value, order);
- }
-
- public final void setFloat(int offset, float value) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JFLOAT);
- OSMemory.setFloat(osaddr + offset, value);
- }
-
- public final float getFloat(int offset, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JFLOAT);
- return OSMemory.getFloat(osaddr + offset, order);
- }
-
- public final float getFloat(int offset) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JFLOAT);
- return OSMemory.getFloat(osaddr + offset);
- }
-
- public final void setDouble(int offset, double value, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JDOUBLE);
- OSMemory.setDouble(osaddr + offset, value, order);
- }
-
- public final void setDouble(int offset, double value) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JDOUBLE);
- OSMemory.setDouble(osaddr + offset, value);
- }
-
- public final double getDouble(int offset, ByteOrder order) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JDOUBLE);
- return OSMemory.getDouble(osaddr + offset, order);
- }
-
- public final double getDouble(int offset) {
- memorySpy.rangeCheck(this, offset, SIZEOF_JDOUBLE);
- return OSMemory.getDouble(osaddr + offset);
- }
-
- // BEGIN android-added
- public final int toInt() {
- return osaddr;
- }
- // END android-added
-
- public final long toLong() {
- return osaddr;
- }
-
- public final String toString() {
- return "PlatformAddress[" + osaddr + "]";
- }
-
- public final long getSize() {
- return size;
- }
-
- public final int compareTo(Object other) {
- if (other == null) {
- throw new NullPointerException(); // per spec.
- }
- if (other instanceof PlatformAddress) {
- int otherPA = ((PlatformAddress) other).osaddr;
- if (osaddr == otherPA) {
- return 0;
- }
- return osaddr < otherPA ? -1 : 1;
- }
-
- throw new ClassCastException(); // per spec.
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/PlatformAddressFactory.java b/luni/src/main/java/org/apache/harmony/luni/platform/PlatformAddressFactory.java
deleted file mode 100644
index 86df02d..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/platform/PlatformAddressFactory.java
+++ /dev/null
@@ -1,143 +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.
- */
-
-// BEGIN android-note
-// address length was changed from long to int for performance reasons.
-// END android-note
-
-package org.apache.harmony.luni.platform;
-
-import java.io.IOException;
-import java.nio.channels.FileChannel.MapMode;
-
-public class PlatformAddressFactory {
-
- // BEGIN android-added
- /**
- * Defines the number of PlatformAddress objects to be cached. Must be a
- * power of two. Caching PlatformAddress objects minimizes the creation
- * of garbage and reduces the number of GC-hiccups in OpenGL animations.
- */
- private final static int CACHE_SIZE = 1<<8;
-
- /**
- * A mask with all bits set, matching the size of the cache.
- */
- private final static int CACHE_MASK = CACHE_SIZE - 1;
-
- /**
- * Defines the maximum number of probes taken per hash, used for looking
- * up an empty cache slot or a previously stored PlatformAddress.
- */
- private final static int MAX_PROBES = 5;
-
- /**
- * A cycling index (0 to MAX_PROBES-1) used to replace elements in
- * the cache.
- */
- private static int replacementIndex = 0;
-
- /**
- * Array of PlatformAddress references kept from garbage collection.
- */
- private static PlatformAddress[] cache = new PlatformAddress[CACHE_SIZE];
-
- /**
- * Constructs a {@code PlatformAddress} or returns
- * {@link PlatformAddress#NULL} if given a {@code null} address.
- *
- * @param address the start address for the memory; {@code 0} means
- * {@code null}
- * @param size the size of the memory in bytes
- * @return an appropriately-constructed {@code PlatformAddress}
- */
- private static PlatformAddress make(int value, long size) {
- if (value == 0) {
- return PlatformAddress.NULL;
- }
-
- return new PlatformAddress(value, size);
- }
- // END android-added
-
- // BEGIN android-changed
- public synchronized static PlatformAddress on(int value, long size) {
- if (value == 0) {
- return PlatformAddress.NULL;
- }
- int idx = value >> 5;
- for (int probe = 0; probe < MAX_PROBES; probe++) {
- PlatformAddress cachedObj = cache[(idx + probe) & CACHE_MASK];
- if (cachedObj == null) {
- return cache[(idx + probe) & CACHE_MASK] =
- new PlatformAddress(value, size);
- }
- if (cachedObj.osaddr == value && cachedObj.size == size) {
- return cachedObj;
- }
- }
- replacementIndex = (replacementIndex + 1) % MAX_PROBES;
- return cache[(idx + replacementIndex) & CACHE_MASK] =
- new PlatformAddress(value, size);
- }
- // END android-changed
-
- public static PlatformAddress on(int value) {
- return PlatformAddressFactory.on(value, PlatformAddress.UNKNOWN);
- }
-
- public static MappedPlatformAddress mapOn(int value, long size) {
- MappedPlatformAddress addr = new MappedPlatformAddress(value, size);
- return addr;
- }
-
- public static PlatformAddress allocMap(int fd, long start, long size, MapMode mode)
- throws IOException {
- if (size == 0) {
- // if size is 0, call to mmap has incorrect behaviour on
- // unix and windows, so return empty address
- return mapOn(0, 0);
- }
- int osAddress = OSMemory.mmap(fd, start, size, mode);
- PlatformAddress newMemory = mapOn(osAddress, size);
- PlatformAddress.memorySpy.alloc(newMemory);
- return newMemory;
- }
-
- /**
- * Allocates a contiguous block of OS heap memory and initializes it to
- * a given value.
- *
- * @param size The number of bytes to allocate from the system heap.
- * @param init The value to initialize the memory.
- * @return PlatformAddress representing the memory block.
- */
- public static PlatformAddress alloc(int size, byte init) {
- int osAddress = OSMemory.malloc(size);
- OSMemory.memset(osAddress, init, size);
- /*
- * We use make() and not on() here, for a couple reasons:
- * First and foremost, doing so means that if the client uses
- * address.autoFree() (to enable auto-free on gc) the cache
- * won't prevent the freeing behavior. Second, this avoids
- * polluting the cache with addresses that aren't likely to be
- * reused anyway.
- */
- PlatformAddress newMemory = make(osAddress, size);
- PlatformAddress.memorySpy.alloc(newMemory);
- return newMemory;
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/RuntimeMemorySpy.java b/luni/src/main/java/org/apache/harmony/luni/platform/RuntimeMemorySpy.java
deleted file mode 100644
index 8be70c6..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/platform/RuntimeMemorySpy.java
+++ /dev/null
@@ -1,118 +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.luni.platform;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.util.HashMap;
-import java.util.Map;
-
-final class RuntimeMemorySpy {
-
- final class AddressWrapper {
- final PlatformAddress shadow;
-
- final PhantomReference<PlatformAddress> wrAddress;
-
- volatile boolean autoFree = false;
-
- AddressWrapper(PlatformAddress address) {
- this.shadow = address.duplicate();
- this.wrAddress = new PhantomReference<PlatformAddress>(address, notifyQueue);
- }
- }
-
- // TODO: figure out how to prevent this being a synchronization bottleneck
- private final Map<PlatformAddress, AddressWrapper> memoryInUse = new HashMap<PlatformAddress, AddressWrapper>(); // Shadow to Wrapper
-
- private final Map<Reference, PlatformAddress> refToShadow = new HashMap<Reference, PlatformAddress>(); // Reference to Shadow
-
- private final ReferenceQueue<Object> notifyQueue = new ReferenceQueue<Object>();
-
- public RuntimeMemorySpy() {
- }
-
- public void alloc(PlatformAddress address) {
- // Pay a tax on the allocation to see if there are any frees pending.
- Reference ref = notifyQueue.poll(); // non-blocking check
- while (ref != null) {
- orphanedMemory(ref);
- ref = notifyQueue.poll();
- }
-
- AddressWrapper wrapper = new AddressWrapper(address);
- synchronized (this) {
- memoryInUse.put(wrapper.shadow, wrapper);
- refToShadow.put(wrapper.wrAddress, wrapper.shadow);
- }
- }
-
- // Has a veto: true == do free,false = don't
- public boolean free(PlatformAddress address) {
- AddressWrapper wrapper;
- synchronized (this) {
- wrapper = memoryInUse.remove(address);
- if (wrapper != null) {
- refToShadow.remove(wrapper.wrAddress);
- }
- }
- if (wrapper == null) {
- // Attempt to free memory we didn't alloc
- System.err.println("Memory Spy! Fixed attempt to free memory that was not allocated " + address);
- }
- return wrapper != null;
- }
-
- public void rangeCheck(PlatformAddress address, int offset, int length) throws IndexOutOfBoundsException {
- // Do nothing
- }
-
- /**
- * Requests that the given address is freed automatically when it becomes
- * garbage. If the address is already freed, or has not been notified as
- * allocated via this memory spy, then this call has no effect and completes
- * quietly.
- *
- * @param address
- * the address to be freed.
- */
- public void autoFree(PlatformAddress address) {
- AddressWrapper wrapper;
- synchronized (this) {
- wrapper = memoryInUse.get(address);
- }
- if (wrapper != null) {
- wrapper.autoFree = true;
- }
- }
-
- private void orphanedMemory(Reference ref) {
- synchronized (this) {
- PlatformAddress shadow = refToShadow.remove(ref);
- AddressWrapper wrapper = memoryInUse.get(shadow);
- if (wrapper != null) {
- // There is a leak if we were not auto-freeing this memory.
- if (!wrapper.autoFree) {
- System.err.println("Memory Spy! Fixed memory leak by freeing " + wrapper.shadow);
- }
- wrapper.shadow.free();
- }
- }
- ref.clear();
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/Base64.java b/luni/src/main/java/org/apache/harmony/luni/util/Base64.java
index 2657867..52aaa96 100644
--- a/luni/src/main/java/org/apache/harmony/luni/util/Base64.java
+++ b/luni/src/main/java/org/apache/harmony/luni/util/Base64.java
@@ -103,9 +103,9 @@
quantum = (quantum << 6) | (byte) bits;
if (in_index%4 == 3) {
// 4 characters were read, so make the output:
- out[out_index++] = (byte) ((quantum & 0x00FF0000) >> 16);
- out[out_index++] = (byte) ((quantum & 0x0000FF00) >> 8);
- out[out_index++] = (byte) (quantum & 0x000000FF);
+ out[out_index++] = (byte) (quantum >> 16);
+ out[out_index++] = (byte) (quantum >> 8);
+ out[out_index++] = (byte) quantum;
}
in_index++;
}
@@ -113,9 +113,9 @@
// adjust the quantum value according to the padding
quantum = quantum << (6*pad);
// make output
- out[out_index++] = (byte) ((quantum & 0x00FF0000) >> 16);
+ out[out_index++] = (byte) (quantum >> 16);
if (pad == 1) {
- out[out_index++] = (byte) ((quantum & 0x0000FF00) >> 8);
+ out[out_index++] = (byte) (quantum >> 8);
}
}
// create the resulting array
@@ -138,10 +138,8 @@
int index = 0, i, crlr = 0, end = in.length - in.length%3;
for (i=0; i<end; i+=3) {
out[index++] = map[(in[i] & 0xff) >> 2];
- out[index++] = map[((in[i] & 0x03) << 4)
- | ((in[i+1] & 0xff) >> 4)];
- out[index++] = map[((in[i+1] & 0x0f) << 2)
- | ((in[i+2] & 0xff) >> 6)];
+ out[index++] = map[((in[i] & 0x03) << 4) | ((in[i+1] & 0xff) >> 4)];
+ out[index++] = map[((in[i+1] & 0x0f) << 2) | ((in[i+2] & 0xff) >> 6)];
out[index++] = map[(in[i+2] & 0x3f)];
if (((index - crlr)%76 == 0) && (index != 0)) {
out[index++] = '\n';
@@ -159,8 +157,7 @@
break;
case 2:
out[index++] = map[(in[end] & 0xff) >> 2];
- out[index++] = map[((in[end] & 0x03) << 4)
- | ((in[end+1] & 0xff) >> 4)];
+ out[index++] = map[((in[end] & 0x03) << 4) | ((in[end+1] & 0xff) >> 4)];
out[index++] = map[((in[end+1] & 0x0f) << 2)];
out[index++] = '=';
break;
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/luni/util/ThreadLocalCache.java b/luni/src/main/java/org/apache/harmony/luni/util/ThreadLocalCache.java
deleted file mode 100644
index e1bc217..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/util/ThreadLocalCache.java
+++ /dev/null
@@ -1,103 +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.luni.util;
-
-import java.lang.ref.SoftReference;
-import java.nio.CharBuffer;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.Charsets;
-
-/**
- * The class extends the functionality of {@link java.lang.ThreadLocal} with
- * possibility of discarding the thread local storage content when a heap is
- * exhausted.
- */
-public class ThreadLocalCache<T> {
-
- private SoftReference<ThreadLocal<T>> storage = new SoftReference<ThreadLocal<T>>(
- null);
-
- private ThreadLocal<T> getThreadLocal() {
- ThreadLocal<T> tls = storage.get();
- if (tls == null) {
- tls = new ThreadLocal<T>() {
- public T initialValue() {
- return ThreadLocalCache.this.initialValue();
- }
- };
- storage = new SoftReference<ThreadLocal<T>>(tls);
- }
- return tls;
- }
-
- /**
- * Returns the initial value for the cache for the current thread.
- */
- protected T initialValue() {
- return null;
- }
-
- /**
- * Returns the thread local value of this object.
- */
- public T get() {
- return getThreadLocal().get();
- }
-
- /**
- * Sets the value of this variable for the current thread. Might be useful
- * for expanding the thread local cache.
- */
- public void set(T value) {
- getThreadLocal().set(value);
- }
-
- /**
- * Discards the cache for all threads.
- */
- public void remove() {
- storage.clear();
- }
-
- public static ThreadLocalCache<CharsetDecoder> utf8Decoder = new ThreadLocalCache<CharsetDecoder>() {
- protected CharsetDecoder initialValue() {
- return Charsets.UTF_8.newDecoder();
- }
- };
-
- public static ThreadLocalCache<CharsetEncoder> utf8Encoder = new ThreadLocalCache<CharsetEncoder>() {
- protected CharsetEncoder initialValue() {
- return Charsets.UTF_8.newEncoder();
- }
- };
-
- public static ThreadLocalCache<java.nio.ByteBuffer> byteBuffer = new ThreadLocalCache<java.nio.ByteBuffer>() {
- protected java.nio.ByteBuffer initialValue() {
- return java.nio.ByteBuffer.allocate(72); // >=
- // Manifest.LINE_LENGTH_LIMIT
- }
- };
-
- public static ThreadLocalCache<CharBuffer> charBuffer = new ThreadLocalCache<CharBuffer>() {
- protected CharBuffer initialValue() {
- return CharBuffer.allocate(72); // no specific requirement
- }
- };
-
-}
diff --git a/luni/src/main/java/org/apache/harmony/nio/AddressUtil.java b/luni/src/main/java/org/apache/harmony/nio/AddressUtil.java
deleted file mode 100644
index eaff193..0000000
--- a/luni/src/main/java/org/apache/harmony/nio/AddressUtil.java
+++ /dev/null
@@ -1,51 +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.
- */
-
-/*
- * Android Notice
- * In this class the address length was changed from long to int.
- * This is due to performance optimizations for the device.
- */
-
-package org.apache.harmony.nio;
-
-import java.nio.Buffer;
-import org.apache.harmony.nio.internal.DirectBuffer;
-
-public class AddressUtil {
-
- /**
- * Gets the start address of a direct buffer.
- * <p>
- * This method corresponds to the JNI function:
- *
- * <pre>
- * void* GetDirectBufferAddress(JNIEnv* env, jobject buf);
- * </pre>
- *
- * @param buf
- * the direct buffer whose address shall be returned must not be
- * <code>null</code>.
- * @return the address of the buffer given, or zero if the buffer is not a
- * direct Buffer.
- */
- public static int getDirectBufferAddress(Buffer buf) {
- if (!(buf instanceof DirectBuffer)) {
- return 0;
- }
- return ((DirectBuffer) buf).getEffectiveAddress().toInt();
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/nio/FileChannelFactory.java b/luni/src/main/java/org/apache/harmony/nio/FileChannelFactory.java
deleted file mode 100644
index d51e8f2..0000000
--- a/luni/src/main/java/org/apache/harmony/nio/FileChannelFactory.java
+++ /dev/null
@@ -1,52 +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.
- */
-
-/*
- * Android Notice
- * In this class the address length was changed from long to int.
- * This is due to performance optimizations for the device.
- */
-
-package org.apache.harmony.nio;
-
-import java.nio.channels.FileChannel;
-import org.apache.harmony.luni.platform.IFileSystem;
-import org.apache.harmony.nio.internal.ReadOnlyFileChannel;
-import org.apache.harmony.nio.internal.ReadWriteFileChannel;
-import org.apache.harmony.nio.internal.WriteOnlyFileChannel;
-
-/**
- * A simple factory to provide a generic way to create FileChannel
- * implementation from within the java.io package.
- */
-public class FileChannelFactory {
- public static FileChannel getFileChannel(Object stream, int fd, int mode) {
- switch (mode) {
- case IFileSystem.O_RDONLY:
- return new ReadOnlyFileChannel(stream, fd);
- case IFileSystem.O_WRONLY:
- return new WriteOnlyFileChannel(stream, fd);
- case IFileSystem.O_RDWR:
- return new ReadWriteFileChannel(stream, fd);
- case IFileSystem.O_RDWRSYNC:
- return new ReadWriteFileChannel(stream, fd);
- case IFileSystem.O_APPEND:
- return new WriteOnlyFileChannel(stream, fd, true);
- default:
- throw new RuntimeException("Unknown file channel type " + mode);
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/DirectBuffer.java b/luni/src/main/java/org/apache/harmony/nio/internal/DirectBuffer.java
deleted file mode 100644
index 58c096b..0000000
--- a/luni/src/main/java/org/apache/harmony/nio/internal/DirectBuffer.java
+++ /dev/null
@@ -1,33 +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.nio.internal;
-
-import org.apache.harmony.luni.platform.PlatformAddress;
-
-public interface DirectBuffer {
-
- PlatformAddress getEffectiveAddress();
-
- PlatformAddress getBaseAddress();
-
- boolean isAddressValid();
-
- void addressValidityCheck();
-
- void free();
-
- int getByteCapacity();
-}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/FileLockImpl.java b/luni/src/main/java/org/apache/harmony/nio/internal/FileLockImpl.java
deleted file mode 100644
index d3d2635..0000000
--- a/luni/src/main/java/org/apache/harmony/nio/internal/FileLockImpl.java
+++ /dev/null
@@ -1,76 +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.nio.internal;
-
-import java.io.IOException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
-
-/**
- * The concrete implementation of an NIO file lock object.
- */
-final class FileLockImpl extends FileLock {
-
- // Remembers if this lock has been released via the API.
- private boolean isReleased = false;
-
- /**
- * Constructs a new file lock object with the given parameters.
- *
- * @param channel
- * the file channel hosting the lock.
- * @param position
- * the start position of the lock, in bytes
- * @param size
- * the length of the lock, in bytes
- * @param shared
- * whether this lock is shared (true) or exclusive (false)
- */
- public FileLockImpl(FileChannel channel, long position, long size, boolean shared) {
- super(channel, position, size, shared);
- }
-
- /**
- * Tests to see if the lock is valid. A lock can be invalidated if the
- * channel it is acquired on is closed or if it is released. (non-Javadoc)
- *
- * @see java.nio.channels.FileLock#isValid()
- */
- @Override
- public boolean isValid() {
- return !isReleased && channel().isOpen();
- }
-
- /**
- * Releases the file lock on the channel that acquired it. Releasing an
- * invalid lock has no effect.
- *
- * @see java.nio.channels.FileLock#release()
- */
- @Override
- public void release() throws IOException {
- if (!channel().isOpen()) {
- throw new ClosedChannelException();
- }
-
- if (!isReleased) {
- ((FileChannelImpl) channel()).release(this);
- isReleased = true;
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/IOUtil.java b/luni/src/main/java/org/apache/harmony/nio/internal/IOUtil.java
deleted file mode 100644
index 8a98928..0000000
--- a/luni/src/main/java/org/apache/harmony/nio/internal/IOUtil.java
+++ /dev/null
@@ -1,225 +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.nio.internal;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CoderResult;
-
-/**
- * Static methods for I/O util. Used by io package and nio package.
- */
-public final class IOUtil {
-
- private static final int DEFAULT_BUFFER_SIZE = 8192;
-
- /*
- * Not designed to be instantiated.
- */
- private IOUtil() {
- super();
- }
-
- /*
- * Read method for InputStreamReader and Channels.
- */
- public static int readInputStreamReader(InputStream in, ByteBuffer bytes,
- CharBuffer chars, CharsetDecoder decoder, Object lock)
- throws IOException {
- synchronized (lock) {
- if (in != null) {
- if (chars.limit() == chars.position()) {
- fillBuf(in, bytes, chars, decoder);
- }
- if (chars.limit() == 0) {
- return -1;
- }
- return chars.get();
- }
- throw new IOException("InputStreamReader is closed");
- }
- }
-
- private static void assertArrayIndex(int arrayLength, int offset, int length) {
- if (offset < 0 || length < 0) {
- throw new IndexOutOfBoundsException("Negative index specified");
- }
- if ((long) offset + (long) length > arrayLength) {
- throw new IndexOutOfBoundsException("Size mismatch");
- }
- }
-
- /*
- * Read method for InputStreamReader and Channels.
- */
- public static int readInputStreamReader(char[] buf, int offset, int length,
- InputStream in, ByteBuffer bytes, CharBuffer chars,
- CharsetDecoder decoder, Object lock) throws IOException {
- synchronized (lock) {
- if (in != null) {
- if (length == 0) {
- return 0;
- }
- assertArrayIndex(buf.length, offset, length);
- // read at least once
- if (chars.limit() == chars.position()) {
- fillBuf(in, bytes, chars, decoder);
- }
- int position = chars.position();
- int availableChars = chars.limit() - position;
- // read at least once for one byte
- int needChars = length;
- while (availableChars < needChars) {
- System.arraycopy(chars.array(), position, buf, offset,
- availableChars);
- chars.position(position + availableChars);
- needChars -= availableChars;
- offset += availableChars;
- if (in.available() <= 0) {
- return needChars == length ? -1 : length - needChars;
- }
- fillBuf(in, bytes, chars, decoder);
- position = chars.position();
- availableChars = chars.limit();
- if (availableChars == 0) {
- return needChars == length ? -1 : length - needChars;
- }
- }
- System.arraycopy(chars.array(), position, buf, offset,
- needChars);
- chars.position(chars.position() + needChars);
- return length;
- }
- throw new IOException("InputStreamReader is closed");
- }
- }
-
- /*
- * Refill the buffer from wrapped InputStream.
- */
- private static void fillBuf(InputStream in, ByteBuffer bytes,
- CharBuffer chars, CharsetDecoder decoder) throws IOException {
- chars.clear();
- int read = 0;
- try {
- read = in.read(bytes.array());
- } catch (IOException e) {
- chars.limit(0);
- throw e;
- }
- if (read == -1) {
- chars.limit(0);
- return;
- }
- bytes.limit(read);
- boolean endOfInput = read < DEFAULT_BUFFER_SIZE;
- CoderResult result = decoder.decode(bytes, chars, endOfInput);
- if (result.isError()) {
- throw new IOException(result.toString());
- }
- bytes.clear();
- chars.flip();
- }
-
- /*
- * Write method for OutputStreamWriter and Channels.
- */
- public static void writeOutputStreamWriter(String str, int offset,
- int count, OutputStream out, ByteBuffer bytes,
- CharsetEncoder encoder, Object lock) throws IOException {
- assertArrayIndex(str.length(), offset, count);
- CharBuffer chars = CharBuffer.wrap(str, offset, count + offset);
- convert(lock, encoder, bytes, chars, out);
- }
-
- private static void checkEncoder(CharsetEncoder encoder) throws IOException {
- if (encoder == null) {
- throw new IOException("Writer is closed");
- }
- }
-
- /*
- * Write method for OutputStreamWriter and Channels.
- */
- public static void writeOutputStreamWriter(int oneChar, OutputStream out,
- ByteBuffer bytes, CharsetEncoder encoder, Object lock)
- throws IOException {
- synchronized (lock) {
- checkEncoder(encoder);
- CharBuffer chars = CharBuffer.wrap(new char[] { (char) oneChar });
- convert(lock, encoder, bytes, chars, out);
- }
- }
-
- /*
- * Write method for OutputStreamWriter and Channels.
- */
- public static void writeOutputStreamWriter(char[] buf, int offset,
- int count, OutputStream out, ByteBuffer bytes,
- CharsetEncoder encoder, Object lock) throws IOException {
- assertArrayIndex(buf.length, offset, count);
- CharBuffer chars = CharBuffer.wrap(buf, offset, count);
- convert(lock, encoder, bytes, chars, out);
- }
-
- /*
- * Flush method for OutputStreamWriter and Channels.
- */
- public static void flushOutputStreamWriter(OutputStream out,
- ByteBuffer bytes, CharsetEncoder encoder, Object lock)
- throws IOException {
- synchronized (lock) {
- checkEncoder(encoder);
- int position;
- if ((position = bytes.position()) > 0) {
- bytes.flip();
- out.write(bytes.array(), 0, position);
- bytes.clear();
- }
- out.flush();
- }
- }
-
- /*
- * Convert function used in write.
- */
- private static void convert(Object lock, CharsetEncoder encoder,
- ByteBuffer bytes, CharBuffer chars, OutputStream out)
- throws IOException {
- synchronized (lock) {
- checkEncoder(encoder);
- CoderResult result = encoder.encode(chars, bytes, true);
- while (true) {
- if (result.isError()) {
- throw new IOException(result.toString());
- } else if (result.isOverflow()) {
- // flush the output buffer
- flushOutputStreamWriter(out, bytes, encoder, lock);
- result = encoder.encode(chars, bytes, true);
- continue;
- }
- break;
- }
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/LockManager.java b/luni/src/main/java/org/apache/harmony/nio/internal/LockManager.java
deleted file mode 100644
index e1ba13d..0000000
--- a/luni/src/main/java/org/apache/harmony/nio/internal/LockManager.java
+++ /dev/null
@@ -1,80 +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.nio.internal;
-
-import java.nio.channels.FileLock;
-import java.nio.channels.OverlappingFileLockException;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-/**
- * The lock manager is responsible for tracking acquired and pending locks on
- * the underlying file channel.
- *
- */
-final class LockManager {
- // The set of acquired and pending locks.
- private final Comparator<FileLock> lockComparator = new Comparator<FileLock>() {
- public int compare(FileLock lock1, FileLock lock2) {
- long position1 = lock1.position();
- long position2 = lock2.position();
- return position1 > position2 ? 1 : (position1 < position2 ? -1 : 0);
- }
- };
-
- private final SortedSet<FileLock> locks = new TreeSet<FileLock>(
- lockComparator);
-
- /*
- * Default Constructor.
- */
- protected LockManager() {
- super();
- }
-
- /*
- * Add a new pending lock to the manager. Throws an exception if the lock
- * would overlap an existing lock. Once the lock is acquired it remains in
- * this set as an acquired lock.
- */
- synchronized void addLock(FileLock lock)
- throws OverlappingFileLockException {
- long lockEnd = lock.position() + lock.size();
- for (Iterator<FileLock> keyItr = locks.iterator(); keyItr.hasNext();) {
- FileLock existingLock = keyItr.next();
- if (existingLock.position() > lockEnd) {
- // This, and all remaining locks, start beyond our end (so
- // cannot overlap).
- break;
- }
- if (existingLock.overlaps(lock.position(), lock.size())) {
- throw new OverlappingFileLockException();
- }
- }
- locks.add(lock);
- }
-
- /*
- * Removes an acquired lock from the lock manager. If the lock did not exist
- * in the lock manager the operation is a no-op.
- */
- synchronized void removeLock(FileLock lock) {
- locks.remove(lock);
- }
-}
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/fortress/Engine.java b/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java
index c5bb376..7dbc476 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/Engine.java
@@ -28,40 +28,94 @@
/**
+ * This class implements common functionality for Provider supplied
+ * classes. The usage pattern is to allocate static Engine instance
+ * per service type and synchronize on that instance during calls to
+ * {@code getInstance} and retreival of the selected {@code Provider}
+ * and Service Provider Interface (SPI) results. Retreiving the
+ * results with {@code getProvider} and {@code getSpi} sets the
+ * internal {@code Engine} values to null to prevent memory leaks.
*
- * This class implements common functionality for all engine classes
+ * <p>
*
+ * For example: <pre> {@code
+ * public class Foo {
+ *
+ * private static final Engine ENGINE = new Engine("Foo");
+ *
+ * private final FooSpi spi;
+ * private final Provider provider;
+ * private final String algorithm;
+ *
+ * protected Foo(FooSpi spi,
+ * Provider provider,
+ * String algorithm) {
+ * this.spi = spi;
+ * this.provider = provider;
+ * this.algorithm = algorithm;
+ * }
+ *
+ * public static Foo getInstance(String algorithm) {
+ * Engine.SpiAndProvider sap = ENGINE.getInstance(algorithm, null);
+ * return new Foo((FooSpi) sap.spi, sap.provider, algorithm);
+ * }
+ *
+ * public static Foo getInstance(String algorithm, Provider provider) {
+ * Object spi = ENGINE.getInstance(algorithm, provider, null);
+ * return new Foo((FooSpi) spi, provider, algorithm);
+ * }
+ *
+ * ...
+ *
+ * }</pre>
*/
public class Engine {
- // Service name
- private final String serviceName;
-
- // for getInstance(String algorithm, Object param) optimization:
- // previous result
- private Provider.Service returnedService;
-
- // previous parameter
- private String lastAlgorithm;
-
- private int refreshNumber;
-
- /**
- * Provider
- */
- public Provider provider;
-
- /**
- * SPI instance
- */
- public Object spi;
-
/**
* Access to package visible api in java.security
*/
public static SecurityAccess door;
/**
+ * Service name such as Cipher or SSLContext
+ */
+ private final String serviceName;
+
+ /**
+ * Previous result for getInstance(String, Object) optimization.
+ * Only this non-Provider version of getInstance is optimized
+ * since the the Provider version does not require an expensive
+ * Services.getService call.
+ */
+ private volatile ServiceCacheEntry serviceCache;
+
+ private static final class ServiceCacheEntry {
+ /** used to test for cache hit */
+ private final String algorithm;
+ /** used to test for cache validity */
+ private final int refreshNumber;
+ /** cached result */
+ private final Provider.Service service;
+
+ private ServiceCacheEntry(String algorithm,
+ int refreshNumber,
+ Provider.Service service) {
+ this.algorithm = algorithm;
+ this.refreshNumber = refreshNumber;
+ this.service = service;
+ }
+ }
+
+ public static final class SpiAndProvider {
+ public final Object spi;
+ public final Provider provider;
+ private SpiAndProvider(Object spi, Provider provider) {
+ this.spi = spi;
+ this.provider = provider;
+ }
+ }
+
+ /**
* Creates a Engine object
*
* @param service
@@ -71,71 +125,60 @@
}
/**
- *
- * Finds the appropriate service implementation and creates instance of the
- * class that implements corresponding Service Provider Interface.
- *
- * @param algorithm
- * @param service
- * @throws NoSuchAlgorithmException
+ * Finds the appropriate service implementation and returns an
+ * {@code SpiAndProvider} instance containing a reference to SPI
+ * and its {@code Provider}
*/
- public synchronized void getInstance(String algorithm, Object param)
+ public SpiAndProvider getInstance(String algorithm, Object param)
throws NoSuchAlgorithmException {
- Provider.Service serv;
-
if (algorithm == null) {
throw new NoSuchAlgorithmException("Null algorithm name");
}
Services.refresh();
- if (returnedService != null
- && Util.equalsIgnoreCase(algorithm, lastAlgorithm)
- && refreshNumber == Services.refreshNumber) {
- serv = returnedService;
+ Provider.Service service;
+ ServiceCacheEntry cacheEntry = this.serviceCache;
+ if (cacheEntry != null
+ && Util.equalsIgnoreCase(algorithm, cacheEntry.algorithm)
+ && Services.refreshNumber != cacheEntry.refreshNumber) {
+ service = cacheEntry.service;
} else {
if (Services.isEmpty()) {
throw notFound(serviceName, algorithm);
}
- serv = Services.getService(new StringBuilder(128)
- .append(serviceName).append(".").append(
- Util.toUpperCase(algorithm)).toString());
- if (serv == null) {
+ String name = new StringBuilder(128)
+ .append(this.serviceName)
+ .append(".")
+ .append(Util.toUpperCase(algorithm))
+ .toString();
+ service = Services.getService(name);
+ if (service == null) {
throw notFound(serviceName, algorithm);
}
- returnedService = serv;
- lastAlgorithm = algorithm;
- refreshNumber = Services.refreshNumber;
+ this.serviceCache = new ServiceCacheEntry(algorithm, Services.refreshNumber, service);
}
- spi = serv.newInstance(param);
- this.provider = serv.getProvider();
- }
-
- private NoSuchAlgorithmException notFound(String serviceName, String algorithm) throws NoSuchAlgorithmException {
- throw new NoSuchAlgorithmException(serviceName + " " + algorithm + " implementation not found");
+ return new SpiAndProvider(service.newInstance(param), service.getProvider());
}
/**
- *
- * Finds the appropriate service implementation and creates instance of the
- * class that implements corresponding Service Provider Interface.
- *
- * @param algorithm
- * @param service
- * @param provider
- * @throws NoSuchAlgorithmException
+ * Finds the appropriate service implementation and returns and
+ * instance of the class that implements corresponding Service
+ * Provider Interface.
*/
- public synchronized void getInstance(String algorithm, Provider provider,
- Object param) throws NoSuchAlgorithmException {
-
- Provider.Service serv = null;
+ public Object getInstance(String algorithm, Provider provider, Object param)
+ throws NoSuchAlgorithmException {
if (algorithm == null) {
throw new NoSuchAlgorithmException("algorithm == null");
}
- serv = provider.getService(serviceName, algorithm);
- if (serv == null) {
+ Provider.Service service = provider.getService(serviceName, algorithm);
+ if (service == null) {
throw notFound(serviceName, algorithm);
}
- spi = serv.newInstance(param);
- this.provider = provider;
+ return service.newInstance(param);
}
+ private NoSuchAlgorithmException notFound(String serviceName, String algorithm)
+ throws NoSuchAlgorithmException {
+ throw new NoSuchAlgorithmException(serviceName + " " + algorithm
+ + " implementation not found");
+ }
}
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/cert/X509CertImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
index 5870f60..d8f79bc 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java
@@ -71,27 +71,26 @@
private final Certificate certificate;
// to speed up access to the info, the following fields
- // cache values retrieved from the certificate object
+ // cache values retrieved from the certificate object,
+ // initialized using the "single-check idiom".
private final TBSCertificate tbsCert;
private final Extensions extensions;
- private long notBefore = -1;
- private long notAfter;
- private BigInteger serialNumber;
- private X500Principal issuer;
- private X500Principal subject;
- private byte[] tbsCertificate;
- private byte[] signature;
- private String sigAlgName;
- private String sigAlgOID;
- private byte[] sigAlgParams;
+ private volatile long notBefore = -1;
+ private volatile long notAfter = -1;
+ private volatile BigInteger serialNumber;
+ private volatile X500Principal issuer;
+ private volatile X500Principal subject;
+ private volatile byte[] tbsCertificate;
+ private volatile byte[] signature;
+ private volatile String sigAlgName;
+ private volatile String sigAlgOID;
+ private volatile byte[] sigAlgParams;
// indicates whether the signature algorithm parameters are null
- private boolean nullSigAlgParams;
- private PublicKey publicKey;
+ private volatile boolean nullSigAlgParams;
+ private volatile PublicKey publicKey;
// encoding of the certificate
-// BEGIN android-changed
private volatile byte[] encoding;
-// END android-changed
//
// ---------------------- Constructors -------------------------------
@@ -144,20 +143,9 @@
* @see java.security.cert.X509Certificate#checkValidity()
* method documentation for more information.
*/
- public void checkValidity() throws CertificateExpiredException,
- CertificateNotYetValidException {
- if (notBefore == -1) {
- // retrieve and cache the value of validity period
- notBefore = tbsCert.getValidity().getNotBefore().getTime();
- notAfter = tbsCert.getValidity().getNotAfter().getTime();
- }
- long time = System.currentTimeMillis();
- if (time < notBefore) {
- throw new CertificateNotYetValidException();
- }
- if (time > notAfter) {
- throw new CertificateExpiredException();
- }
+ public void checkValidity()
+ throws CertificateExpiredException, CertificateNotYetValidException {
+ checkValidity(System.currentTimeMillis());
}
/**
@@ -165,25 +153,19 @@
* method documentation for more information.
*/
public void checkValidity(Date date)
- throws CertificateExpiredException,
- CertificateNotYetValidException {
- if (notBefore == -1) {
- // retrieve and cache the value of validity period
- notBefore = tbsCert.getValidity().getNotBefore().getTime();
- notAfter = tbsCert.getValidity().getNotAfter().getTime();
+ throws CertificateExpiredException, CertificateNotYetValidException {
+ checkValidity(date.getTime());
+ }
+
+ private void checkValidity(long time)
+ throws CertificateExpiredException, CertificateNotYetValidException {
+ if (time < getNotBeforeInternal()) {
+ throw new CertificateNotYetValidException("current time: " + new Date(time)
+ + ", validation time: " + new Date(getNotBeforeInternal()));
}
- long time = date.getTime();
- if (time < notBefore) {
- // BEGIN android-changed
- throw new CertificateNotYetValidException("current time: " + date
- + ", validation time: " + new Date(notBefore));
- // END android-changed
- }
- if (time > notAfter) {
- // BEGIN android-changed
- throw new CertificateExpiredException("current time: " + date
- + ", expiration time: " + new Date(notAfter));
- // END android-changed
+ if (time > getNotAfterInternal()) {
+ throw new CertificateExpiredException("current time: " + new Date(time)
+ + ", expiration time: " + new Date(getNotAfterInternal()));
}
}
@@ -200,10 +182,11 @@
* method documentation for more information.
*/
public BigInteger getSerialNumber() {
- if (serialNumber == null) {
- serialNumber = tbsCert.getSerialNumber();
+ BigInteger result = serialNumber;
+ if (result == null) {
+ serialNumber = result = tbsCert.getSerialNumber();
}
- return serialNumber;
+ return result;
}
/**
@@ -211,11 +194,7 @@
* method documentation for more information.
*/
public Principal getIssuerDN() {
- if (issuer == null) {
- // retrieve the issuer's principal
- issuer = tbsCert.getIssuer().getX500Principal();
- }
- return issuer;
+ return getIssuerX500Principal();
}
/**
@@ -223,11 +202,12 @@
* method documentation for more information.
*/
public X500Principal getIssuerX500Principal() {
- if (issuer == null) {
+ X500Principal result = issuer;
+ if (result == null) {
// retrieve the issuer's principal
- issuer = tbsCert.getIssuer().getX500Principal();
+ issuer = result = tbsCert.getIssuer().getX500Principal();
}
- return issuer;
+ return result;
}
/**
@@ -235,11 +215,7 @@
* method documentation for more information.
*/
public Principal getSubjectDN() {
- if (subject == null) {
- // retrieve the subject's principal
- subject = tbsCert.getSubject().getX500Principal();
- }
- return subject;
+ return getSubjectX500Principal();
}
/**
@@ -247,11 +223,12 @@
* method documentation for more information.
*/
public X500Principal getSubjectX500Principal() {
- if (subject == null) {
+ X500Principal result = subject;
+ if (result == null) {
// retrieve the subject's principal
- subject = tbsCert.getSubject().getX500Principal();
+ subject = result = tbsCert.getSubject().getX500Principal();
}
- return subject;
+ return result;
}
/**
@@ -259,12 +236,14 @@
* method documentation for more information.
*/
public Date getNotBefore() {
- if (notBefore == -1) {
- // the value was not retrieved from the certificate, do it:
- notBefore = tbsCert.getValidity().getNotBefore().getTime();
- notAfter = tbsCert.getValidity().getNotAfter().getTime();
+ return new Date(getNotBeforeInternal());
+ }
+ private long getNotBeforeInternal() {
+ long result = notBefore;
+ if (result == -1) {
+ notBefore = result = tbsCert.getValidity().getNotBefore().getTime();
}
- return new Date(notBefore);
+ return result;
}
/**
@@ -272,26 +251,28 @@
* method documentation for more information.
*/
public Date getNotAfter() {
- if (notBefore == -1) {
- // the value was not retrieved from the certificate, do it:
- notBefore = tbsCert.getValidity().getNotBefore().getTime();
- notAfter = tbsCert.getValidity().getNotAfter().getTime();
+ return new Date(getNotAfterInternal());
+ }
+ private long getNotAfterInternal() {
+ long result = notAfter;
+ if (result == -1) {
+ notAfter = result = tbsCert.getValidity().getNotAfter().getTime();
}
- return new Date(notAfter);
+ return result;
}
/**
* @see java.security.cert.X509Certificate#getTBSCertificate()
* method documentation for more information.
*/
- public byte[] getTBSCertificate()
- throws CertificateEncodingException {
- if (tbsCertificate == null) {
- // retrieve the encoded form of the TBSCertificate structure
- tbsCertificate = tbsCert.getEncoded();
+ public byte[] getTBSCertificate() throws CertificateEncodingException {
+ return getTbsCertificateInternal().clone();
+ }
+ private byte[] getTbsCertificateInternal() {
+ byte[] result = tbsCertificate;
+ if (result == null) {
+ tbsCertificate = result = tbsCert.getEncoded();
}
- byte[] result = new byte[tbsCertificate.length];
- System.arraycopy(tbsCertificate, 0, result, 0, tbsCertificate.length);
return result;
}
@@ -300,12 +281,13 @@
* method documentation for more information.
*/
public byte[] getSignature() {
- if (signature == null) {
- // retrieve the value of the signature
- signature = certificate.getSignatureValue();
+ return getSignatureInternal().clone();
+ }
+ private byte[] getSignatureInternal() {
+ byte[] result = signature;
+ if (result == null) {
+ signature = result = certificate.getSignatureValue();
}
- byte[] result = new byte[signature.length];
- System.arraycopy(signature, 0, result, 0, signature.length);
return result;
}
@@ -314,17 +296,18 @@
* method documentation for more information.
*/
public String getSigAlgName() {
- if (sigAlgOID == null) {
- // if info was not retrieved (and cached), do it:
- sigAlgOID = tbsCert.getSignature().getAlgorithm();
+ String result = sigAlgName;
+ if (result == null) {
+ String sigAlgOIDLocal = getSigAlgOID();
// retrieve the name of the signing algorithm
- sigAlgName = AlgNameMapper.map2AlgName(sigAlgOID);
- if (sigAlgName == null) {
+ result = AlgNameMapper.map2AlgName(sigAlgOIDLocal);
+ if (result == null) {
// if could not be found, use OID as a name
- sigAlgName = sigAlgOID;
+ result = sigAlgOIDLocal;
}
+ sigAlgName = result;
}
- return sigAlgName;
+ return result;
}
/**
@@ -332,17 +315,12 @@
* method documentation for more information.
*/
public String getSigAlgOID() {
- if (sigAlgOID == null) {
+ String result = sigAlgOID;
+ if (result == null) {
// if info was not retrieved (and cached), do it:
- sigAlgOID = tbsCert.getSignature().getAlgorithm();
- // retrieve the name of the signing algorithm
- sigAlgName = AlgNameMapper.map2AlgName(sigAlgOID);
- if (sigAlgName == null) {
- // if could not be found, use OID as a name
- sigAlgName = sigAlgOID;
- }
+ sigAlgOID = result = tbsCert.getSignature().getAlgorithm();
}
- return sigAlgOID;
+ return result;
}
/**
@@ -353,14 +331,16 @@
if (nullSigAlgParams) {
return null;
}
- if (sigAlgParams == null) {
- sigAlgParams = tbsCert.getSignature().getParameters();
- if (sigAlgParams == null) {
+ byte[] result = sigAlgParams;
+ if (result == null) {
+ result = tbsCert.getSignature().getParameters();
+ if (result == null) {
nullSigAlgParams = true;
return null;
}
+ sigAlgParams = result;
}
- return sigAlgParams;
+ return result;
}
/**
@@ -464,11 +444,13 @@
* method documentation for more information.
*/
public byte[] getEncoded() throws CertificateEncodingException {
+ return getEncodedInternal().clone();
+ }
+ private byte[] getEncodedInternal() throws CertificateEncodingException {
+ byte[] result = encoding;
if (encoding == null) {
- encoding = certificate.getEncoded();
+ encoding = result = certificate.getEncoded();
}
- byte[] result = new byte[encoding.length];
- System.arraycopy(encoding, 0, result, 0, encoding.length);
return result;
}
@@ -477,12 +459,11 @@
* method documentation for more information.
*/
public PublicKey getPublicKey() {
- if (publicKey == null) {
- // retrieve the public key from SubjectPublicKeyInfo
- // substructure of X.509 certificate
- publicKey = tbsCert.getSubjectPublicKeyInfo().getPublicKey();
+ PublicKey result = publicKey;
+ if (result == null) {
+ publicKey = result = tbsCert.getSubjectPublicKeyInfo().getPublicKey();
}
- return publicKey;
+ return result;
}
/**
@@ -502,22 +483,17 @@
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException {
-
- // BEGIN android-added
if (getSigAlgName().endsWith("withRSA")) {
fastVerify(key);
return;
}
- // END android-added
Signature signature = Signature.getInstance(getSigAlgName());
signature.initVerify(key);
// retrieve the encoding of the TBSCertificate structure
- if (tbsCertificate == null) {
- tbsCertificate = tbsCert.getEncoded();
- }
+ byte[] tbsCertificateLocal = getTbsCertificateInternal();
// compute and verify the signature
- signature.update(tbsCertificate, 0, tbsCertificate.length);
+ signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
if (!signature.verify(certificate.getSignatureValue())) {
throw new SignatureException("Signature was not verified");
}
@@ -532,29 +508,23 @@
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
SignatureException {
-
- // BEGIN android-added
if (getSigAlgName().endsWith("withRSA")) {
fastVerify(key);
return;
}
- // END android-added
Signature signature =
Signature.getInstance(getSigAlgName(), sigProvider);
signature.initVerify(key);
// retrieve the encoding of the TBSCertificate structure
- if (tbsCertificate == null) {
- tbsCertificate = tbsCert.getEncoded();
- }
+ byte[] tbsCertificateLocal = getTbsCertificateInternal();
// compute and verify the signature
- signature.update(tbsCertificate, 0, tbsCertificate.length);
+ signature.update(tbsCertificateLocal, 0, tbsCertificateLocal.length);
if (!signature.verify(certificate.getSignatureValue())) {
throw new SignatureException("Signature was not verified");
}
}
- // BEGIN android-added
/**
* Implements a faster RSA verification method that delegates to OpenSSL
* native code. In all other aspects it behaves just like the ordinary
@@ -586,16 +556,12 @@
int i = algorithm.indexOf("with");
algorithm = algorithm.substring(i + 4) + "-" + algorithm.substring(0, i);
- if (tbsCertificate == null) {
- tbsCertificate = tbsCert.getEncoded();
- }
-
+ byte[] tbsCertificateLocal = getTbsCertificateInternal();
byte[] sig = certificate.getSignatureValue();
- if (!NativeCrypto.verifySignature(tbsCertificate, sig, algorithm, rsaKey)) {
+ if (!NativeCrypto.verifySignature(tbsCertificateLocal, sig, algorithm, rsaKey)) {
throw new SignatureException("Signature was not verified");
}
}
- // END android-added
//
// ----- java.security.cert.X509Extension methods implementations ----
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
index 8d5f247..e961d1f 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertPathImpl.java
@@ -83,10 +83,8 @@
public static final int PKCS7 = 1;
// supported encoding names
- private static final String[] encodingsArr =
- new String[] {"PkiPath", "PKCS7"};
- static final List encodings = Collections.unmodifiableList(
- Arrays.asList(encodingsArr));
+ private static final String[] encodingsArr = new String[] {"PkiPath", "PKCS7"};
+ static final List encodings = Collections.unmodifiableList(Arrays.asList(encodingsArr));
// the list of certificates representing this certification path
private final List certificates;
// PkiPath encoding of the certification path
@@ -107,7 +105,8 @@
for (int i=0; i<size; i++) {
Object cert = certs.get(i);
if (!(cert instanceof X509Certificate) ) {
- throw new CertificateException("One of the provided certificates is not an X509 certificate");
+ throw new CertificateException(
+ "One of the provided certificates is not an X509 certificate");
}
certificates.add(cert);
}
@@ -140,8 +139,7 @@
* @throws CertificateException if some problems occurred during
* the decoding.
*/
- public static X509CertPathImpl getInstance(InputStream in)
- throws CertificateException {
+ public static X509CertPathImpl getInstance(InputStream in) throws CertificateException {
try {
return (X509CertPathImpl) ASN1.decode(in);
} catch (IOException e) {
@@ -157,7 +155,7 @@
* or some problems occurred during the decoding.
*/
public static X509CertPathImpl getInstance(InputStream in, String encoding)
- throws CertificateException {
+ throws CertificateException {
if (!encodings.contains(encoding)) {
throw new CertificateException("Unsupported encoding");
}
@@ -170,7 +168,8 @@
ContentInfo ci = (ContentInfo) ContentInfo.ASN1.decode(in);
SignedData sd = ci.getSignedData();
if (sd == null) {
- throw new CertificateException("Incorrect PKCS7 encoded form: missing signed data");
+ throw new CertificateException(
+ "Incorrect PKCS7 encoded form: missing signed data");
}
List certs = sd.getCertificates();
if (certs == null) {
@@ -194,8 +193,7 @@
* @throws CertificateException if some problems occurred during
* the decoding.
*/
- public static X509CertPathImpl getInstance(byte[] in)
- throws CertificateException {
+ public static X509CertPathImpl getInstance(byte[] in) throws CertificateException {
try {
return (X509CertPathImpl) ASN1.decode(in);
} catch (IOException e) {
@@ -211,7 +209,7 @@
* or some problems occurred during the decoding.
*/
public static X509CertPathImpl getInstance(byte[] in, String encoding)
- throws CertificateException {
+ throws CertificateException {
if (!encodings.contains(encoding)) {
throw new CertificateException("Unsupported encoding");
}
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/AttributeTypeAndValue.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java
index d386c84..6dbf416 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValue.java
@@ -244,7 +244,7 @@
private final ObjectIdentifier oid;
//Attribute value
- private AttributeValue value;
+ private final AttributeValue value;
// for decoder only
private AttributeTypeAndValue(int[] oid, AttributeValue value)
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/text/BidiRun.java b/luni/src/main/java/org/apache/harmony/text/BidiRun.java
index 8cbe8d1..b1490ef 100644
--- a/luni/src/main/java/org/apache/harmony/text/BidiRun.java
+++ b/luni/src/main/java/org/apache/harmony/text/BidiRun.java
@@ -44,12 +44,4 @@
public int getStart() {
return start;
}
-
- @Override
- public boolean equals(Object o) {
- return o == null || o.getClass() != BidiRun.class ? false
- : this.start == ((BidiRun) o).start
- && this.limit == ((BidiRun) o).limit
- && this.level == ((BidiRun) o).level;
- }
}
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/AbstractSessionContext.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
index 90035d4..8ee8a33 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
@@ -158,7 +158,7 @@
* Called when a session is removed. Used by ClientSessionContext
* to update its host-and-port based cache.
*/
- abstract protected void sessionRemoved(SSLSession session);
+ protected abstract void sessionRemoved(SSLSession session);
public final void setSessionCacheSize(int size)
throws IllegalArgumentException {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
index f712d11..0457885 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
@@ -524,7 +524,7 @@
/**
* Creates CipherSuite
*/
- public CipherSuite(String name, boolean isExportable, int keyExchange,
+ private CipherSuite(String name, boolean isExportable, int keyExchange,
String authType, String cipherName, String hash, byte[] code) {
this.name = name;
this.keyExchange = keyExchange;
@@ -690,19 +690,6 @@
}
/**
- * Compares this cipher suite to the specified object.
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof CipherSuite
- && this.cipherSuiteCode[0] == ((CipherSuite) obj).cipherSuiteCode[0]
- && this.cipherSuiteCode[1] == ((CipherSuite) obj).cipherSuiteCode[1]) {
- return true;
- }
- return false;
- }
-
- /**
* Returns cipher algorithm name
* @return
*/
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/Finished.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
index 9cc988c..fc89d48 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
@@ -50,7 +50,7 @@
throws IOException {
if (length == 12 || length == 36) {
data = in.read(length);
- length = data.length;
+ this.length = data.length;
} else {
fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect Finished");
}
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/IndexedPKIXParameters.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/IndexedPKIXParameters.java
index 30556fe..c48e331 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/IndexedPKIXParameters.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/IndexedPKIXParameters.java
@@ -17,7 +17,9 @@
package org.apache.harmony.xnet.provider.jsse;
import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
import java.security.KeyStoreException;
+import java.security.PublicKey;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.PKIXParameters;
@@ -25,12 +27,11 @@
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import javax.security.auth.x500.X500Principal;
/**
@@ -38,80 +39,65 @@
*/
public class IndexedPKIXParameters extends PKIXParameters {
- final Map<Bytes, TrustAnchor> encodings
- = new HashMap<Bytes, TrustAnchor>();
- final Map<X500Principal, TrustAnchor> bySubject
- = new HashMap<X500Principal, TrustAnchor>();
- final Map<X500Principal, List<TrustAnchor>> byCA
+ private final Map<X500Principal, List<TrustAnchor>> subjectToTrustAnchors
= new HashMap<X500Principal, List<TrustAnchor>>();
public IndexedPKIXParameters(Set<TrustAnchor> anchors)
- throws KeyStoreException, InvalidAlgorithmParameterException,
- CertificateEncodingException {
+ throws InvalidAlgorithmParameterException {
super(anchors);
+ index();
+ }
- for (TrustAnchor anchor : anchors) {
+ public IndexedPKIXParameters(KeyStore keyStore)
+ throws KeyStoreException, InvalidAlgorithmParameterException {
+ super(keyStore);
+ index();
+ }
+
+ private void index() {
+ for (TrustAnchor anchor : getTrustAnchors()) {
+ X500Principal subject;
X509Certificate cert = anchor.getTrustedCert();
-
- Bytes encoded = new Bytes(cert.getEncoded());
- encodings.put(encoded, anchor);
-
- X500Principal subject = cert.getSubjectX500Principal();
- if (bySubject.put(subject, anchor) != null) {
- // TODO: Should we allow this?
- throw new KeyStoreException("Two certs have the same subject: "
- + subject);
+ if (cert != null) {
+ subject = cert.getSubjectX500Principal();
+ } else {
+ subject = anchor.getCA();
}
- X500Principal ca = anchor.getCA();
- List<TrustAnchor> caAnchors = byCA.get(ca);
- if (caAnchors == null) {
- caAnchors = new ArrayList<TrustAnchor>();
- byCA.put(ca, caAnchors);
+ List<TrustAnchor> anchors = subjectToTrustAnchors.get(subject);
+ if (anchors == null) {
+ anchors = new ArrayList<TrustAnchor>();
+ subjectToTrustAnchors.put(subject, anchors);
}
- caAnchors.add(anchor);
+ anchors.add(anchor);
}
}
public TrustAnchor findTrustAnchor(X509Certificate cert)
throws CertPathValidatorException {
- // Mimic the alg in CertPathValidatorUtilities.findTrustAnchor().
- Exception verificationException = null;
X500Principal issuer = cert.getIssuerX500Principal();
-
- List<TrustAnchor> anchors = byCA.get(issuer);
- if (anchors != null) {
- for (TrustAnchor caAnchor : anchors) {
- try {
- cert.verify(caAnchor.getCAPublicKey());
- return caAnchor;
- } catch (Exception e) {
- verificationException = e;
- }
- }
+ List<TrustAnchor> anchors = subjectToTrustAnchors.get(issuer);
+ if (anchors == null) {
+ return null;
}
- TrustAnchor anchor = bySubject.get(issuer);
- if (anchor != null) {
+ Exception verificationException = null;
+ for (TrustAnchor anchor : anchors) {
+ PublicKey publicKey;
try {
- cert.verify(anchor.getTrustedCert().getPublicKey());
+ X509Certificate caCert = anchor.getTrustedCert();
+ if (caCert != null) {
+ publicKey = caCert.getPublicKey();
+ } else {
+ publicKey = anchor.getCAPublicKey();
+ }
+ cert.verify(publicKey);
return anchor;
} catch (Exception e) {
verificationException = e;
}
}
- try {
- Bytes encoded = new Bytes(cert.getEncoded());
- anchor = encodings.get(encoded);
- if (anchor != null) {
- return anchor;
- }
- } catch (Exception e) {
- Logger.getLogger(IndexedPKIXParameters.class.getName()).log(
- Level.WARNING, "Error encoding cert.", e);
- }
-
// Throw last verification exception.
if (verificationException != null) {
throw new CertPathValidatorException("TrustAnchor found but"
@@ -122,19 +108,34 @@
return null;
}
- /**
- * Returns true if the given certificate is found in the trusted key
- * store.
- */
- public boolean isDirectlyTrusted(X509Certificate cert) {
- try {
- Bytes encoded = new Bytes(cert.getEncoded());
- return encodings.containsKey(encoded);
- } catch (Exception e) {
- Logger.getLogger(IndexedPKIXParameters.class.getName()).log(
- Level.WARNING, "Error encoding cert.", e);
+ public boolean isTrustAnchor(X509Certificate cert) {
+ X500Principal subject = cert.getSubjectX500Principal();
+ List<TrustAnchor> anchors = subjectToTrustAnchors.get(subject);
+ if (anchors == null) {
return false;
}
+ return isTrustAnchor(cert, anchors);
+ }
+
+ public static boolean isTrustAnchor(X509Certificate cert, Collection<TrustAnchor> anchors) {
+ PublicKey certPublicKey = cert.getPublicKey();
+ for (TrustAnchor anchor : anchors) {
+ PublicKey caPublicKey;
+ try {
+ X509Certificate caCert = anchor.getTrustedCert();
+ if (caCert != null) {
+ caPublicKey = caCert.getPublicKey();
+ } else {
+ caPublicKey = anchor.getCAPublicKey();
+ }
+ if (caPublicKey.equals(certPublicKey)) {
+ return true;
+ }
+ } catch (Exception e) {
+ // can happen with unsupported public key types
+ }
+ }
+ return false;
}
/**
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
index 756030b..41c58b6 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
@@ -24,23 +24,25 @@
public class OpenSSLSocketFactoryImpl extends javax.net.ssl.SSLSocketFactory {
- private SSLParametersImpl sslParameters;
- private IOException instantiationException;
+ private final SSLParametersImpl sslParameters;
+ private final IOException instantiationException;
public OpenSSLSocketFactoryImpl() {
- super();
+ SSLParametersImpl sslParametersLocal = null;
+ IOException instantiationExceptionLocal = null;
try {
- sslParameters = SSLParametersImpl.getDefault();
+ sslParametersLocal = SSLParametersImpl.getDefault();
} catch (KeyManagementException e) {
- instantiationException =
- new IOException("Delayed instantiation exception:");
- instantiationException.initCause(e);
+ instantiationExceptionLocal = new IOException("Delayed instantiation exception:");
+ instantiationExceptionLocal.initCause(e);
}
+ this.sslParameters = sslParametersLocal;
+ this.instantiationException = instantiationExceptionLocal;
}
public OpenSSLSocketFactoryImpl(SSLParametersImpl sslParameters) {
- super();
this.sslParameters = sslParameters;
+ this.instantiationException = null;
}
public String[] getDefaultCipherSuites() {
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 3bd59a9..1aab4ea 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
@@ -100,16 +103,6 @@
private String wrappedHost;
private int wrappedPort;
- private static final AtomicInteger instanceCount = new AtomicInteger(0);
-
- public static int getInstanceCount() {
- return instanceCount.get();
- }
-
- private static void updateInstanceCount(int amount) {
- instanceCount.addAndGet(amount);
- }
-
/**
* Class constructor with 1 parameter
*
@@ -246,7 +239,6 @@
this.enabledProtocols = enabledProtocols;
this.enabledCipherSuites = enabledCipherSuites;
this.enabledCompressionMethods = enabledCompressionMethods;
- updateInstanceCount(1);
}
/**
@@ -369,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();
+ }
}
}
@@ -653,9 +659,7 @@
}
X509Certificate[] peerCertificateChain = new X509Certificate[bytes.length];
for (int i = 0; i < bytes.length; i++) {
- peerCertificateChain[i] =
- new X509CertImpl(
- javax.security.cert.X509Certificate.getInstance(bytes[i]).getEncoded());
+ peerCertificateChain[i] = new X509CertImpl(bytes[i]);
}
boolean client = sslParameters.getUseClientMode();
if (client) {
@@ -854,7 +858,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;
@@ -1268,6 +1271,7 @@
}
NativeCrypto.SSL_free(sslNativePointer);
sslNativePointer = 0;
+ guard.close();
}
@Override protected void finalize() throws Throwable {
@@ -1288,7 +1292,9 @@
* and will write the close notify to some unsuspecting
* reader.
*/
- updateInstanceCount(-1);
+ if (guard != null) {
+ guard.warnIfOpen();
+ }
free();
} finally {
super.finalize();
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
index 99eb9b4..230f9fe 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
@@ -112,13 +112,13 @@
/**
* SSL 3.0 protocol version
*/
- public static ProtocolVersion SSLv3 = new ProtocolVersion("SSLv3",
+ public static final ProtocolVersion SSLv3 = new ProtocolVersion("SSLv3",
new byte[] { 3, 0 });
/**
* TLS 1.0 protocol version
*/
- public static ProtocolVersion TLSv1 = new ProtocolVersion("TLSv1",
+ public static final ProtocolVersion TLSv1 = new ProtocolVersion("TLSv1",
new byte[] { 3, 1 });
static {
@@ -142,17 +142,4 @@
this.name = name;
this.version = version;
}
-
- /**
- * Compares this ProtocolVersion to the specified object.
- */
- @Override
- public boolean equals(Object o) {
- if (o instanceof ProtocolVersion
- && this.version[0] == ((ProtocolVersion) o).version[0]
- && this.version[1] == ((ProtocolVersion) o).version[1]) {
- return true;
- }
- return false;
- }
}
\ No newline at end of file
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/SSLParametersImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParametersImpl.java
index f6db4b2..405e5dd 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParametersImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParametersImpl.java
@@ -425,20 +425,11 @@
tmf.init((KeyStore) null);
TrustManager[] tms = tmf.getTrustManagers();
X509TrustManager trustManager = findX509TrustManager(tms);
- // BEGIN android-added
- if (trustManager instanceof TrustManagerImpl) {
- ((TrustManagerImpl) trustManager).indexTrustAnchors();
- }
- // END android-added
return trustManager;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (KeyStoreException e) {
return null;
- } catch (CertificateEncodingException e) {
- return null;
- } catch (InvalidAlgorithmParameterException e) {
- return null;
}
}
private static X509TrustManager findX509TrustManager(TrustManager[] tms) {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
index 7a1683a..abec7d1 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
@@ -36,11 +36,11 @@
* getChangeCipherSpecMesage method).
* For server side mode record protocol retrieves the parameters from
* handshake protocol after receiving of client's change_cipher_spec message.
- * After the pending session has been setted up as a curent session,
- * new connectin state object is created and used for encryption/decryption
+ * After the pending session has been set up as a current session,
+ * new connection state object is created and used for encryption/decryption
* of the messages.
* Among with base functionality this class provides the information about
- * constrains on the data length, and information about correspondance
+ * constrains on the data length, and information about correspondence
* of plain and encrypted data lengths.
* For more information on TLS v1 see http://www.ietf.org/rfc/rfc2246.txt,
* on SSL v3 see http://wp.netscape.com/eng/ssl3,
@@ -52,24 +52,24 @@
* Maximum length of allowed plain data fragment
* as specified by TLS specification.
*/
- protected static int MAX_DATA_LENGTH = 16384; // 2^14
+ protected static final int MAX_DATA_LENGTH = 16384; // 2^14
/**
* Maximum length of allowed compressed data fragment
* as specified by TLS specification.
*/
- protected static int MAX_COMPRESSED_DATA_LENGTH
+ protected static final int MAX_COMPRESSED_DATA_LENGTH
= MAX_DATA_LENGTH + 1024;
/**
* Maximum length of allowed ciphered data fragment
* as specified by TLS specification.
*/
- protected static int MAX_CIPHERED_DATA_LENGTH
+ protected static final int MAX_CIPHERED_DATA_LENGTH
= MAX_COMPRESSED_DATA_LENGTH + 1024;
/**
* Maximum length of ssl record. It is counted as:
* type(1) + version(2) + length(2) + MAX_CIPHERED_DATA_LENGTH
*/
- protected static int MAX_SSL_PACKET_SIZE
+ protected static final int MAX_SSL_PACKET_SIZE
= MAX_CIPHERED_DATA_LENGTH + 5;
// the SSL session used for connection
private SSLSessionImpl session;
@@ -79,7 +79,7 @@
private SSLInputStream in;
// handshake protocol object to which handshaking data will be transmitted
private HandshakeProtocol handshakeProtocol;
- // alert protocol to indicate alerts occured/received
+ // alert protocol to indicate alerts occurred/received
private AlertProtocol alertProtocol;
// application data object to which application data will be transmitted
private org.apache.harmony.xnet.provider.jsse.Appendable appData;
@@ -119,7 +119,7 @@
/**
* Returns the session obtained during the handshake negotiation.
- * If the handshake process was not compleated, method returns null.
+ * If the handshake process was not completed, method returns null.
* @return the session in effect.
*/
protected SSLSessionImpl getSession() {
@@ -148,7 +148,7 @@
int res = 5 + activeWriteState.getFragmentSize(data_size);
return (res > MAX_CIPHERED_DATA_LENGTH)
? MAX_CIPHERED_DATA_LENGTH // so the source data should be
- // splitted into several packets
+ // split into several packets
: res;
}
}
@@ -178,7 +178,6 @@
* Depending on the Connection State (Session) encrypts and compress
* the provided data, and packs it into TLSCiphertext structure.
* @param content_type: int
- * @param fragment: byte[]
* @return ssl packet created over the current connection state
*/
protected byte[] wrap(byte content_type, DataStream dataStream) {
@@ -318,10 +317,10 @@
* In addition this method can recognize SSLv2 hello message which
* are often used to establish the SSL/TLS session.
*
- * @throws IOException if some io errors have been occured
+ * @throws IOException if some io errors have been occurred
* @throws EndOfSourceException if underlying input stream
* has ran out of data.
- * @throws EndOfBufferException if there was not enought data
+ * @throws EndOfBufferException if there was not enough data
* to build complete ssl packet.
* @return the type of unwrapped message.
*/
@@ -452,7 +451,7 @@
}
/**
- * Shutdownes the protocol. It will be impossiblke to use the instance
+ * Shuts down the protocol. It will be impossible to use the instance
* after the calling of this method.
*/
protected void shutdown() {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketFactoryImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketFactoryImpl.java
index 2701f5d..4e185fd 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketFactoryImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketFactoryImpl.java
@@ -29,29 +29,31 @@
*/
public class SSLSocketFactoryImpl extends SSLSocketFactory {
- private SSLParametersImpl sslParameters;
- private IOException instantiationException;
+ private final SSLParametersImpl sslParameters;
+ private final IOException instantiationException;
/**
* Constructor.
*/
public SSLSocketFactoryImpl() {
- super();
+ SSLParametersImpl sslParametersLocal = null;
+ IOException instantiationExceptionLocal = null;
try {
- sslParameters = SSLParametersImpl.getDefault();
+ sslParametersLocal = SSLParametersImpl.getDefault();
} catch (KeyManagementException e) {
- instantiationException =
- new IOException("Delayed instantiation exception:");
- instantiationException.initCause(e);
+ instantiationExceptionLocal = new IOException("Delayed instantiation exception:");
+ instantiationExceptionLocal.initCause(e);
}
+ this.sslParameters = sslParametersLocal;
+ this.instantiationException = instantiationExceptionLocal;
}
/**
* Constructor.
*/
protected SSLSocketFactoryImpl(SSLParametersImpl sslParameters) {
- super();
this.sslParameters = sslParameters;
+ this.instantiationException = null;
}
/**
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/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
index 8ccf085..a767c94 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
@@ -20,6 +20,7 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
+import java.security.PublicKey;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorException;
@@ -29,10 +30,11 @@
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
-import java.util.Iterator;
+import java.util.List;
import java.util.Set;
import javax.net.ssl.X509TrustManager;
@@ -46,13 +48,13 @@
*/
public class TrustManagerImpl implements X509TrustManager {
- private CertPathValidator validator;
+ private final CertPathValidator validator;
- private PKIXParameters params;
+ private final PKIXParameters params;
- private Exception err = null;
+ private final Exception err;
- private CertificateFactory factory;
+ private final CertificateFactory factory;
/**
* Creates trust manager implementation
@@ -60,74 +62,31 @@
* @param ks
*/
public TrustManagerImpl(KeyStore ks) {
+ CertPathValidator validatorLocal = null;
+ CertificateFactory factoryLocal = null;
+ PKIXParameters paramsLocal = null;
+ Exception errLocal = null;
try {
- validator = CertPathValidator.getInstance("PKIX");
- factory = CertificateFactory.getInstance("X509");
- byte[] nameConstrains = null;
- Set<TrustAnchor> trusted = new HashSet<TrustAnchor>();
- for (Enumeration<String> en = ks.aliases(); en.hasMoreElements();) {
- final String alias = en.nextElement();
- final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
- if (cert != null) {
- trusted.add(new TrustAnchor(cert, nameConstrains));
- }
- }
- params = new PKIXParameters(trusted);
- params.setRevocationEnabled(false);
+ validatorLocal = CertPathValidator.getInstance("PKIX");
+ factoryLocal = CertificateFactory.getInstance("X509");
+ paramsLocal = new IndexedPKIXParameters(ks);
+ paramsLocal.setRevocationEnabled(false);
} catch (Exception e) {
- err = e;
+ errLocal = e;
}
+ this.validator = validatorLocal;
+ this.factory = factoryLocal;
+ this.params = paramsLocal;
+ this.err = errLocal;
}
-// BEGIN android-added
- /**
- * Indexes trust anchors so they can be found in O(1) instead of O(N) time.
- */
- public void indexTrustAnchors() throws CertificateEncodingException,
- InvalidAlgorithmParameterException, KeyStoreException {
- params = new IndexedPKIXParameters(params.getTrustAnchors());
- params.setRevocationEnabled(false);
- }
-// END android-added
-
/**
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
* String)
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
- if (chain == null || chain.length == 0 || authType == null
- || authType.length() == 0) {
- throw new IllegalArgumentException("null or zero-length parameter");
- }
- if (err != null) {
- throw new CertificateException(err);
- }
- // BEGIN android-added
- // Caters to degenerate special case where we can't
- // establish an actual certificate chain the usual way,
- // but have the peer certificate in our trust store.
- if (isDirectlyTrustedCert(chain)) {
- return;
- }
- // END android-added
- try {
- // BEGIN android-changed
- CertPath certPath = factory.generateCertPath(Arrays.asList(chain));
- if (!Arrays.equals(chain[0].getEncoded(),
- ((X509Certificate)certPath.getCertificates().get(0))
- .getEncoded())) {
- // Sanity check failed (shouldn't ever happen, but we
- // are using pretty remote code)
- throw new CertificateException("Certificate chain error");
- }
- validator.validate(certPath, params);
- // END android-changed
- } catch (InvalidAlgorithmParameterException e) {
- throw new CertificateException(e);
- } catch (CertPathValidatorException e) {
- throw new CertificateException(e);
- }
+ checkTrusted(chain, authType);
}
/**
@@ -136,79 +95,112 @@
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
- if (chain == null || chain.length == 0 || authType == null
- || authType.length() == 0) {
+ checkTrusted(chain, authType);
+ }
+
+ private void checkTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ if (chain == null || chain.length == 0 || authType == null || authType.length() == 0) {
throw new IllegalArgumentException("null or zero-length parameter");
}
if (err != null) {
throw new CertificateException(err);
}
- // BEGIN android-changed
- CertificateException ce = null;
+
+ X509Certificate[] newChain = cleanupCertChain(chain);
+ if (newChain.length == 0) {
+ // chain was entirely trusted, skip the validator
+ return;
+ }
+ CertPath certPath = factory.generateCertPath(Arrays.asList(newChain));
+ if (!Arrays.equals(chain[0].getEncoded(),
+ certPath.getCertificates().get(0).getEncoded())) {
+ // Sanity check failed (shouldn't ever happen, but we
+ // are using pretty remote code)
+ throw new CertificateException("Certificate chain error");
+ }
try {
- CertPath certPath = factory.generateCertPath(Arrays.asList(chain));
- if (!Arrays.equals(chain[0].getEncoded(),
- certPath.getCertificates().get(0).getEncoded())) {
- // Sanity check failed (shouldn't ever happen, but we
- // are using pretty remote code)
- throw new CertificateException("Certificate chain error");
- }
validator.validate(certPath, params);
- // END android-changed
} catch (InvalidAlgorithmParameterException e) {
- ce = new CertificateException(e);
+ throw new CertificateException(e);
} catch (CertPathValidatorException e) {
- ce = new CertificateException(e);
+ throw new CertificateException(e);
}
- // BEGIN android-added
- if (ce != null) {
- // Caters to degenerate special case where we can't
- // establish an actual certificate chain the usual way
- // but have the peer certificate in our trust store.
- if (!isDirectlyTrustedCert(chain)) {
- throw ce;
- }
- }
- // END android-added
}
/**
- * Checks whether the given chain is just a certificate
- * that we have in our trust store.
- *
- * @param chain The certificate chain.
- *
- * @return True if the certificate is in our trust store, false otherwise.
+ * Clean up the certificate chain, returning a cleaned up chain,
+ * which may be a new array instance if elements were removed.
+ * Theoretically, we shouldn't have to do this, but various web
+ * servers in practice are mis-configured to have out-of-order
+ * certificates, expired self-issued root certificate, or CAs with
+ * unsupported signature algorithms such as
+ * md2WithRSAEncryption. This also handles removing old certs
+ * after bridge CA certs.
*/
- private boolean isDirectlyTrustedCert(X509Certificate[] chain) {
- byte[] questionable;
+ private X509Certificate[] cleanupCertChain(X509Certificate[] chain) {
+ X509Certificate[] original = chain;
- if (chain.length == 1) {
- if (params instanceof IndexedPKIXParameters) {
- IndexedPKIXParameters index = (IndexedPKIXParameters) params;
- return index.isDirectlyTrusted(chain[0]);
- } else {
- try {
- questionable = chain[0].getEncoded();
- Set<TrustAnchor> anchors = params.getTrustAnchors();
-
- for (TrustAnchor trustAnchor : anchors) {
- byte[] trusted = trustAnchor.getTrustedCert()
- .getEncoded();
- if (Arrays.equals(questionable, trusted)) {
- return true;
+ // 1. Clean the received certificates chain.
+ int currIndex;
+ // Start with the first certificate in the chain, assuming it
+ // is the leaf certificate (server or client cert).
+ for (currIndex = 0; currIndex < chain.length; currIndex++) {
+ // If the current cert is a TrustAnchor, we can ignore the rest of the chain.
+ // This avoids including "bridge" CA certs that added for legacy compatability.
+ if (isTrustAnchor(chain[currIndex])) {
+ currIndex--;
+ break;
+ }
+ // Walk the rest of the chain to find a "subject" matching
+ // the "issuer" of the current certificate. In a properly
+ // order chain this should be the next cert and be fast.
+ // If not, we reorder things to be as the validator will
+ // expect.
+ boolean foundNext = false;
+ for (int nextIndex = currIndex + 1; nextIndex < chain.length; nextIndex++) {
+ if (chain[currIndex].getIssuerDN().equals(chain[nextIndex].getSubjectDN())) {
+ foundNext = true;
+ // Exchange certificates so that 0 through currIndex + 1 are in proper order
+ if (nextIndex != currIndex + 1) {
+ // don't mutuate original chain, which may be directly from an SSLSession
+ if (chain == original) {
+ chain = original.clone();
}
+ X509Certificate tempCertificate = chain[nextIndex];
+ chain[nextIndex] = chain[currIndex + 1];
+ chain[currIndex + 1] = tempCertificate;
}
- } catch (CertificateEncodingException e) {
- // Ignore.
+ break;
}
}
-
+ // If we can't find the next in the chain, just give up
+ // and use what we found so far. This drops unrelated
+ // certificates that have nothing to do with the cert
+ // chain.
+ if (!foundNext) {
+ break;
+ }
}
- return false;
+ // 2. If the chain is now shorter, copy to an appropriately sized array.
+ int chainLength = currIndex + 1;
+ if (chainLength == chain.length) {
+ return chain;
+ }
+ return Arrays.copyOf(chain, chainLength);
}
-// END android-changed
+
+ /**
+ * Checks whether the given certificate is found in our trust store.
+ */
+ private boolean isTrustAnchor(X509Certificate cert) {
+ if (params instanceof IndexedPKIXParameters) {
+ IndexedPKIXParameters index = (IndexedPKIXParameters) params;
+ return index.isTrustAnchor(cert);
+ }
+ return IndexedPKIXParameters.isTrustAnchor(cert, params.getTrustAnchors());
+ }
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
@@ -218,12 +210,14 @@
return new X509Certificate[0];
}
Set<TrustAnchor> anchors = params.getTrustAnchors();
- X509Certificate[] certs = new X509Certificate[anchors.size()];
- int i = 0;
- for (Iterator<TrustAnchor> it = anchors.iterator(); it.hasNext();) {
- certs[i++] = it.next().getTrustedCert();
+ List<X509Certificate> certs = new ArrayList<X509Certificate>(anchors.size());
+ for (TrustAnchor trustAnchor : anchors) {
+ X509Certificate cert = trustAnchor.getTrustedCert();
+ if (cert != null) {
+ certs.add(cert);
+ }
}
- return certs;
+ return certs.toArray(new X509Certificate[certs.size()]);
}
}
diff --git a/luni/src/main/java/sun/misc/Unsafe.java b/luni/src/main/java/sun/misc/Unsafe.java
index 6cd0519..1080414 100644
--- a/luni/src/main/java/sun/misc/Unsafe.java
+++ b/luni/src/main/java/sun/misc/Unsafe.java
@@ -258,10 +258,7 @@
/**
* Lazy set an int field.
*/
- public void putOrderedInt(Object obj, long offset, int newValue) {
- // TODO: this should be an intrinsic that executes a store fence followed by a write
- putIntVolatile(obj, offset, newValue);
- }
+ public native void putOrderedInt(Object obj, long offset, int newValue);
/**
* Gets a <code>long</code> field from the given object.
@@ -284,10 +281,7 @@
/**
* Lazy set a long field.
*/
- public void putOrderedLong(Object obj, long offset, long newValue) {
- // TODO: this should be an intrinsic that executes a store fence followed by a write
- putLongVolatile(obj, offset, newValue);
- }
+ public native void putOrderedLong(Object obj, long offset, long newValue);
/**
* Gets an <code>Object</code> field from the given object.
@@ -310,10 +304,8 @@
/**
* Lazy set an object field.
*/
- public void putOrderedObject(Object obj, long offset, Object newValue) {
- // TODO: this should be an intrinsic that executes a store fence followed by a write
- putObjectVolatile(obj, offset, newValue);
- }
+ public native void putOrderedObject(Object obj, long offset,
+ Object newValue);
/**
* Parks the calling thread for the specified amount of time,
diff --git a/luni/src/main/native/ICU.cpp b/luni/src/main/native/ICU.cpp
index 04f6631..7e05978 100644
--- a/luni/src/main/native/ICU.cpp
+++ b/luni/src/main/native/ICU.cpp
@@ -353,21 +353,6 @@
return result;
}
-static jstring getIntCurrencyCode(JNIEnv* env, jstring locale) {
- ScopedUtfChars localeChars(env, locale);
-
- // Extract the 2-character country name.
- if (strlen(localeChars.c_str()) < 5) {
- return NULL;
- }
- if (localeChars[3] < 'A' || localeChars[3] > 'Z' || localeChars[4] < 'A' || localeChars[4] > 'Z') {
- return NULL;
- }
-
- char country[3] = { localeChars[3], localeChars[4], 0 };
- return ICU_getCurrencyCodeNative(env, NULL, env->NewStringUTF(country));
-}
-
static void setIntegerField(JNIEnv* env, jobject obj, const char* fieldName, int value) {
ScopedLocalRef<jobject> integerValue(env, integerValueOf(env, value));
jfieldID fid = env->GetFieldID(JniConstants::localeDataClass, fieldName, "Ljava/lang/Integer;");
@@ -506,7 +491,8 @@
}
status = U_ZERO_ERROR;
- jstring internationalCurrencySymbol = getIntCurrencyCode(env, locale);
+ jstring countryCode = env->NewStringUTF(Locale::createFromName(localeName.c_str()).getCountry());
+ jstring internationalCurrencySymbol = ICU_getCurrencyCodeNative(env, NULL, countryCode);
jstring currencySymbol = NULL;
if (internationalCurrencySymbol != NULL) {
currencySymbol = ICU_getCurrencySymbolNative(env, NULL, locale, internationalCurrencySymbol);
@@ -563,10 +549,19 @@
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) {
- return jniRegisterNativeMethods(env, "com/ibm/icu4jni/util/ICU", gMethods, NELEM(gMethods));
+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.
+ UErrorCode status = U_ZERO_ERROR;
+ u_init(&status);
+ if (status != U_ZERO_ERROR) {
+ LOGE("Couldn't initialize ICU: %s", u_errorName(status));
+ return -1;
+ }
+ 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/NativeCrypto.cpp b/luni/src/main/native/NativeCrypto.cpp
index d380215..1447c3c 100644
--- a/luni/src/main/native/NativeCrypto.cpp
+++ b/luni/src/main/native/NativeCrypto.cpp
@@ -987,72 +987,6 @@
return result;
}
-/**
- * Convert ssl version constant to string. Based on SSL_get_version
- */
-// TODO move to jsse.patch
-static const char* get_ssl_version(int ssl_version) {
- switch (ssl_version) {
- // newest to oldest
- case TLS1_VERSION: {
- return SSL_TXT_TLSV1;
- }
- case SSL3_VERSION: {
- return SSL_TXT_SSLV3;
- }
- case SSL2_VERSION: {
- return SSL_TXT_SSLV2;
- }
- default: {
- return "unknown";
- }
- }
-}
-
-#ifdef WITH_JNI_TRACE
-/**
- * Convert content type constant to string.
- */
-// TODO move to jsse.patch
-static const char* get_content_type(int content_type) {
- switch (content_type) {
- case SSL3_RT_CHANGE_CIPHER_SPEC: {
- return "SSL3_RT_CHANGE_CIPHER_SPEC";
- }
- case SSL3_RT_ALERT: {
- return "SSL3_RT_ALERT";
- }
- case SSL3_RT_HANDSHAKE: {
- return "SSL3_RT_HANDSHAKE";
- }
- case SSL3_RT_APPLICATION_DATA: {
- return "SSL3_RT_APPLICATION_DATA";
- }
- default: {
- LOGD("Unknown TLS/SSL content type %d", content_type);
- return "<unknown>";
- }
- }
-}
-#endif
-
-#ifdef WITH_JNI_TRACE
-/**
- * Simple logging call back to show hand shake messages
- */
-static void ssl_msg_callback_LOG(int write_p, int ssl_version, int content_type,
- const void* buf, size_t len, SSL* ssl, void* arg) {
- JNI_TRACE("ssl=%p SSL msg %s %s %s %p %d %p",
- ssl,
- (write_p) ? "send" : "recv",
- get_ssl_version(ssl_version),
- get_content_type(content_type),
- buf,
- len,
- arg);
-}
-#endif
-
#ifdef WITH_JNI_TRACE
/**
* Based on example logging call back from SSL_CTX_set_info_callback man page
@@ -1470,76 +1404,6 @@
errno = errnoBackup;
}
-// From private header file external/openssl/ssl_locl.h
-// TODO move dependent code to jsse.patch to avoid dependency
-#define SSL_aRSA 0x00000001L
-#define SSL_aDSS 0x00000002L
-#define SSL_aNULL 0x00000004L
-#define SSL_aDH 0x00000008L
-#define SSL_aECDH 0x00000010L
-#define SSL_aKRB5 0x00000020L
-#define SSL_aECDSA 0x00000040L
-#define SSL_aPSK 0x00000080L
-
-/**
- * Converts an SSL_CIPHER's algorithms field to a TrustManager auth argument
- */
-// TODO move to jsse.patch
-static const char* SSL_CIPHER_authentication_method(const SSL_CIPHER* cipher)
-{
- unsigned long alg_auth = cipher->algorithm_auth;
-
- const char* au;
- switch (alg_auth) {
- case SSL_aRSA:
- au="RSA";
- break;
- case SSL_aDSS:
- au="DSS";
- break;
- case SSL_aDH:
- au="DH";
- break;
- case SSL_aKRB5:
- au="KRB5";
- break;
- case SSL_aECDH:
- au = "ECDH";
- break;
- case SSL_aNULL:
- au="None";
- break;
- case SSL_aECDSA:
- au="ECDSA";
- break;
- case SSL_aPSK:
- au="PSK";
- break;
- default:
- au="unknown";
- break;
- }
- return au;
-}
-
-/**
- * Converts an SSL_CIPHER's algorithms field to a TrustManager auth argument
- */
-// TODO move to jsse.patch
-static const char* SSL_authentication_method(SSL* ssl)
-{
- switch (ssl->version) {
- case SSL2_VERSION:
- return "RSA";
- case SSL3_VERSION:
- case TLS1_VERSION:
- case DTLS1_VERSION:
- return SSL_CIPHER_authentication_method(ssl->s3->tmp.new_cipher);
- default:
- return "unknown";
- }
-}
-
static AppData* toAppData(const SSL* ssl) {
return reinterpret_cast<AppData*>(SSL_get_app_data(ssl));
}
@@ -1634,6 +1498,10 @@
JNI_TRACE("ssl=%p client_cert_cb env error => 0", ssl);
return 0;
}
+ if (env->ExceptionCheck()) {
+ JNI_TRACE("ssl=%p client_cert_cb already pending exception", ssl);
+ return 0;
+ }
jobject sslHandshakeCallbacks = appData->sslHandshakeCallbacks;
jclass cls = env->GetObjectClass(sslHandshakeCallbacks);
@@ -1825,9 +1693,6 @@
SSL_CTX_set_tmp_rsa_callback(sslCtx.get(), tmp_rsa_callback);
SSL_CTX_set_tmp_dh_callback(sslCtx.get(), tmp_dh_callback);
-#ifdef WITH_JNI_TRACE
- SSL_CTX_set_msg_callback(sslCtx.get(), ssl_msg_callback_LOG); /* enable for message debug */
-#endif
JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx.get());
return (jint) sslCtx.release();
}
@@ -3244,16 +3109,6 @@
}
/**
- * Our implementation of what might be considered
- * SSL_SESSION_get_version, based on SSL_get_version.
- * See get_ssl_version above.
- */
-// TODO move to jsse.patch
-static const char* SSL_SESSION_get_version(SSL_SESSION* ssl_session) {
- return get_ssl_version(ssl_session->ssl_version);
-}
-
-/**
* Gets and returns in a string the version of the SSL protocol. If it
* returns the string "unknown" it means that no connection is established.
*/
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 0c953cb..380bb7e 100644
--- a/luni/src/main/native/Register.cpp
+++ b/luni/src/main/native/Register.cpp
@@ -14,18 +14,17 @@
* limitations under the License.
*/
+#define LOG_TAG "libcore" // We'll be next to "dalvikvm" in the log; make the distinction clear.
+
#include "JniConstants.h"
#include "ScopedLocalFrame.h"
+#include <stdlib.h>
+
namespace android {
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);
@@ -51,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);
@@ -72,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 &&
@@ -102,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 &&
@@ -118,5 +122,9 @@
register_org_apache_harmony_dalvik_NativeTestTarget(env) != -1 &&
register_org_apache_harmony_xml_ExpatParser(env) != -1;
- return result ? 0 : -1;
+ if (!result) {
+ LOGE("Failed to initialize the core libraries; aborting...");
+ abort();
+ }
+ return 0;
}
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/java_lang_Double.cpp b/luni/src/main/native/java_lang_Double.cpp
index 259be30..f8b6be8 100644
--- a/luni/src/main/native/java_lang_Double.cpp
+++ b/luni/src/main/native/java_lang_Double.cpp
@@ -18,36 +18,25 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "java_lang_Double.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
-#include <stdint.h>
-
-union Double {
- uint64_t bits;
- double d;
-};
static const jlong NaN = 0x7ff8000000000000ULL;
-static jlong Double_doubleToLongBits(JNIEnv*, jclass, jdouble val) {
- Double d;
- d.d = val;
+static jlong Double_doubleToLongBits(JNIEnv*, jclass, jdouble doubleValue) {
// For this method all values in the NaN range are normalized to the canonical NaN value.
- return isnan(d.d) ? NaN : d.bits;
+ return isnan(doubleValue) ? NaN : Double::doubleToRawLongBits(doubleValue);
}
-static jlong Double_doubleToRawLongBits(JNIEnv*, jclass, jdouble val) {
- Double d;
- d.d = val;
- return d.bits;
+static jlong Double_doubleToRawLongBits(JNIEnv*, jclass, jdouble doubleValue) {
+ return Double::doubleToRawLongBits(doubleValue);
}
-static jdouble Double_longBitsToDouble(JNIEnv*, jclass, jlong val) {
- Double d;
- d.bits = val;
- return d.d;
+static jdouble Double_longBitsToDouble(JNIEnv*, jclass, jlong bits) {
+ return Double::longBitsToDouble(bits);
}
static JNINativeMethod gMethods[] = {
diff --git a/luni/src/main/native/java_lang_Double.h b/luni/src/main/native/java_lang_Double.h
new file mode 100644
index 0000000..2f63c0d
--- /dev/null
+++ b/luni/src/main/native/java_lang_Double.h
@@ -0,0 +1,41 @@
+/*
+ * 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 JAVA_LANG_DOUBLE_H_included
+#define JAVA_LANG_DOUBLE_H_included
+
+#include <stdint.h>
+
+union Double {
+public:
+ static inline double longBitsToDouble(uint64_t bits) {
+ Double result;
+ result.bits = bits;
+ return result.doubleValue;
+ }
+
+ static inline uint64_t doubleToRawLongBits(double doubleValue) {
+ Double result;
+ result.doubleValue = doubleValue;
+ return result.bits;
+ }
+
+private:
+ uint64_t bits;
+ double doubleValue;
+};
+
+#endif // JAVA_LANG_DOUBLE_H_included
diff --git a/luni/src/main/native/java_lang_Float.cpp b/luni/src/main/native/java_lang_Float.cpp
index 59544db..93384df 100644
--- a/luni/src/main/native/java_lang_Float.cpp
+++ b/luni/src/main/native/java_lang_Float.cpp
@@ -18,35 +18,25 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "java_lang_Float.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
-union Float {
- unsigned int bits;
- float f;
-};
-
static const jint NaN = 0x7fc00000;
-static jint Float_floatToIntBits(JNIEnv*, jclass, jfloat val) {
- Float f;
- f.f = val;
+static jint Float_floatToIntBits(JNIEnv*, jclass, jfloat floatValue) {
// For this method all values in the NaN range are normalized to the canonical NaN value.
- return isnanf(f.f) ? NaN : f.bits;
+ return isnanf(floatValue) ? NaN : Float::floatToRawIntBits(floatValue);
}
-jint Float_floatToRawIntBits(JNIEnv*, jclass, jfloat val) {
- Float f;
- f.f = val;
- return f.bits;
+static jint Float_floatToRawIntBits(JNIEnv*, jclass, jfloat floatValue) {
+ return Float::floatToRawIntBits(floatValue);
}
-jfloat Float_intBitsToFloat(JNIEnv*, jclass, jint val) {
- Float f;
- f.bits = val;
- return f.f;
+static jfloat Float_intBitsToFloat(JNIEnv*, jclass, jint bits) {
+ return Float::intBitsToFloat(bits);
}
static JNINativeMethod gMethods[] = {
diff --git a/luni/src/main/native/java_lang_Float.h b/luni/src/main/native/java_lang_Float.h
new file mode 100644
index 0000000..e60d953
--- /dev/null
+++ b/luni/src/main/native/java_lang_Float.h
@@ -0,0 +1,41 @@
+/*
+ * 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 JAVA_LANG_FLOAT_H_included
+#define JAVA_LANG_FLOAT_H_included
+
+#include <stdint.h>
+
+union Float {
+public:
+ static inline float intBitsToFloat(uint32_t bits) {
+ Float result;
+ result.bits = bits;
+ return result.floatValue;
+ }
+
+ static inline uint32_t floatToRawIntBits(float floatValue) {
+ Float result;
+ result.floatValue = floatValue;
+ return result.bits;
+ }
+
+private:
+ uint32_t bits;
+ float floatValue;
+};
+
+#endif // JAVA_LANG_FLOAT_H_included
diff --git a/luni/src/main/native/java_lang_StrictMath.cpp b/luni/src/main/native/java_lang_StrictMath.cpp
index bce7a48..24c15b0 100644
--- a/luni/src/main/native/java_lang_StrictMath.cpp
+++ b/luni/src/main/native/java_lang_StrictMath.cpp
@@ -21,6 +21,7 @@
#include "jni.h"
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "java_lang_Float.h"
static jdouble StrictMath_sin(JNIEnv*, jclass, jdouble a) {
return ieee_sin(a);
@@ -118,17 +119,14 @@
return ieee_nextafter(a, b);
}
-extern jint Float_floatToRawIntBits(JNIEnv*, jclass, jfloat);
-extern jfloat Float_intBitsToFloat(JNIEnv*, jclass, jint val);
-
// TODO: we should make Float.floatToRawBits and Float.intBitsToFloat intrinsics, and move
// this kind of code into Java.
static jfloat StrictMath_nextafterf(JNIEnv*, jclass, jfloat arg1, jfloat arg2) {
- jint hx = Float_floatToRawIntBits(NULL, NULL, arg1);
- jint hy = Float_floatToRawIntBits(NULL, NULL, arg2);
+ jint hx = Float::floatToRawIntBits(arg1);
+ jint hy = Float::floatToRawIntBits(arg2);
if (!(hx & 0x7fffffff)) { /* arg1 == 0 */
- return Float_intBitsToFloat(NULL, NULL, (hy & 0x80000000) | 0x1);
+ return Float::intBitsToFloat((hy & 0x80000000) | 0x1);
}
if ((hx > 0) ^ (hx > hy)) { /* |arg1| < |arg2| */
@@ -136,7 +134,7 @@
} else {
hx -= 1;
}
- return Float_intBitsToFloat(NULL, NULL, hx);
+ return Float::intBitsToFloat(hx);
}
static JNINativeMethod gMethods[] = {
diff --git a/luni/src/main/native/java_net_InetAddress.cpp b/luni/src/main/native/java_net_InetAddress.cpp
index 8c81075..7681463 100644
--- a/luni/src/main/native/java_net_InetAddress.cpp
+++ b/luni/src/main/native/java_net_InetAddress.cpp
@@ -145,9 +145,12 @@
} else if (result == EAI_SYSTEM && errno == EACCES) {
/* No permission to use network */
jniThrowException(env, "java/lang/SecurityException",
- "Permission denied (maybe missing INTERNET permission)");
+ "Permission denied (maybe missing INTERNET permission)");
} else {
- jniThrowException(env, "java/net/UnknownHostException", gai_strerror(result));
+ char buf[256];
+ snprintf(buf, sizeof(buf), "Unable to resolve host \"%s\": %s",
+ name.c_str(), gai_strerror(result));
+ jniThrowException(env, "java/net/UnknownHostException", buf);
}
if (addressList) {
@@ -209,25 +212,6 @@
return env->NewStringUTF(name);
}
-/**
- * Convert a Java string representing an IP address to a Java byte array.
- * The formats accepted are:
- * - IPv4:
- * - 1.2.3.4
- * - 1.2.4
- * - 1.4
- * - 4
- * - IPv6
- * - Compressed form (2001:db8::1)
- * - Uncompressed form (2001:db8:0:0:0:0:0:1)
- * - IPv4-compatible (::192.0.2.0)
- * - With an embedded IPv4 address (2001:db8::192.0.2.0).
- * IPv6 addresses may appear in square brackets.
- *
- * @param addressByteArray the byte array to convert.
- * @return a string with the textual representation of the address.
- * @throws UnknownHostException the IP address was invalid.
- */
static jbyteArray InetAddress_ipStringToByteArray(JNIEnv* env, jobject, jstring javaString) {
// Convert the String to UTF-8 bytes.
ScopedUtfChars chars(env, javaString);
@@ -287,7 +271,6 @@
if (!result) {
env->ExceptionClear();
- jniThrowException(env, "java/net/UnknownHostException", gai_strerror(ret));
}
return result;
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 6576155..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;
}
@@ -408,8 +393,24 @@
if (path.c_str() == NULL) {
return -1;
}
- jint rc = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
- if (rc == -1) {
+ jint fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
+
+ // Posix open(2) fails with EISDIR only if you ask for write permission.
+ // Java disallows reading directories too.
+ if (fd != -1) {
+ struct stat sb;
+ int rc = fstat(fd, &sb);
+ if (rc == -1 || S_ISDIR(sb.st_mode)) {
+ // Use EISDIR if that was the case; fail with the fstat(2) error otherwise.
+ close(fd);
+ fd = -1;
+ if (S_ISDIR(sb.st_mode)) {
+ errno = EISDIR;
+ }
+ }
+ }
+
+ if (fd == -1) {
// Get the human-readable form of errno.
char buffer[80];
const char* reason = jniStrError(errno, &buffer[0], sizeof(buffer));
@@ -422,7 +423,7 @@
// failure. (This appears to be true of the RI too.)
jniThrowException(env, "java/io/FileNotFoundException", &message[0]);
}
- return rc;
+ return fd;
}
static jint OSFileSystem_ioctlAvailable(JNIEnv*env, jobject, jobject fileDescriptor) {
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 43cfa32..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
@@ -18,249 +18,288 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "ScopedPrimitiveArray.h"
#include "UniquePtr.h"
+#include "java_lang_Float.h"
+#include "java_lang_Double.h"
+#include <byteswap.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
-/*
- * Cached dalvik.system.VMRuntime pieces.
- */
-static struct {
- jmethodID method_trackExternalAllocation;
- jmethodID method_trackExternalFree;
+#if defined(__arm__)
+// 32-bit ARM has load/store alignment restrictions for longs.
+#define LONG_ALIGNMENT_MASK 0x3
+#elif defined(__i386__)
+// x86 can load anything at any alignment.
+#define LONG_ALIGNMENT_MASK 0x0
+#else
+#error unknown load/store alignment restrictions for this architecture
+#endif
- jobject runtimeInstance;
-} gIDCache;
+static jobject runtimeInstance;
template <typename T> static T cast(jint address) {
return reinterpret_cast<T>(static_cast<uintptr_t>(address));
}
+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
+ 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);
+ *reinterpret_cast<jshort*>(dst) = bswap_16(v);
+ }
+}
+
+static inline void swapInts(jint* dstInts, const jint* srcInts, size_t count) {
+ for (size_t i = 0; i < count; ++i) {
+ jint v = *srcInts++;
+ *dstInts++ = bswap_32(v);
+ }
+}
+
+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++;
+ *dst++ = bswap_32(v2);
+ *dst++ = bswap_32(v1);
+ }
+}
+
static jint OSMemory_malloc(JNIEnv* env, jclass, jint size) {
- jboolean allowed = env->CallBooleanMethod(gIDCache.runtimeInstance,
- gIDCache.method_trackExternalAllocation, static_cast<jlong>(size));
+ static jmethodID trackExternalAllocationMethod =
+ env->GetMethodID(JniConstants::vmRuntimeClass, "trackExternalAllocation", "(J)Z");
+
+ jboolean allowed = env->CallBooleanMethod(runtimeInstance, trackExternalAllocationMethod,
+ static_cast<jlong>(size));
if (!allowed) {
LOGW("External allocation of %d bytes was rejected\n", size);
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return 0;
}
- LOGV("OSMemory alloc %d\n", size);
- void* block = malloc(size + sizeof(jlong));
+ // Our only caller wants zero-initialized memory.
+ // calloc(3) may be faster than malloc(3) followed by memset(3).
+ void* block = calloc(size + sizeof(jlong), 1);
if (block == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return 0;
}
- /*
- * Tuck a copy of the size at the head of the buffer. We need this
- * so OSMemory_free() knows how much memory is being freed.
- */
+ // Tuck a copy of the size at the head of the buffer. We need this
+ // so OSMemory_free() knows how much memory is being freed.
jlong* result = reinterpret_cast<jlong*>(block);
*result++ = size;
return static_cast<jint>(reinterpret_cast<uintptr_t>(result));
}
static void OSMemory_free(JNIEnv* env, jclass, jint address) {
+ static jmethodID trackExternalFreeMethod =
+ env->GetMethodID(JniConstants::vmRuntimeClass, "trackExternalFree", "(J)V");
+
jlong* p = reinterpret_cast<jlong*>(static_cast<uintptr_t>(address));
jlong size = *--p;
- LOGV("OSMemory free %ld\n", size);
- env->CallVoidMethod(gIDCache.runtimeInstance, gIDCache.method_trackExternalFree, size);
+ env->CallVoidMethod(runtimeInstance, trackExternalFreeMethod, size);
free(reinterpret_cast<void*>(p));
}
-static void OSMemory_memset(JNIEnv*, jclass, jint dstAddress, jbyte value, jlong length) {
- memset(cast<void*>(dstAddress), value, length);
-}
-
static void OSMemory_memmove(JNIEnv*, jclass, jint dstAddress, jint srcAddress, jlong length) {
memmove(cast<void*>(dstAddress), cast<const void*>(srcAddress), length);
}
-static jbyte OSMemory_getByte(JNIEnv*, jclass, jint srcAddress) {
+static jbyte OSMemory_peekByte(JNIEnv*, jclass, jint srcAddress) {
return *cast<const jbyte*>(srcAddress);
}
-static void OSMemory_getByteArray(JNIEnv* env, jclass, jint srcAddress,
- jbyteArray dst, jint offset, jint length) {
- env->SetByteArrayRegion(dst, offset, length, cast<const jbyte*>(srcAddress));
+static void OSMemory_peekByteArray(JNIEnv* env, jclass, jint srcAddress, jbyteArray dst, jint dstOffset, jint byteCount) {
+ env->SetByteArrayRegion(dst, dstOffset, byteCount, cast<const jbyte*>(srcAddress));
}
-static void OSMemory_setByte(JNIEnv*, jclass, jint dstAddress, jbyte value) {
+// Implements the peekXArray methods:
+// - For unswapped access, we just use the JNI SetXArrayRegion functions.
+// - For swapped access, we use GetXArrayElements and our own copy-and-swap routines.
+// GetXArrayElements is disproportionately cheap on Dalvik because it doesn't copy (as opposed
+// to Hotspot, which always copies). The SWAP_FN copies and swaps in one pass, which is cheaper
+// than copying and then swapping in a second pass. Depending on future VM/GC changes, the
+// swapped case might need to be revisited.
+#define PEEKER(SCALAR_TYPE, JNI_NAME, SWAP_TYPE, SWAP_FN) { \
+ if (swap) { \
+ Scoped ## JNI_NAME ## ArrayRW elements(env, dst); \
+ if (elements.get() == NULL) { \
+ return; \
+ } \
+ const SWAP_TYPE* src = cast<const SWAP_TYPE*>(srcAddress); \
+ SWAP_FN(reinterpret_cast<SWAP_TYPE*>(elements.get()) + dstOffset, src, count); \
+ } else { \
+ const SCALAR_TYPE* src = cast<const SCALAR_TYPE*>(srcAddress); \
+ env->Set ## JNI_NAME ## ArrayRegion(dst, dstOffset, count, src); \
+ } \
+}
+
+static void OSMemory_peekCharArray(JNIEnv* env, jclass, jint srcAddress, jcharArray dst, jint dstOffset, jint count, jboolean swap) {
+ PEEKER(jchar, Char, jshort, swapShorts);
+}
+
+static void OSMemory_peekDoubleArray(JNIEnv* env, jclass, jint srcAddress, jdoubleArray dst, jint dstOffset, jint count, jboolean swap) {
+ PEEKER(jdouble, Double, jlong, swapLongs);
+}
+
+static void OSMemory_peekFloatArray(JNIEnv* env, jclass, jint srcAddress, jfloatArray dst, jint dstOffset, jint count, jboolean swap) {
+ PEEKER(jfloat, Float, jint, swapInts);
+}
+
+static void OSMemory_peekIntArray(JNIEnv* env, jclass, jint srcAddress, jintArray dst, jint dstOffset, jint count, jboolean swap) {
+ PEEKER(jint, Int, jint, swapInts);
+}
+
+static void OSMemory_peekLongArray(JNIEnv* env, jclass, jint srcAddress, jlongArray dst, jint dstOffset, jint count, jboolean swap) {
+ PEEKER(jlong, Long, jlong, swapLongs);
+}
+
+static void OSMemory_peekShortArray(JNIEnv* env, jclass, jint srcAddress, jshortArray dst, jint dstOffset, jint count, jboolean swap) {
+ PEEKER(jshort, Short, jshort, swapShorts);
+}
+
+static void OSMemory_pokeByte(JNIEnv*, jclass, jint dstAddress, jbyte value) {
*cast<jbyte*>(dstAddress) = value;
}
-static void OSMemory_setByteArray(JNIEnv* env, jclass,
- jint dstAddress, jbyteArray src, jint offset, jint length) {
+static void OSMemory_pokeByteArray(JNIEnv* env, jclass, jint dstAddress, jbyteArray src, jint offset, jint length) {
env->GetByteArrayRegion(src, offset, length, cast<jbyte*>(dstAddress));
}
-static void swapShorts(jshort* shorts, int count) {
- jbyte* src = reinterpret_cast<jbyte*>(shorts);
- jbyte* dst = src;
- for (int i = 0; i < count; ++i) {
- jbyte b0 = *src++;
- jbyte b1 = *src++;
- *dst++ = b1;
- *dst++ = b0;
- }
+// Implements the pokeXArray methods:
+// - For unswapped access, we just use the JNI GetXArrayRegion functions.
+// - For swapped access, we use GetXArrayElements and our own copy-and-swap routines.
+// GetXArrayElements is disproportionately cheap on Dalvik because it doesn't copy (as opposed
+// to Hotspot, which always copies). The SWAP_FN copies and swaps in one pass, which is cheaper
+// than copying and then swapping in a second pass. Depending on future VM/GC changes, the
+// swapped case might need to be revisited.
+#define POKER(SCALAR_TYPE, JNI_NAME, SWAP_TYPE, SWAP_FN) { \
+ if (swap) { \
+ Scoped ## JNI_NAME ## ArrayRO elements(env, src); \
+ if (elements.get() == NULL) { \
+ return; \
+ } \
+ const SWAP_TYPE* src = reinterpret_cast<const SWAP_TYPE*>(elements.get()) + srcOffset; \
+ SWAP_FN(cast<SWAP_TYPE*>(dstAddress), src, count); \
+ } else { \
+ env->Get ## JNI_NAME ## ArrayRegion(src, srcOffset, count, cast<SCALAR_TYPE*>(dstAddress)); \
+ } \
}
-static void swapInts(jint* ints, int count) {
- jbyte* src = reinterpret_cast<jbyte*>(ints);
- jbyte* dst = src;
- for (int i = 0; i < count; ++i) {
- jbyte b0 = *src++;
- jbyte b1 = *src++;
- jbyte b2 = *src++;
- jbyte b3 = *src++;
- *dst++ = b3;
- *dst++ = b2;
- *dst++ = b1;
- *dst++ = b0;
- }
+static void OSMemory_pokeCharArray(JNIEnv* env, jclass, jint dstAddress, jcharArray src, jint srcOffset, jint count, jboolean swap) {
+ POKER(jchar, Char, jshort, swapShorts);
}
-static void OSMemory_setFloatArray(JNIEnv* env, jclass, jint dstAddress,
- jfloatArray src, jint offset, jint length, jboolean swap) {
- jfloat* dst = cast<jfloat*>(dstAddress);
- env->GetFloatArrayRegion(src, offset, length, dst);
+static void OSMemory_pokeDoubleArray(JNIEnv* env, jclass, jint dstAddress, jdoubleArray src, jint srcOffset, jint count, jboolean swap) {
+ POKER(jdouble, Double, jlong, swapLongs);
+}
+
+static void OSMemory_pokeFloatArray(JNIEnv* env, jclass, jint dstAddress, jfloatArray src, jint srcOffset, jint count, jboolean swap) {
+ POKER(jfloat, Float, jint, swapInts);
+}
+
+static void OSMemory_pokeIntArray(JNIEnv* env, jclass, jint dstAddress, jintArray src, jint srcOffset, jint count, jboolean swap) {
+ POKER(jint, Int, jint, swapInts);
+}
+
+static void OSMemory_pokeLongArray(JNIEnv* env, jclass, jint dstAddress, jlongArray src, jint srcOffset, jint count, jboolean swap) {
+ POKER(jlong, Long, jlong, swapLongs);
+}
+
+static void OSMemory_pokeShortArray(JNIEnv* env, jclass, jint dstAddress, jshortArray src, jint srcOffset, jint count, jboolean swap) {
+ POKER(jshort, Short, jshort, swapShorts);
+}
+
+static jshort OSMemory_peekShort(JNIEnv*, jclass, jint srcAddress, jboolean swap) {
+ jshort result = *cast<const jshort*>(srcAddress);
if (swap) {
- swapInts(reinterpret_cast<jint*>(dst), length);
+ result = bswap_16(result);
}
+ return result;
}
-static void OSMemory_setIntArray(JNIEnv* env, jclass,
- jint dstAddress, jintArray src, jint offset, jint length, jboolean swap) {
- jint* dst = cast<jint*>(dstAddress);
- env->GetIntArrayRegion(src, offset, length, dst);
+static void OSMemory_pokeShort(JNIEnv*, jclass, jint dstAddress, jshort value, jboolean swap) {
if (swap) {
- swapInts(dst, length);
+ value = bswap_16(value);
}
+ *cast<jshort*>(dstAddress) = value;
}
-static void OSMemory_setShortArray(JNIEnv* env, jclass,
- jint dstAddress, jshortArray src, jint offset, jint length, jboolean swap) {
- jshort* dst = cast<jshort*>(dstAddress);
- env->GetShortArrayRegion(src, offset, length, dst);
+static jint OSMemory_peekInt(JNIEnv*, jclass, jint srcAddress, jboolean swap) {
+ jint result = *cast<const jint*>(srcAddress);
if (swap) {
- swapShorts(dst, length);
+ result = bswap_32(result);
}
+ return result;
}
-static jshort OSMemory_getShort(JNIEnv*, jclass, jint srcAddress) {
- if ((srcAddress & 0x1) == 0) {
- return *cast<const jshort*>(srcAddress);
- } else {
- // Handle unaligned memory access one byte at a time
- jshort result;
- const jbyte* src = cast<const jbyte*>(srcAddress);
- jbyte* dst = reinterpret_cast<jbyte*>(&result);
- dst[0] = src[0];
- dst[1] = src[1];
- return result;
+static void OSMemory_pokeInt(JNIEnv*, jclass, jint dstAddress, jint value, jboolean swap) {
+ if (swap) {
+ value = bswap_32(value);
}
-}
-
-static void OSMemory_setShort(JNIEnv*, jclass, jint dstAddress, jshort value) {
- if ((dstAddress & 0x1) == 0) {
- *cast<jshort*>(dstAddress) = value;
- } else {
- // Handle unaligned memory access one byte at a time
- const jbyte* src = reinterpret_cast<const jbyte*>(&value);
- jbyte* dst = cast<jbyte*>(dstAddress);
- dst[0] = src[0];
- dst[1] = src[1];
- }
-}
-
-static jint OSMemory_getInt(JNIEnv*, jclass, jint srcAddress) {
- if ((srcAddress & 0x3) == 0) {
- return *cast<const jint*>(srcAddress);
- } else {
- // Handle unaligned memory access one byte at a time
- jint result;
- const jbyte* src = cast<const jbyte*>(srcAddress);
- jbyte* dst = reinterpret_cast<jbyte*>(&result);
- dst[0] = src[0];
- dst[1] = src[1];
- dst[2] = src[2];
- dst[3] = src[3];
- return result;
- }
-}
-
-static void OSMemory_setInt(JNIEnv*, jclass, jint dstAddress, jint value) {
- if ((dstAddress & 0x3) == 0) {
- *cast<jint*>(dstAddress) = value;
- } else {
- // Handle unaligned memory access one byte at a time
- const jbyte* src = reinterpret_cast<const jbyte*>(&value);
- jbyte* dst = cast<jbyte*>(dstAddress);
- dst[0] = src[0];
- dst[1] = src[1];
- dst[2] = src[2];
- dst[3] = src[3];
- }
-}
-
-template <typename T> static T get(jint srcAddress) {
- if ((srcAddress & (sizeof(T) - 1)) == 0) {
- return *cast<const T*>(srcAddress);
- } else {
- // Cast to void* so GCC can't assume correct alignment and optimize this out.
- const void* src = cast<const void*>(srcAddress);
- T result;
- memcpy(&result, src, sizeof(T));
- return result;
- }
-}
-
-template <typename T> static void set(jint dstAddress, T value) {
- if ((dstAddress & (sizeof(T) - 1)) == 0) {
- *cast<T*>(dstAddress) = value;
- } else {
- // Cast to void* so GCC can't assume correct alignment and optimize this out.
- void* dst = cast<void*>(dstAddress);
- memcpy(dst, &value, sizeof(T));
- }
-}
-
-static jlong OSMemory_getLong(JNIEnv*, jclass, jint srcAddress) {
- return get<jlong>(srcAddress);
-}
-
-static void OSMemory_setLong(JNIEnv*, jclass, jint dstAddress, jlong value) {
- set<jlong>(dstAddress, value);
-}
-
-static jfloat OSMemory_getFloat(JNIEnv*, jclass, jint srcAddress) {
- return get<jfloat>(srcAddress);
-}
-
-static void OSMemory_setFloat(JNIEnv*, jclass, jint dstAddress, jfloat value) {
- set<jfloat>(dstAddress, value);
-}
-
-static jdouble OSMemory_getDouble(JNIEnv*, jclass, jint srcAddress) {
- return get<jdouble>(srcAddress);
-}
-
-static void OSMemory_setDouble(JNIEnv*, jclass, jint dstAddress, jdouble value) {
- set<jdouble>(dstAddress, value);
-}
-
-static jint OSMemory_getAddress(JNIEnv*, jclass, jint srcAddress) {
- return *cast<const jint*>(srcAddress);
-}
-
-static void OSMemory_setAddress(JNIEnv*, jclass, jint dstAddress, jint value) {
*cast<jint*>(dstAddress) = value;
}
+static jlong OSMemory_peekLong(JNIEnv*, jclass, jint srcAddress, jboolean swap) {
+ jlong result;
+ if ((srcAddress & LONG_ALIGNMENT_MASK) == 0) {
+ result = *cast<const jlong*>(srcAddress);
+ } else {
+ // Handle unaligned memory access one byte at a time
+ const jbyte* src = cast<const jbyte*>(srcAddress);
+ jbyte* dst = reinterpret_cast<jbyte*>(&result);
+ dst[0] = src[0];
+ dst[1] = src[1];
+ dst[2] = src[2];
+ dst[3] = src[3];
+ dst[4] = src[4];
+ dst[5] = src[5];
+ dst[6] = src[6];
+ dst[7] = src[7];
+ }
+ if (swap) {
+ result = bswap_64(result);
+ }
+ return result;
+}
+
+static void OSMemory_pokeLong(JNIEnv*, jclass, jint dstAddress, jlong value, jboolean swap) {
+ if (swap) {
+ value = bswap_64(value);
+ }
+ if ((dstAddress & LONG_ALIGNMENT_MASK) == 0) {
+ *cast<jlong*>(dstAddress) = value;
+ } else {
+ // Handle unaligned memory access one byte at a time
+ const jbyte* src = reinterpret_cast<const jbyte*>(&value);
+ jbyte* dst = cast<jbyte*>(dstAddress);
+ dst[0] = src[0];
+ dst[1] = src[1];
+ dst[2] = src[2];
+ dst[3] = src[3];
+ dst[4] = src[4];
+ dst[5] = src[5];
+ dst[6] = src[6];
+ dst[7] = src[7];
+ }
+}
+
static jint OSMemory_mmapImpl(JNIEnv* env, jclass, jint fd, jlong offset, jlong size, jint mapMode) {
int prot, flags;
switch (mapMode) {
@@ -289,7 +328,7 @@
return reinterpret_cast<uintptr_t>(mapAddress);
}
-static void OSMemory_unmap(JNIEnv*, jclass, jint address, jlong size) {
+static void OSMemory_munmap(JNIEnv*, jclass, jint address, jlong size) {
munmap(cast<void*>(address), size);
}
@@ -325,57 +364,104 @@
return JNI_TRUE;
}
-static void OSMemory_flush(JNIEnv*, jclass, jint address, jlong size) {
+static void OSMemory_msync(JNIEnv*, jclass, jint address, jlong size) {
msync(cast<void*>(address), size, MS_SYNC);
}
+static void unsafeBulkCopy(jbyte* dst, const jbyte* src, jint byteCount,
+ jint sizeofElement, jboolean swap) {
+ if (!swap) {
+ memcpy(dst, src, byteCount);
+ return;
+ }
+
+ if (sizeofElement == 2) {
+ jshort* dstShorts = reinterpret_cast<jshort*>(dst);
+ const jshort* srcShorts = reinterpret_cast<const jshort*>(src);
+ swapShorts(dstShorts, srcShorts, byteCount / 2);
+ } else if (sizeofElement == 4) {
+ jint* dstInts = reinterpret_cast<jint*>(dst);
+ const jint* srcInts = reinterpret_cast<const jint*>(src);
+ swapInts(dstInts, srcInts, byteCount / 4);
+ } else if (sizeofElement == 8) {
+ jlong* dstLongs = reinterpret_cast<jlong*>(dst);
+ const jlong* srcLongs = reinterpret_cast<const jlong*>(src);
+ swapLongs(dstLongs, srcLongs, byteCount / 8);
+ }
+}
+
+static void OSMemory_unsafeBulkGet(JNIEnv* env, jclass, jobject dstObject, jint dstOffset,
+ jint byteCount, jbyteArray srcArray, jint srcOffset, jint sizeofElement, jboolean swap) {
+ ScopedByteArrayRO srcBytes(env, srcArray);
+ if (srcBytes.get() == NULL) {
+ return;
+ }
+ jarray dstArray = reinterpret_cast<jarray>(dstObject);
+ jbyte* dstBytes = reinterpret_cast<jbyte*>(env->GetPrimitiveArrayCritical(dstArray, NULL));
+ if (dstBytes == NULL) {
+ return;
+ }
+ jbyte* dst = dstBytes + dstOffset*sizeofElement;
+ const jbyte* src = srcBytes.get() + srcOffset;
+ unsafeBulkCopy(dst, src, byteCount, sizeofElement, swap);
+ env->ReleasePrimitiveArrayCritical(dstArray, dstBytes, 0);
+}
+
+static void OSMemory_unsafeBulkPut(JNIEnv* env, jclass, jbyteArray dstArray, jint dstOffset,
+ jint byteCount, jobject srcObject, jint srcOffset, jint sizeofElement, jboolean swap) {
+ ScopedByteArrayRW dstBytes(env, dstArray);
+ if (dstBytes.get() == NULL) {
+ return;
+ }
+ jarray srcArray = reinterpret_cast<jarray>(srcObject);
+ jbyte* srcBytes = reinterpret_cast<jbyte*>(env->GetPrimitiveArrayCritical(srcArray, NULL));
+ if (srcBytes == NULL) {
+ return;
+ }
+ jbyte* dst = dstBytes.get() + dstOffset;
+ const jbyte* src = srcBytes + srcOffset*sizeofElement;
+ unsafeBulkCopy(dst, src, byteCount, sizeofElement, swap);
+ env->ReleasePrimitiveArrayCritical(srcArray, srcBytes, 0);
+}
+
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(OSMemory, flush, "(IJ)V"),
NATIVE_METHOD(OSMemory, free, "(I)V"),
- NATIVE_METHOD(OSMemory, getAddress, "(I)I"),
- NATIVE_METHOD(OSMemory, getByte, "(I)B"),
- NATIVE_METHOD(OSMemory, getByteArray, "(I[BII)V"),
- NATIVE_METHOD(OSMemory, getDouble, "(I)D"),
- NATIVE_METHOD(OSMemory, getFloat, "(I)F"),
- NATIVE_METHOD(OSMemory, getInt, "(I)I"),
- NATIVE_METHOD(OSMemory, getLong, "(I)J"),
- NATIVE_METHOD(OSMemory, getShort, "(I)S"),
NATIVE_METHOD(OSMemory, isLoaded, "(IJ)Z"),
NATIVE_METHOD(OSMemory, load, "(IJ)V"),
NATIVE_METHOD(OSMemory, malloc, "(I)I"),
NATIVE_METHOD(OSMemory, memmove, "(IIJ)V"),
- NATIVE_METHOD(OSMemory, memset, "(IBJ)V"),
NATIVE_METHOD(OSMemory, mmapImpl, "(IJJI)I"),
- NATIVE_METHOD(OSMemory, setAddress, "(II)V"),
- NATIVE_METHOD(OSMemory, setByte, "(IB)V"),
- NATIVE_METHOD(OSMemory, setByteArray, "(I[BII)V"),
- NATIVE_METHOD(OSMemory, setDouble, "(ID)V"),
- NATIVE_METHOD(OSMemory, setFloat, "(IF)V"),
- NATIVE_METHOD(OSMemory, setFloatArray, "(I[FIIZ)V"),
- NATIVE_METHOD(OSMemory, setInt, "(II)V"),
- NATIVE_METHOD(OSMemory, setIntArray, "(I[IIIZ)V"),
- NATIVE_METHOD(OSMemory, setLong, "(IJ)V"),
- NATIVE_METHOD(OSMemory, setShort, "(IS)V"),
- NATIVE_METHOD(OSMemory, setShortArray, "(I[SIIZ)V"),
- NATIVE_METHOD(OSMemory, unmap, "(IJ)V"),
+ NATIVE_METHOD(OSMemory, msync, "(IJ)V"),
+ NATIVE_METHOD(OSMemory, munmap, "(IJ)V"),
+ NATIVE_METHOD(OSMemory, peekByte, "(I)B"),
+ NATIVE_METHOD(OSMemory, peekByteArray, "(I[BII)V"),
+ NATIVE_METHOD(OSMemory, peekCharArray, "(I[CIIZ)V"),
+ NATIVE_METHOD(OSMemory, peekDoubleArray, "(I[DIIZ)V"),
+ NATIVE_METHOD(OSMemory, peekFloatArray, "(I[FIIZ)V"),
+ NATIVE_METHOD(OSMemory, peekInt, "(IZ)I"),
+ NATIVE_METHOD(OSMemory, peekIntArray, "(I[IIIZ)V"),
+ NATIVE_METHOD(OSMemory, peekLong, "(IZ)J"),
+ NATIVE_METHOD(OSMemory, peekLongArray, "(I[JIIZ)V"),
+ NATIVE_METHOD(OSMemory, peekShort, "(IZ)S"),
+ NATIVE_METHOD(OSMemory, peekShortArray, "(I[SIIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeByte, "(IB)V"),
+ NATIVE_METHOD(OSMemory, pokeByteArray, "(I[BII)V"),
+ NATIVE_METHOD(OSMemory, pokeCharArray, "(I[CIIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeDoubleArray, "(I[DIIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeFloatArray, "(I[FIIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeInt, "(IIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeIntArray, "(I[IIIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeLong, "(IJZ)V"),
+ NATIVE_METHOD(OSMemory, pokeLongArray, "(I[JIIZ)V"),
+ NATIVE_METHOD(OSMemory, pokeShort, "(ISZ)V"),
+ NATIVE_METHOD(OSMemory, pokeShortArray, "(I[SIIZ)V"),
+ NATIVE_METHOD(OSMemory, unsafeBulkGet, "(Ljava/lang/Object;II[BIIZ)V"),
+ NATIVE_METHOD(OSMemory, unsafeBulkPut, "([BIILjava/lang/Object;IIZ)V"),
};
int register_org_apache_harmony_luni_platform_OSMemory(JNIEnv* env) {
- /*
- * We need to call VMRuntime.trackExternal{Allocation,Free}. Cache
- * method IDs and a reference to the singleton.
- */
- gIDCache.method_trackExternalAllocation = env->GetMethodID(JniConstants::vmRuntimeClass,
- "trackExternalAllocation", "(J)Z");
- gIDCache.method_trackExternalFree = env->GetMethodID(JniConstants::vmRuntimeClass,
- "trackExternalFree", "(J)V");
-
jmethodID method_getRuntime = env->GetStaticMethodID(JniConstants::vmRuntimeClass,
- "getRuntime", "()Ldalvik/system/VMRuntime;");
-
- if (gIDCache.method_trackExternalAllocation == NULL ||
- gIDCache.method_trackExternalFree == NULL ||
- method_getRuntime == NULL)
- {
+ "getRuntime", "()Ldalvik/system/VMRuntime;");
+ if (method_getRuntime == NULL) {
LOGE("Unable to find VMRuntime methods\n");
return -1;
}
@@ -385,7 +471,7 @@
LOGE("Unable to obtain VMRuntime instance\n");
return -1;
}
- gIDCache.runtimeInstance = env->NewGlobalRef(instance);
+ runtimeInstance = env->NewGlobalRef(instance);
return jniRegisterNativeMethods(env, "org/apache/harmony/luni/platform/OSMemory",
gMethods, NELEM(gMethods));
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 64cf516..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;
@@ -1328,6 +1343,8 @@
static void OSNetworkSystem_close(JNIEnv* env, jobject, jobject fileDescriptor) {
NetFd fd(env, fileDescriptor);
if (fd.isClosed()) {
+ // Socket.close doesn't throw if you try to close an already-closed socket.
+ env->ExceptionClear();
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/main/native/org_apache_harmony_xml_ExpatParser.cpp b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
index c4623e6..960e73e 100644
--- a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
+++ b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
@@ -608,7 +608,7 @@
// Count the number of attributes.
int count = 0;
- while (attributes[count << 1]) count++;
+ while (attributes[count * 2]) count++;
// Make the attributes available for the duration of this call.
parsingContext->attributes = attributes;
@@ -1159,7 +1159,7 @@
static jstring ExpatAttributes_getValueByIndex(JNIEnv* env, jobject,
jint attributePointer, jint index) {
const char** attributes = toAttributes(attributePointer);
- const char* value = attributes[(index << 1) + 1];
+ const char* value = attributes[(index * 2) + 1];
return env->NewStringUTF(value);
}
@@ -1262,7 +1262,7 @@
*/
static jint ExpatParser_cloneAttributes(JNIEnv* env, jobject, jint address, jint count) {
const char** source = reinterpret_cast<const char**>(static_cast<uintptr_t>(address));
- count <<= 1;
+ count *= 2;
// Figure out how big the buffer needs to be.
int arraySize = (count + 1) * sizeof(char*);
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/libcore/base/CollectionUtilsTest.java b/luni/src/test/java/libcore/base/CollectionUtilsTest.java
new file mode 100644
index 0000000..1c92a46
--- /dev/null
+++ b/luni/src/test/java/libcore/base/CollectionUtilsTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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.base;
+
+import java.lang.ref.Reference;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import junit.framework.TestCase;
+
+public final class CollectionUtilsTest extends TestCase {
+
+ public void testDereferenceIterable() {
+ List<Reference<String>> refs = new ArrayList<Reference<String>>();
+ refs.add(newLiteralReference("a"));
+ refs.add(newLiteralReference("b"));
+ refs.add(newLiteralReference("c"));
+ refs.add(newLiteralReference("d"));
+ refs.add(newLiteralReference("e"));
+
+ Iterable<String> strings = CollectionUtils.dereferenceIterable(refs, true);
+ assertEquals(Arrays.<String>asList("a", "b", "c", "d", "e"), toList(strings));
+
+ refs.get(1).clear(); // b
+ assertEquals(Arrays.<String>asList("a", "c", "d", "e"), toList(strings));
+ assertEquals(4, refs.size());
+
+ Iterator<String> i = strings.iterator();
+ assertEquals("a", i.next());
+ i.remove();
+ assertEquals(3, refs.size());
+ assertEquals("c", i.next());
+ assertEquals("d", i.next());
+ assertTrue(i.hasNext());
+ try {
+ i.remove();
+ fail("Expected hasNext() to make remove() impossible.");
+ } catch (IllegalStateException expected) {
+ }
+ assertEquals("e", i.next());
+ i.remove();
+ assertEquals(2, refs.size());
+ assertFalse(i.hasNext());
+
+ refs.get(0).clear(); // c
+ refs.get(1).clear(); // d
+ assertEquals(Arrays.<String>asList(), toList(strings));
+ }
+
+ private <T> List<T> toList(Iterable<T> iterable) {
+ List<T> result = new ArrayList<T>();
+ for (T t : iterable) {
+ result.add(t);
+ }
+ return result;
+ }
+
+ /**
+ * A reference that must be manually cleared.
+ */
+ public Reference<String> newLiteralReference(String s) {
+ return new WeakReference<String>(s);
+ }
+}
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/OldReaderTest.java b/luni/src/test/java/libcore/java/io/OldReaderTest.java
new file mode 100644
index 0000000..eb7767e
--- /dev/null
+++ b/luni/src/test/java/libcore/java/io/OldReaderTest.java
@@ -0,0 +1,124 @@
+/* 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.io;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.nio.CharBuffer;
+
+import junit.framework.TestCase;
+import tests.support.Support_ASimpleReader;
+
+public class OldReaderTest extends TestCase {
+
+ public void test_Reader() {
+ MockReader r = new MockReader();
+ assertTrue("Test 1: Lock has not been set correctly.", r.lockSet(r));
+ }
+
+ public void test_Reader_CharBufferChar() throws IOException {
+ Support_ASimpleReader simple;
+ simple = new Support_ASimpleReader("Bla bla, what else?");
+ CharBuffer buf = CharBuffer.allocate(4);
+ assertEquals("Wrong return value!", 4, simple.read(buf));
+ buf.rewind();
+ assertEquals("Wrong stuff read!", "Bla ", String.valueOf(buf));
+ simple.read(buf);
+ buf.rewind();
+ assertEquals("Wrong stuff read!", "bla,", String.valueOf(buf));
+ simple.throwExceptionOnNextUse = true;
+ try {
+ simple.read(buf);
+ fail("IOException not thrown!");
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_Read_$C() throws IOException {
+ Support_ASimpleReader simple;
+ simple = new Support_ASimpleReader("Bla bla, what else?");
+ char[] buf = new char[4];
+ assertEquals("Wrong return value!", 4, simple.read(buf));
+ assertEquals("Wrong stuff read!", "Bla ", new String(buf));
+ simple.read(buf);
+ assertEquals("Wrong stuff read!", "bla,", new String(buf));
+ simple.throwExceptionOnNextUse = true;
+ try {
+ simple.read(buf);
+ fail("IOException not thrown!");
+ } catch (IOException expected) {
+ }
+ }
+
+
+ public void test_markSupported() {
+ assertFalse("markSupported must return false", new MockReader().markSupported());
+ }
+
+ public void test_read() throws IOException {
+ Support_ASimpleReader simple = new Support_ASimpleReader("Bla bla, what else?");
+ int res = simple.read();
+ assertEquals("Wrong stuff read!", 'B', res);
+ res = simple.read();
+ assertEquals("Wrong stuff read!", 'l', res);
+ simple.throwExceptionOnNextUse = true;
+ try {
+ simple.read();
+ fail("IOException not thrown!");
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_ready() throws IOException {
+ Support_ASimpleReader simple = new Support_ASimpleReader("Bla bla, what else?");
+ simple.throwExceptionOnNextUse = true;
+ try {
+ simple.ready();
+ fail("IOException not thrown!");
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_skip() throws IOException {
+ Support_ASimpleReader simple = new Support_ASimpleReader("Bla bla, what else?");
+ char[] buf = new char[4];
+ simple.read(buf);
+ assertEquals("Wrong stuff read!", "Bla ", new String(buf));
+ simple.skip(5);
+ simple.read(buf);
+ assertEquals("Wrong stuff read!", "what", new String(buf));
+ simple.throwExceptionOnNextUse = true;
+ try {
+ simple.skip(1);
+ fail("IOException not thrown!");
+ } catch (IOException expected) {
+ }
+ }
+
+ class MockReader extends Reader {
+
+ @Override public void close() {}
+
+ @Override public int read(char[] buf, int offset, int count) {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean lockSet(Object o) {
+ return (lock == o);
+ }
+ }
+}
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/ArrayIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
new file mode 100644
index 0000000..ee7f6e8
--- /dev/null
+++ b/luni/src/test/java/libcore/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.lang;
+
+import junit.framework.TestCase;
+
+public final class ArrayIndexOutOfBoundsExceptionTest extends TestCase {
+ public void testAput() throws Exception {
+ byte[] bs = new byte[1];
+ try {
+ bs[2] = 0;
+ fail();
+ } catch (Exception ex) {
+ assertEquals("index=2 length=1", ex.getMessage());
+ }
+ }
+
+ public void testAget() throws Exception {
+ byte[] bs = new byte[1];
+ try {
+ byte b = bs[2];
+ fail();
+ } catch (Exception ex) {
+ assertEquals("index=2 length=1", ex.getMessage());
+ }
+ }
+
+ public void testAputWide() throws Exception {
+ double[] ds = new double[1];
+ try {
+ ds[2] = 0.0;
+ fail();
+ } catch (Exception ex) {
+ assertEquals("index=2 length=1", ex.getMessage());
+ }
+ }
+
+ public void testAgetWide() throws Exception {
+ double[] ds = new double[1];
+ try {
+ double d = ds[2];
+ fail();
+ } catch (Exception ex) {
+ assertEquals("index=2 length=1", ex.getMessage());
+ }
+ }
+
+ public void testAputObject() throws Exception {
+ Object[] os = new Object[1];
+ try {
+ os[2] = null;
+ fail();
+ } catch (Exception ex) {
+ assertEquals("index=2 length=1", ex.getMessage());
+ }
+ }
+
+ public void testAgetObject() throws Exception {
+ Object[] os = new Object[1];
+ try {
+ Object o = os[2];
+ fail();
+ } catch (Exception ex) {
+ assertEquals("index=2 length=1", ex.getMessage());
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
index 6b8edcb..405de6e 100644
--- a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
+++ b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
@@ -16,13 +16,21 @@
package libcore.java.lang;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
+import libcore.dalvik.system.CloseGuardTester;
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,
@@ -46,6 +54,46 @@
execAndCheckOutput(pb, "android\n", "");
}
+ public void testDestroyClosesEverything() throws IOException {
+ Process process = new ProcessBuilder(shell(), "-c", "echo out; echo err 1>&2").start();
+ InputStream in = process.getInputStream();
+ InputStream err = process.getErrorStream();
+ OutputStream out = process.getOutputStream();
+ process.destroy();
+
+ try {
+ in.read();
+ fail();
+ } catch (IOException expected) {
+ }
+ try {
+ err.read();
+ fail();
+ } catch (IOException expected) {
+ }
+ try {
+ /*
+ * We test write+flush because the RI returns a wrapped stream, but
+ * only bothers to close the underlying stream.
+ */
+ out.write(1);
+ out.flush();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testDestroyDoesNotLeak() throws IOException {
+ CloseGuardTester closeGuardTester = new CloseGuardTester();
+ try {
+ Process process = new ProcessBuilder(shell(), "-c", "echo out; echo err 1>&2").start();
+ process.destroy();
+ closeGuardTester.assertEverythingWasClosed();
+ } finally {
+ closeGuardTester.close();
+ }
+ }
+
public void testEnvironmentMapForbidsNulls() throws Exception {
ProcessBuilder pb = new ProcessBuilder(shell(), "-c", "echo $A");
Map<String, String> environment = pb.environment();
diff --git a/luni/src/test/java/libcore/java/lang/ThreadTest.java b/luni/src/test/java/libcore/java/lang/ThreadTest.java
new file mode 100644
index 0000000..3695e3e
--- /dev/null
+++ b/luni/src/test/java/libcore/java/lang/ThreadTest.java
@@ -0,0 +1,59 @@
+/*
+ * 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.lang;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import junit.framework.TestCase;
+
+public final class ThreadTest extends TestCase {
+
+ public void testLeakingStartedThreads() {
+ final AtomicInteger finalizedThreadsCount = new AtomicInteger();
+ for (int i = 0; true; i++) {
+ try {
+ newThread(finalizedThreadsCount, 1024 << i).start();
+ } catch (OutOfMemoryError expected) {
+ break;
+ }
+ }
+ System.runFinalization();
+ assertTrue("Started threads were never finalized!", finalizedThreadsCount.get() > 0);
+ }
+
+ public void testLeakingUnstartedThreads() {
+ final AtomicInteger finalizedThreadsCount = new AtomicInteger();
+ for (int i = 0; true; i++) {
+ try {
+ newThread(finalizedThreadsCount, 1024 << i);
+ } catch (OutOfMemoryError expected) {
+ break;
+ }
+ }
+ System.runFinalization();
+ assertTrue("Unstarted threads were never finalized!", finalizedThreadsCount.get() > 0);
+ }
+
+ private Thread newThread(final AtomicInteger finalizedThreadsCount, final int size) {
+ return new Thread() {
+ byte[] memoryPressure = new byte[size];
+ @Override protected void finalize() throws Throwable {
+ super.finalize();
+ finalizedThreadsCount.incrementAndGet();
+ }
+ };
+ }
+}
diff --git a/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java b/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java
index a5a72e0..2e15de2 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/ClassLoaderReflectionTest.java
@@ -16,22 +16,18 @@
package libcore.java.lang.reflect;
-import java.io.File;
-import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import junit.framework.TestCase;
+import tests.util.ClassLoaderBuilder;
/**
* This class creates another class loader to load multiple copies of various
@@ -55,7 +51,7 @@
@Override protected void setUp() throws Exception {
String prefix = ClassLoaderReflectionTest.class.getName();
- ClassLoader loader = twoCopiesClassLoader(prefix, getClass().getClassLoader());
+ ClassLoader loader = new ClassLoaderBuilder().withPrivateCopy(prefix).build();
aClass = loader.loadClass(prefix + "$A");
bClass = loader.loadClass(prefix + "$B");
cClass = loader.loadClass(prefix + "$C");
@@ -152,68 +148,6 @@
}
static class BString extends B<String> {}
- /**
- * Returns a class loader that permits multiple copies of the same class to
- * be loaded into the same VM at the same time. This loads classes using the
- * same classpath as the application class loader.
- *
- * @param prefix the prefix of classes that can be loaded by both the
- * returned class loader and the application class loader.
- */
- private ClassLoader twoCopiesClassLoader(final String prefix, ClassLoader parent)
- throws IOException, InterruptedException {
-
- /*
- * To load two copies of a given class in the VM, we end up creating two
- * new class loaders: a bridge class loader and a leaf class loader.
- *
- * The bridge class loader is a child of the application class loader.
- * It never loads any classes. All it does is decide when to delegate to
- * the application class loader (which has a copy of everything) and
- * when to fail.
- *
- * The leaf class loader is a child of the bridge class loader. It
- * uses the same classpath as the application class loader. It loads
- * anything that its parent failed on.
- */
-
- ClassLoader bridge = new ClassLoader(parent) {
- @Override protected Class<?> loadClass(String className, boolean resolve)
- throws ClassNotFoundException {
- if (className.startsWith(prefix)) {
- /* throwing will cause the child class loader to load the class. */
- throw new ClassNotFoundException();
- } else {
- return super.loadClass(className, resolve);
- }
- }
- };
-
- try {
- // first try to create a PathClassLoader for a dalvik VM...
- String classPath = System.getProperty("java.class.path");
- return (ClassLoader) Class.forName("dalvik.system.PathClassLoader")
- .getConstructor(String.class, ClassLoader.class)
- .newInstance(classPath, bridge);
- } catch (Exception ignored) {
- }
-
- // fall back to a URLClassLoader on a JVM
- List<URL> classpath = new ArrayList<URL>();
- classpath.addAll(classpathToUrls("java.class.path"));
- classpath.addAll(classpathToUrls("sun.boot.class.path"));
- return new URLClassLoader(classpath.toArray(new URL[classpath.size()]), bridge);
- }
-
- private List<URL> classpathToUrls(String propertyName) throws MalformedURLException {
- String classpath = System.getProperty(propertyName);
- List<URL> result = new ArrayList<URL>();
- for (String pathElement : classpath.split(File.pathSeparator)) {
- result.add(new File(pathElement).toURI().toURL());
- }
- return result;
- }
-
private void assertParameterizedType(Type actual, Type raw, Type... args) {
assertTrue(actual.toString(), actual instanceof ParameterizedType);
ParameterizedType parameterizedType = (ParameterizedType) actual;
diff --git a/luni/src/test/java/libcore/java/lang/reflect/MissingClassesTest.java b/luni/src/test/java/libcore/java/lang/reflect/MissingClassesTest.java
new file mode 100644
index 0000000..8b4c835
--- /dev/null
+++ b/luni/src/test/java/libcore/java/lang/reflect/MissingClassesTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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.lang.reflect;
+
+import junit.framework.TestCase;
+import tests.util.ClassLoaderBuilder;
+
+public final class MissingClassesTest extends TestCase {
+
+ private Class<?> loadableClass;
+
+ @Override protected void setUp() throws Exception {
+ String prefix = MissingClassesTest.class.getName();
+ ClassLoader cl = new ClassLoaderBuilder()
+ .withPrivateCopy(prefix + "$Loadable")
+ .without(prefix + "$Unloadable")
+ .build();
+ loadableClass = cl.loadClass(prefix + "$Loadable");
+ }
+
+ /**
+ * http://b/issue?id=2634005
+ */
+ public void testGetDeclaredFieldsFails() {
+ try {
+ loadableClass.getDeclaredFields();
+ fail();
+ } catch (NoClassDefFoundError expected) {
+ }
+ }
+
+ public void testGetDeclaredMethodsFails() {
+ try {
+ loadableClass.getDeclaredMethods();
+ fail();
+ } catch (NoClassDefFoundError expected) {
+ }
+ }
+
+ public void testGetMethodFails() throws NoSuchMethodException {
+ try {
+ loadableClass.getDeclaredMethod("method", Unloadable.class);
+ fail();
+ } catch (NoClassDefFoundError expected) {
+ }
+ }
+
+ public void testGetFieldFails() throws NoSuchFieldException {
+ try {
+ loadableClass.getDeclaredField("field");
+ fail();
+ } catch (NoClassDefFoundError expected) {
+ }
+ }
+
+ class Loadable {
+ Unloadable field;
+ void method(Unloadable unloadable) {}
+ }
+
+ class Unloadable {}
+}
diff --git a/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java b/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
index c4a662e..b7efa67 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;
@@ -208,9 +209,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
@@ -256,7 +256,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/OldURLStreamHandlerTest.java b/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
index a6804be..a75e512 100644
--- a/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
@@ -1,3 +1,19 @@
+/* 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.net;
import java.io.IOException;
@@ -38,11 +54,11 @@
URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
assertNull(handler.getHostAddress(url1));
- URL url2 = new URL("http://test:pwd@host/test?a=b&c=%D0+%D1");
- assertNull("testHost", handler.getHostAddress(url2));handler.getHostAddress(url2);
+ URL url2 = new URL("http://test:pwd@fakehostname.fakedomain/test?a=b&c=%D0+%D1");
+ assertNull(handler.getHostAddress(url2));
URL url3 = new URL("http://localhost/test");
- assertEquals(InetAddress.getLocalHost(), handler.getHostAddress(url3));
+ assertEquals(InetAddress.getByName("localhost"), handler.getHostAddress(url3));
}
public void test_hashCodeLjava_net_URL() throws MalformedURLException {
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/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
index 960a1b7..1b167e0 100644
--- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java
+++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
@@ -30,11 +30,14 @@
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.ResponseCache;
+import java.net.SecureCacheResponse;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
+import java.security.Principal;
+import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
@@ -155,7 +158,9 @@
HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
assertEquals(200, urlConnection.getResponseCode());
assertEquals("Fantastic", urlConnection.getResponseMessage());
+ assertEquals("HTTP/1.0 200 Fantastic", urlConnection.getHeaderField(null));
Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
+ assertEquals(Arrays.asList("HTTP/1.0 200 Fantastic"), responseHeaders.get(null));
assertEquals(newSet("b", "c"), new HashSet<String>(responseHeaders.get("A")));
try {
responseHeaders.put("N", Arrays.asList("o"));
@@ -198,11 +203,11 @@
server.enqueue(response);
server.play();
- assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/").openConnection());
+ assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
assertEquals(0, server.takeRequest().getSequenceNumber());
- assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/").openConnection());
+ assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
assertEquals(1, server.takeRequest().getSequenceNumber());
- assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/").openConnection());
+ assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
assertEquals(2, server.takeRequest().getSequenceNumber());
}
@@ -214,11 +219,11 @@
server.enqueue(response);
server.play();
- assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/").openConnection());
+ assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection());
assertEquals(0, server.takeRequest().getSequenceNumber());
- assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/").openConnection());
+ assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection());
assertEquals(1, server.takeRequest().getSequenceNumber());
- assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/").openConnection());
+ assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection());
assertEquals(2, server.takeRequest().getSequenceNumber());
}
@@ -628,7 +633,8 @@
* http://code.google.com/p/android/issues/detail?id=8175
*/
private void testResponseCaching(TransferKind transferKind) throws IOException {
- MockResponse response = new MockResponse();
+ MockResponse response = new MockResponse()
+ .setStatus("HTTP/1.1 200 Fantastic");
transferKind.setBody(response, "I love puppies but hate spiders", 1);
server.enqueue(response);
server.play();
@@ -637,7 +643,7 @@
ResponseCache.setDefault(cache);
// Make sure that calling skip() doesn't omit bytes from the cache.
- URLConnection urlConnection = server.getUrl("/").openConnection();
+ HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection();
InputStream in = urlConnection.getInputStream();
assertEquals("I love ", readAscii(in, "I love ".length()));
reliableSkip(in, "puppies but hate ".length());
@@ -647,10 +653,13 @@
assertEquals(1, cache.getSuccessCount());
assertEquals(0, cache.getAbortCount());
- urlConnection = server.getUrl("/").openConnection(); // this response is cached!
+ urlConnection = (HttpURLConnection) server.getUrl("/").openConnection(); // cached!
in = urlConnection.getInputStream();
assertEquals("I love puppies but hate spiders",
readAscii(in, "I love puppies but hate spiders".length()));
+ assertEquals(200, urlConnection.getResponseCode());
+ assertEquals("Fantastic", urlConnection.getResponseMessage());
+
assertEquals(-1, in.read());
assertEquals(1, cache.getMissCount());
assertEquals(1, cache.getHitCount());
@@ -658,6 +667,105 @@
assertEquals(0, cache.getAbortCount());
}
+ public void testSecureResponseCaching() throws IOException {
+ TestSSLContext testSSLContext = TestSSLContext.create();
+ server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
+ server.enqueue(new MockResponse().setBody("ABC"));
+ server.play();
+
+ DefaultResponseCache cache = new DefaultResponseCache();
+ ResponseCache.setDefault(cache);
+
+ HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
+ connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ // OpenJDK 6 fails on this line, complaining that the connection isn't open yet
+ String suite = connection.getCipherSuite();
+ List<Certificate> localCerts = toListOrNull(connection.getLocalCertificates());
+ List<Certificate> serverCerts = toListOrNull(connection.getServerCertificates());
+ Principal peerPrincipal = connection.getPeerPrincipal();
+ Principal localPrincipal = connection.getLocalPrincipal();
+
+ connection = (HttpsURLConnection) server.getUrl("/").openConnection(); // cached!
+ connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ assertEquals(1, cache.getMissCount());
+ assertEquals(1, cache.getHitCount());
+
+ assertEquals(suite, connection.getCipherSuite());
+ assertEquals(localCerts, toListOrNull(connection.getLocalCertificates()));
+ assertEquals(serverCerts, toListOrNull(connection.getServerCertificates()));
+ assertEquals(peerPrincipal, connection.getPeerPrincipal());
+ assertEquals(localPrincipal, connection.getLocalPrincipal());
+ }
+
+ public void testCacheReturnsInsecureResponseForSecureRequest() throws IOException {
+ TestSSLContext testSSLContext = TestSSLContext.create();
+ server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
+ server.enqueue(new MockResponse().setBody("ABC"));
+ server.enqueue(new MockResponse().setBody("DEF"));
+ server.play();
+
+ ResponseCache insecureResponseCache = new InsecureResponseCache();
+ ResponseCache.setDefault(insecureResponseCache);
+
+ HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
+ connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ connection = (HttpsURLConnection) server.getUrl("/").openConnection(); // not cached!
+ connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
+ assertEquals("DEF", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+ }
+
+ public void testResponseCachingAndRedirects() throws IOException {
+ server.enqueue(new MockResponse()
+ .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
+ .addHeader("Location: /foo"));
+ server.enqueue(new MockResponse().setBody("ABC"));
+ server.enqueue(new MockResponse().setBody("DEF"));
+ server.play();
+
+ DefaultResponseCache cache = new DefaultResponseCache();
+ ResponseCache.setDefault(cache);
+
+ HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ connection = (HttpURLConnection) server.getUrl("/").openConnection(); // cached!
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ assertEquals(2, cache.getMissCount()); // 1 redirect + 1 final response = 2
+ assertEquals(2, cache.getHitCount());
+ }
+
+ public void testSecureResponseCachingAndRedirects() throws IOException {
+ TestSSLContext testSSLContext = TestSSLContext.create();
+ server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
+ server.enqueue(new MockResponse()
+ .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
+ .addHeader("Location: /foo"));
+ server.enqueue(new MockResponse().setBody("ABC"));
+ server.enqueue(new MockResponse().setBody("DEF"));
+ server.play();
+
+ DefaultResponseCache cache = new DefaultResponseCache();
+ ResponseCache.setDefault(cache);
+
+ HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection();
+ connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ connection = (HttpsURLConnection) server.getUrl("/").openConnection(); // cached!
+ connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory());
+ assertEquals("ABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
+
+ assertEquals(2, cache.getMissCount()); // 1 redirect + 1 final response = 2
+ assertEquals(2, cache.getHitCount());
+ }
+
public void testResponseCacheRequestHeaders() throws IOException, URISyntaxException {
server.enqueue(new MockResponse().setBody("ABC"));
server.play();
@@ -1435,6 +1543,10 @@
return bytesOut.toByteArray();
}
+ private <T> List<T> toListOrNull(T[] arrayOrNull) {
+ return arrayOrNull != null ? Arrays.asList(arrayOrNull) : null;
+ }
+
/**
* Reads at most {@code limit} characters from {@code in} and asserts that
* content equals {@code expected}.
@@ -1571,4 +1683,28 @@
return true;
}
}
+
+ private static class InsecureResponseCache extends ResponseCache {
+ private final DefaultResponseCache delegate = new DefaultResponseCache();
+
+ @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
+ return delegate.put(uri, connection);
+ }
+
+ @Override public CacheResponse get(URI uri, String requestMethod,
+ Map<String, List<String>> requestHeaders) throws IOException {
+ final CacheResponse response = delegate.get(uri, requestMethod, requestHeaders);
+ if (response instanceof SecureCacheResponse) {
+ return new CacheResponse() {
+ @Override public InputStream getBody() throws IOException {
+ return response.getBody();
+ }
+ @Override public Map<String, List<String>> getHeaders() throws IOException {
+ return response.getHeaders();
+ }
+ };
+ }
+ return response;
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/nio/BufferTest.java b/luni/src/test/java/libcore/java/nio/BufferTest.java
new file mode 100644
index 0000000..712e964
--- /dev/null
+++ b/luni/src/test/java/libcore/java/nio/BufferTest.java
@@ -0,0 +1,303 @@
+/*
+ * 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;
+
+import java.nio.*;
+import java.util.Arrays;
+import junit.framework.TestCase;
+
+public class BufferTest extends TestCase {
+ 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);
+ }
+ b.position(1);
+
+ char[] chars = new char[6];
+ b.order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(chars, 1, 4);
+ assertEquals("[\u0000, \u0102, \u0304, \u0506, \u0708, \u0000]", Arrays.toString(chars));
+ b.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer().get(chars, 1, 4);
+ assertEquals("[\u0000, \u0201, \u0403, \u0605, \u0807, \u0000]", Arrays.toString(chars));
+
+ double[] doubles = new double[3];
+ b.order(ByteOrder.BIG_ENDIAN).asDoubleBuffer().get(doubles, 1, 1);
+ assertEquals(0, Double.doubleToRawLongBits(doubles[0]));
+ assertEquals(0x0102030405060708L, Double.doubleToRawLongBits(doubles[1]));
+ assertEquals(0, Double.doubleToRawLongBits(doubles[2]));
+ b.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer().get(doubles, 1, 1);
+ assertEquals(0, Double.doubleToRawLongBits(doubles[0]));
+ assertEquals(0x0807060504030201L, Double.doubleToRawLongBits(doubles[1]));
+ assertEquals(0, Double.doubleToRawLongBits(doubles[2]));
+
+ float[] floats = new float[4];
+ b.order(ByteOrder.BIG_ENDIAN).asFloatBuffer().get(floats, 1, 2);
+ assertEquals(0, Float.floatToRawIntBits(floats[0]));
+ assertEquals(0x01020304, Float.floatToRawIntBits(floats[1]));
+ assertEquals(0x05060708, Float.floatToRawIntBits(floats[2]));
+ assertEquals(0, Float.floatToRawIntBits(floats[3]));
+ b.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer().get(floats, 1, 2);
+ assertEquals(0, Float.floatToRawIntBits(floats[0]));
+ assertEquals(0x04030201, Float.floatToRawIntBits(floats[1]));
+ assertEquals(0x08070605, Float.floatToRawIntBits(floats[2]));
+ assertEquals(0, Float.floatToRawIntBits(floats[3]));
+
+ int[] ints = new int[4];
+ b.order(ByteOrder.BIG_ENDIAN).asIntBuffer().get(ints, 1, 2);
+ assertEquals(0, ints[0]);
+ assertEquals(0x01020304, ints[1]);
+ assertEquals(0x05060708, ints[2]);
+ assertEquals(0, ints[3]);
+ b.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(ints, 1, 2);
+ assertEquals(0, ints[0]);
+ assertEquals(0x04030201, ints[1]);
+ assertEquals(0x08070605, ints[2]);
+ assertEquals(0, ints[3]);
+
+ long[] longs = new long[3];
+ b.order(ByteOrder.BIG_ENDIAN).asLongBuffer().get(longs, 1, 1);
+ assertEquals(0, longs[0]);
+ assertEquals(0x0102030405060708L, longs[1]);
+ assertEquals(0, longs[2]);
+ b.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().get(longs, 1, 1);
+ assertEquals(0, longs[0]);
+ assertEquals(0x0807060504030201L, longs[1]);
+ assertEquals(0, longs[2]);
+
+ short[] shorts = new short[6];
+ b.order(ByteOrder.BIG_ENDIAN).asShortBuffer().get(shorts, 1, 4);
+ assertEquals(0, shorts[0]);
+ assertEquals(0x0102, shorts[1]);
+ assertEquals(0x0304, shorts[2]);
+ assertEquals(0x0506, shorts[3]);
+ assertEquals(0x0708, shorts[4]);
+ assertEquals(0, shorts[5]);
+ b.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts, 1, 4);
+ assertEquals(0, shorts[0]);
+ assertEquals(0x0201, shorts[1]);
+ assertEquals(0x0403, shorts[2]);
+ assertEquals(0x0605, shorts[3]);
+ assertEquals(0x0807, shorts[4]);
+ assertEquals(0, shorts[5]);
+ }
+
+ 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)));
+ }
+ return result.toString();
+ }
+
+ 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' };
+ b.order(ByteOrder.BIG_ENDIAN).asCharBuffer().put(chars, 1, 4);
+ assertEquals("00010203040506070800", toString(b));
+ b.order(ByteOrder.LITTLE_ENDIAN).asCharBuffer().put(chars, 1, 4);
+ assertEquals("00020104030605080700", toString(b));
+
+ double[] doubles = new double[] { 0, Double.longBitsToDouble(0x0102030405060708L), 0 };
+ b.order(ByteOrder.BIG_ENDIAN).asDoubleBuffer().put(doubles, 1, 1);
+ assertEquals("00010203040506070800", toString(b));
+ b.order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer().put(doubles, 1, 1);
+ assertEquals("00080706050403020100", toString(b));
+
+ float[] floats = new float[] { 0, Float.intBitsToFloat(0x01020304),
+ Float.intBitsToFloat(0x05060708), 0 };
+ b.order(ByteOrder.BIG_ENDIAN).asFloatBuffer().put(floats, 1, 2);
+ assertEquals("00010203040506070800", toString(b));
+ b.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer().put(floats, 1, 2);
+ assertEquals("00040302010807060500", toString(b));
+
+ int[] ints = new int[] { 0, 0x01020304, 0x05060708, 0 };
+ b.order(ByteOrder.BIG_ENDIAN).asIntBuffer().put(ints, 1, 2);
+ assertEquals("00010203040506070800", toString(b));
+ b.order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(ints, 1, 2);
+ assertEquals("00040302010807060500", toString(b));
+
+ long[] longs = new long[] { 0, 0x0102030405060708L, 0 };
+ b.order(ByteOrder.BIG_ENDIAN).asLongBuffer().put(longs, 1, 1);
+ assertEquals("00010203040506070800", toString(b));
+ b.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer().put(longs, 1, 1);
+ assertEquals("00080706050403020100", toString(b));
+
+ short[] shorts = new short[] { 0, 0x0102, 0x0304, 0x0506, 0x0708, 0 };
+ b.order(ByteOrder.BIG_ENDIAN).asShortBuffer().put(shorts, 1, 4);
+ assertEquals("00010203040506070800", toString(b));
+ 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/NoArrayTest.java b/luni/src/test/java/libcore/java/nio/NoArrayTest.java
new file mode 100644
index 0000000..04d9af1
--- /dev/null
+++ b/luni/src/test/java/libcore/java/nio/NoArrayTest.java
@@ -0,0 +1,51 @@
+/* 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.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ReadOnlyBufferException;
+import junit.framework.TestCase;
+
+public final class NoArrayTest extends TestCase {
+
+ public void testWrappedReadOnly() {
+ assertNoArray(ByteBuffer.wrap(new byte[32]).asReadOnlyBuffer());
+ }
+
+ public void testAllocatedReadOnly() {
+ assertNoArray(ByteBuffer.allocate(32).asReadOnlyBuffer());
+ }
+
+ public void testAllocatedDirect() {
+ assertNoArray(ByteBuffer.allocateDirect(32));
+ }
+
+ private void assertNoArray(ByteBuffer buf) {
+ try {
+ buf.asReadOnlyBuffer().array();
+ fail();
+ } catch (ReadOnlyBufferException expected) {
+ } catch (UnsupportedOperationException expected) {
+ }
+ try {
+ buf.arrayOffset();
+ fail();
+ } catch (ReadOnlyBufferException expected) {
+ } catch (UnsupportedOperationException expected) {
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/nio/OldDirectIntBufferTest.java b/luni/src/test/java/libcore/java/nio/OldDirectIntBufferTest.java
new file mode 100644
index 0000000..4274f42
--- /dev/null
+++ b/luni/src/test/java/libcore/java/nio/OldDirectIntBufferTest.java
@@ -0,0 +1,42 @@
+/* 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.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.IntBuffer;
+import junit.framework.TestCase;
+
+public final class OldDirectIntBufferTest extends TestCase {
+
+ /**
+ * Regression for http://code.google.com/p/android/issues/detail?id=3279
+ */
+ public void testPutWhenOffsetIsNonZero() {
+ ByteBuffer byteBuffer = ByteBuffer.allocateDirect(40);
+ byteBuffer.order(ByteOrder.nativeOrder());
+ IntBuffer intBuffer = byteBuffer.asIntBuffer();
+
+ int[] source = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
+
+ intBuffer.put(source, 2, 2);
+ intBuffer.put(source, 4, 2);
+ assertEquals(4, intBuffer.get(0));
+ assertEquals(5, intBuffer.get(1));
+ assertEquals(6, intBuffer.get(2));
+ assertEquals(7, intBuffer.get(3));
+ }
+}
diff --git a/luni/src/test/java/libcore/java/nio/OldDirectShortBufferTest.java b/luni/src/test/java/libcore/java/nio/OldDirectShortBufferTest.java
new file mode 100644
index 0000000..7a93857
--- /dev/null
+++ b/luni/src/test/java/libcore/java/nio/OldDirectShortBufferTest.java
@@ -0,0 +1,42 @@
+/* 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.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.ShortBuffer;
+import junit.framework.TestCase;
+
+public final class OldDirectShortBufferTest extends TestCase {
+
+ /**
+ * Regression for http://code.google.com/p/android/issues/detail?id=3279
+ */
+ public void testPutWhenOffsetIsNonZero() {
+ ByteBuffer byteBuffer = ByteBuffer.allocateDirect(40);
+ byteBuffer.order(ByteOrder.nativeOrder());
+ ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
+
+ short[] source = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
+
+ shortBuffer.put(source, 2, 2);
+ shortBuffer.put(source, 4, 2);
+ assertEquals(4, shortBuffer.get(0));
+ assertEquals(5, shortBuffer.get(1));
+ assertEquals(6, shortBuffer.get(2));
+ assertEquals(7, shortBuffer.get(3));
+ }
+}
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/nio/charset/CharsetEncoderTest.java b/luni/src/test/java/libcore/java/nio/charset/CharsetEncoderTest.java
index 9632ffe..87e7306 100644
--- a/luni/src/test/java/libcore/java/nio/charset/CharsetEncoderTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/CharsetEncoderTest.java
@@ -41,12 +41,22 @@
}
// For all the guaranteed built-in charsets, check that we have the right default replacements.
- public void test_defaultReplacementBytes() throws Exception {
+ public void test_defaultReplacementBytesIso_8859_1() throws Exception {
assertReplacementBytesForEncoder("ISO-8859-1", new byte[] { (byte) '?' });
+ }
+ public void test_defaultReplacementBytesUs_Ascii() throws Exception {
assertReplacementBytesForEncoder("US-ASCII", new byte[] { (byte) '?' });
+ }
+ public void test_defaultReplacementBytesUtf_16() throws Exception {
assertReplacementBytesForEncoder("UTF-16", new byte[] { (byte) 0xff, (byte) 0xfd });
+ }
+ public void test_defaultReplacementBytesUtf_16be() throws Exception {
assertReplacementBytesForEncoder("UTF-16BE", new byte[] { (byte) 0xff, (byte) 0xfd });
+ }
+ public void test_defaultReplacementBytesUtf_16le() throws Exception {
assertReplacementBytesForEncoder("UTF-16LE", new byte[] { (byte) 0xfd, (byte) 0xff });
+ }
+ public void test_defaultReplacementBytesUtf_8() throws Exception {
assertReplacementBytesForEncoder("UTF-8", new byte[] { (byte) '?' });
}
}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_TestGenerator.java b/luni/src/test/java/libcore/java/nio/charset/Charset_TestGenerator.java
similarity index 97%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_TestGenerator.java
rename to luni/src/test/java/libcore/java/nio/charset/Charset_TestGenerator.java
index 387ebf5..b189382 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_TestGenerator.java
+++ b/luni/src/test/java/libcore/java/nio/charset/Charset_TestGenerator.java
@@ -13,13 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
+package libcore.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
@@ -104,7 +98,7 @@
32013, 32046, 32079, 32112, 32145, 32178, 32211, 32244, 32277, 32310, 32343, 32376, 32409, 32442, 32475, 32508,
32541, 32574, 32607, 32640, 32673, 32706, 32739
};
- static final char[] chars = Charset_AbstractTest.theseChars(codes);
+ static final char[] chars = OldCharset_AbstractTest.theseChars(codes);
static abstract class CodesGenerator {
int row = 0, col = 0;
diff --git a/luni/src/test/java/libcore/java/nio/charset/CharsetDecoderTest.java b/luni/src/test/java/libcore/java/nio/charset/OldCharsetDecoderTest.java
similarity index 98%
rename from luni/src/test/java/libcore/java/nio/charset/CharsetDecoderTest.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharsetDecoderTest.java
index fa8eab5..8f37f63 100644
--- a/luni/src/test/java/libcore/java/nio/charset/CharsetDecoderTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharsetDecoderTest.java
@@ -25,7 +25,7 @@
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
-public class CharsetDecoderTest extends junit.framework.TestCase {
+public class OldCharsetDecoderTest extends junit.framework.TestCase {
private static final String CHARSET = "UTF-16";
private static final String SAMPLE_STRING = "Android";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/CharsetEncoderDecoderBufferTest.java b/luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java
similarity index 84%
rename from luni/src/test/java/tests/api/java/nio/charset/CharsetEncoderDecoderBufferTest.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java
index 5e4c3d0..583cb47 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/CharsetEncoderDecoderBufferTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java
@@ -14,41 +14,26 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
+import junit.framework.TestCase;
/* See bug 1844104.
* Checks for ICU encoder/decoder buffer corruption.
*/
-@TestTargetClass(CharsetDecoder.class)
-public class CharsetEncoderDecoderBufferTest extends TestCase {
+public class OldCharsetEncoderDecoderBufferTest extends TestCase {
/* Checks for a buffer corruption that happens in ICU
* (CharsetDecoderICU) when a decode operation
* is done first with an out-buffer with hasArray()==true, and next with an out-buffer with
* hasArray()==false. In that situation ICU may overwrite the first out-buffer.
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {}
- )
- })
public void testDecoderOutputBuffer() {
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
@@ -81,14 +66,6 @@
* is done first with an in-buffer with hasArray()==true, and next with an in-buffer with
* hasArray()==false. In that situation ICU may overwrite the array of the first in-buffer.
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {}
- )
- })
public void testDecoderInputBuffer() {
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
CharBuffer out = CharBuffer.wrap(new char[10]);
@@ -115,14 +92,6 @@
* is done first with an out-buffer with hasArray()==true, and next with an out-buffer with
* hasArray()==false. In that situation ICU may overwrite the first out-buffer.
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "encode",
- args = {}
- )
- })
public void testEncoderOutputBuffer() {
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
@@ -151,14 +120,6 @@
* is done first with an in-buffer with hasArray()==true, and next with an in-buffer with
* hasArray()==false. In that situation ICU may overwrite the array of the first in-buffer.
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "encode",
- args = {}
- )
- })
public void testEncoderInputBuffer() {
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
ByteBuffer out = ByteBuffer.wrap(new byte[10]);
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_AbstractTest.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_AbstractTest.java
similarity index 91%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_AbstractTest.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_AbstractTest.java
index 386d5c5..d6a635e 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_AbstractTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_AbstractTest.java
@@ -14,13 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
+package libcore.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
@@ -29,12 +23,12 @@
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
-import java.util.Arrays;
+import junit.framework.TestCase;
/**
* Super class for concrete charset test suites.
*/
-public class Charset_AbstractTest extends TestCase {
+public abstract class OldCharset_AbstractTest extends TestCase {
static String charsetName;
static private Charset charset;
@@ -75,20 +69,10 @@
super.tearDown();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
public void test_nameMatch () {
assertEquals("Name of charset must match!", charsetName, charset.name());
}
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public void test_dumpEncodableChars () {
if (testChars == null) return;
if (testChars.length > 0) return;
@@ -115,11 +99,6 @@
fail("Encodable Chars dumped for Test Class " + getClass().getName());
}
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public void test_dumpEncoded () throws CharacterCodingException {
if (testChars == null) return;
if (testChars.length == 0) return;
@@ -169,20 +148,10 @@
// outputCB.toString());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
public void test_Decode () throws CharacterCodingException {
decode(testBytes, testChars);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
public void test_Encode () throws CharacterCodingException {
CharBuffer inputCB = CharBuffer.wrap(testChars);
ByteBuffer outputBB;
@@ -224,11 +193,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
public void test_CodecDynamic () throws CharacterCodingException {
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
decoder.onMalformedInput(CodingErrorAction.REPORT);
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_GSM0338.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_GSM0338.java
similarity index 82%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_GSM0338.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_GSM0338.java
index 977d4d7..a8d2669 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_GSM0338.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_GSM0338.java
@@ -13,17 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.charset.CharacterCodingException;
-@AndroidOnly("gsm specific")
-public class Charset_GSM0338 extends Charset_AbstractTest {
+/** Note: this test is GSM specific */
+public class OldCharset_GSM0338 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
@@ -55,12 +50,6 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Not applicable to this charset.",
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_CodecDynamic () throws CharacterCodingException {
}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_10.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_10.java
similarity index 93%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_10.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_10.java
index 051e72d..c7bbc94 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_10.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_10.java
@@ -13,13 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
-
-@AndroidOnly("icu")
-public class Charset_ISO_8859_10 extends Charset_AbstractTest {
+/** Note: ICU only */
+public class OldCharset_ISO_8859_10 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_14.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_14.java
similarity index 84%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_14.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_14.java
index a53fbc98..1daedf5 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_14.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_14.java
@@ -13,25 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-@AndroidOnly("icu")
-public class Charset_ISO_8859_14 extends Charset_AbstractTest {
+/** Note: ICU only */
+public class OldCharset_ISO_8859_14 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_16.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_16.java
similarity index 93%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_16.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_16.java
index b740582..edb219a 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_ISO_8859_16.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_ISO_8859_16.java
@@ -13,13 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
-
-@AndroidOnly("icu")
-public class Charset_ISO_8859_16 extends Charset_AbstractTest {
+/** Note: ICU only */
+public class OldCharset_ISO_8859_16 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_Big5.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_Big5.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_Big5.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_Big5.java
index 1847278..0330cd5 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_Big5.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_Big5.java
@@ -13,27 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
+package libcore.java.nio.charset;
/** @hide
* SEE correspondig_Android test class:
*/
-public class Charset_MultiByte_Big5 extends Charset_AbstractTest {
+public class OldCharset_MultiByte_Big5 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_Big5_Android.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_Big5_Android.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_Big5_Android.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_Big5_Android.java
index 663023b..b1a71f0 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_Big5_Android.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_Big5_Android.java
@@ -13,14 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
+/** Note: ICU behaves differently from the RI */
-@AndroidOnly("icu different from RI")
-
-public class Charset_MultiByte_Big5_Android extends Charset_AbstractTest {
+public class OldCharset_MultiByte_Big5_Android extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_JP.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_JP.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_JP.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_JP.java
index 2dbff5e..2e7fcc2 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_JP.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_JP.java
@@ -13,27 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
+package libcore.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
/** @hide
* SEE correspondig_Android test class:
*/
-public class Charset_MultiByte_EUC_JP extends Charset_AbstractTest {
+public class OldCharset_MultiByte_EUC_JP extends OldCharset_AbstractTest {
protected void setUp() throws Exception {
charsetName = "EUC-JP";
@@ -510,12 +501,6 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Duplicate Characters.",
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_CodecDynamic () throws CharacterCodingException {
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_JP_Android.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_JP_Android.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_JP_Android.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_JP_Android.java
index 3f80cd8..373c97f 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_JP_Android.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_JP_Android.java
@@ -13,21 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
-@AndroidOnly("icu different from RI")
+/** Note: ICU behaves differently from the RI */
-public class Charset_MultiByte_EUC_JP_Android extends Charset_AbstractTest {
+public class OldCharset_MultiByte_EUC_JP_Android extends OldCharset_AbstractTest {
protected void setUp() throws Exception {
charsetName = "EUC-JP";
@@ -504,12 +499,6 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Duplicate Characters.",
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_CodecDynamic () throws CharacterCodingException {
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_KR.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_KR.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_KR.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_KR.java
index 90ae541..c64e0b9 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_EUC_KR.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_EUC_KR.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_MultiByte_EUC_KR extends Charset_AbstractTest {
+public class OldCharset_MultiByte_EUC_KR extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GB2312.java
similarity index 94%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GB2312.java
index 9b178d8..4f6123a 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GB2312.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GB2312.java
@@ -13,16 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.charset.CharacterCodingException;
-public class Charset_MultiByte_GB2312 extends Charset_AbstractTest {
+public class OldCharset_MultiByte_GB2312 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
@@ -175,41 +170,21 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_CodecDynamic() throws CharacterCodingException {
super.test_CodecDynamic();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Decode() throws CharacterCodingException {
super.test_Decode();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Encode() throws CharacterCodingException {
super.test_Encode();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_nameMatch() {
super.test_nameMatch();
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GBK.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GBK.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GBK.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GBK.java
index dc446df..8de181b 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GBK.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GBK.java
@@ -13,27 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
+package libcore.java.nio.charset;
/** @hide
* SEE correspondig_Android test class:
*/
-public class Charset_MultiByte_GBK extends Charset_AbstractTest {
+public class OldCharset_MultiByte_GBK extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GBK_Android.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GBK_Android.java
similarity index 99%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GBK_Android.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GBK_Android.java
index 71a9932..cc0c60b 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_GBK_Android.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_GBK_Android.java
@@ -13,14 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
+/** Note: ICU behaves differently from the RI */
-@AndroidOnly("icu different from RI")
-
-public class Charset_MultiByte_GBK_Android extends Charset_AbstractTest {
+public class OldCharset_MultiByte_GBK_Android extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_ISO_2022_JP.java
similarity index 97%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_ISO_2022_JP.java
index 0e1aaa6..b789ce3 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_ISO_2022_JP.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_ISO_2022_JP.java
@@ -13,16 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.charset.CharacterCodingException;
-public class Charset_MultiByte_ISO_2022_JP extends Charset_AbstractTest {
+public class OldCharset_MultiByte_ISO_2022_JP extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
@@ -368,31 +363,16 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_CodecDynamic() throws CharacterCodingException {
super.test_CodecDynamic();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Decode() throws CharacterCodingException {
super.test_Decode();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Encode() throws CharacterCodingException {
super.test_Encode();
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16.java
similarity index 97%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16.java
index 7457a87..29c42a3 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16.java
@@ -13,27 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
+package libcore.java.nio.charset;
/** @hide
* SEE correspondig_Android test class:
*/
-public class Charset_MultiByte_UTF_16 extends Charset_AbstractTest {
+public class OldCharset_MultiByte_UTF_16 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16BE.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16BE.java
similarity index 97%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16BE.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16BE.java
index 5f5a2bf..2200718 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16BE.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16BE.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_MultiByte_UTF_16BE extends Charset_AbstractTest {
+public class OldCharset_MultiByte_UTF_16BE extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16LE.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16LE.java
similarity index 97%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16LE.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16LE.java
index c907f52..d83d79d 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16LE.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16LE.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_MultiByte_UTF_16LE extends Charset_AbstractTest {
+public class OldCharset_MultiByte_UTF_16LE extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16_Android.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16_Android.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16_Android.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16_Android.java
index ebdd9fc..b9c7c03 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_16_Android.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_16_Android.java
@@ -13,14 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
+/** Note: ICU behaves differently from the RI */
-@AndroidOnly("icu different from RI")
-
-public class Charset_MultiByte_UTF_16_Android extends Charset_AbstractTest {
+public class OldCharset_MultiByte_UTF_16_Android extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_8.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_8.java
similarity index 98%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_8.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_8.java
index fb3e4ba..d899057 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_UTF_8.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_8.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_MultiByte_UTF_8 extends Charset_AbstractTest {
+public class OldCharset_MultiByte_UTF_8 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_x_windows_950.java
similarity index 95%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_x_windows_950.java
index 0823dc8..7525474 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_x_windows_950.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_x_windows_950.java
@@ -13,16 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.charset.CharacterCodingException;
-public class Charset_MultiByte_x_windows_950 extends Charset_AbstractTest {
+public class OldCharset_MultiByte_x_windows_950 extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
@@ -224,41 +219,21 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_CodecDynamic() throws CharacterCodingException {
super.test_CodecDynamic();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Decode() throws CharacterCodingException {
super.test_Decode();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Encode() throws CharacterCodingException {
super.test_Encode();
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_nameMatch() {
super.test_nameMatch();
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByteAbstractTest.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByteAbstractTest.java
similarity index 90%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByteAbstractTest.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByteAbstractTest.java
index f895c0c..8ac6eb6 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByteAbstractTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByteAbstractTest.java
@@ -13,23 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
-import java.util.Arrays;
/**
* Super class for concrete charset test suites.
*/
-public class Charset_SingleByteAbstractTest extends Charset_AbstractTest {
+public abstract class OldCharset_SingleByteAbstractTest extends OldCharset_AbstractTest {
static byte[] allBytes;
static char[] allChars;
@@ -71,6 +65,7 @@
ByteBuffer inputBB = ByteBuffer.wrap(input);
CharBuffer outputCB;
decoder.onMalformedInput(CodingErrorAction.REPLACE);
+ decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
outputCB = decoder.decode(inputBB);
outputCB.rewind();
assertEqualChars2("Decoded charactes must match!",
@@ -89,11 +84,6 @@
// outputCB.toString());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Decode () throws CharacterCodingException {
decodeReplace(allBytes, allChars);
@@ -110,11 +100,6 @@
//// outputCB.toString());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "functionalCoDec_REPR",
- args = {}
- )
@Override
public void test_Encode () throws CharacterCodingException {
CharBuffer inputCB = CharBuffer.wrap(allChars);
@@ -205,11 +190,4 @@
assertTrue(msg, match);
}
- public static void main(String[] args) {
-// charset = Charset.defaultCharset();
-// decoder = charset.newDecoder();
-// System.out.println(charset.name());
- dumpDecoded();
- }
-
}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_IBM864.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_IBM864.java
similarity index 91%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_IBM864.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_IBM864.java
index 730285b..8698d68 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_IBM864.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_IBM864.java
@@ -13,18 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.nio.charset;
import java.nio.charset.CharacterCodingException;
-@AndroidOnly("icu different from RI")
+/** Note: ICU behaves differently from the RI */
-public class Charset_SingleByte_IBM864 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_IBM864 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
// charsetName = "IBM864"; // ICU name "cp864", wanted Android name "CP864"
@@ -74,11 +69,6 @@
// new char[] {26, 28, 1642, 127, 65533, 65217, 65221, 1617} );
// }
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public static void test_Bytes_DifferentOnes_Android() throws CharacterCodingException {
// Android:
decodeReplace(
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_1.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_1.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_1.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_1.java
index 4d28cf8..31cede6 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_1.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_1.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_1 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_1 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-1";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_11.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_11.java
similarity index 79%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_11.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_11.java
index 04a544d..7da6da4 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_11.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_11.java
@@ -13,25 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-@AndroidOnly("charset x-iso-8859_11-2001 not supported ")
-public class Charset_SingleByte_ISO_8859_11 extends Charset_SingleByteAbstractTest {
+/* charset x-iso-8859_11-2001 not supported on the RI */
+public class OldCharset_SingleByte_ISO_8859_11 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
// charsetName = "ISO-8859-11";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_13.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_13.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_13.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_13.java
index b65038f..23efed0 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_13.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_13.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_13 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_13 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-13";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_15.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_15.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_15.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_15.java
index 228cdfd..76eb556 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_15.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_15.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_15 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_15 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-15";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_2.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_2.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_2.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_2.java
index a0952b9..d51b203 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_2.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_2.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_2 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_2 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-2";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_3.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_3.java
similarity index 78%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_3.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_3.java
index 1af2add..fe4fbf6 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_3.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_3.java
@@ -13,23 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-public class Charset_SingleByte_ISO_8859_3 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_3 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-3";
@@ -53,11 +41,6 @@
super.setUp();
}
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public static void test_Bytes_166() throws CharacterCodingException {
decodeReplace(
new byte[] {(byte)166},
@@ -73,33 +56,18 @@
// outputCB.array());
}
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public static void test_Bytes_195() throws CharacterCodingException {
decodeReplace(
new byte[] {(byte)195},
new char[] {65533} );
}
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public static void test_Bytes_165() throws CharacterCodingException {
decodeReplace(
new byte[] {(byte)165},
new char[] {65533} );
}
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "functionalCoDec_REPR",
- args = {}
- )
public static void test_Bytes_165_any() throws CharacterCodingException {
decodeReplace(
new byte[] {(byte)165, 32},
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_4.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_4.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_4.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_4.java
index c5c0778..dbde77c 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_4.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_4.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_4 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_4 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-4";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_5.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_5.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_5.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_5.java
index 0bf11f6..229137c 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_5.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_5.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_5 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_5 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-5";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_6.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_6.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_6.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_6.java
index b2caf2a..294bee5 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_6.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_6.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_6 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_6 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-6";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_7.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_7.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_7.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_7.java
index 7a920d3..6249b10 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_7.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_7.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_7 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_7 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-7";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_8.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_8.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_8.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_8.java
index 72a26eb..e3054f7 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_8.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_8.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_8 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_8 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-8";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_9.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_9.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_9.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_9.java
index 99e7617..c623e23 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_ISO_8859_9.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_ISO_8859_9.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ISO_8859_9 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_ISO_8859_9 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "ISO-8859-9";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_KOI8_R.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_KOI8_R.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_KOI8_R.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_KOI8_R.java
index 0247752..cb6532e 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_KOI8_R.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_KOI8_R.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_KOI8_R extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_KOI8_R extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "KOI8-R";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_US_ASCII.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_US_ASCII.java
similarity index 82%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_US_ASCII.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_US_ASCII.java
index a76d619..ae15a60 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_US_ASCII.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_US_ASCII.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_US_ASCII extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_US_ASCII extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "US-ASCII";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1250.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1250.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1250.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1250.java
index 09b7ed2..cbb534e 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1250.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1250.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1250 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1250 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1250";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1251.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1251.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1251.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1251.java
index eaaf422..23f5a31 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1251.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1251.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1251 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1251 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1251";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1252.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1252.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1252.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1252.java
index f2baf89..813219b 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1252.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1252.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1252 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1252 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1252";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1253.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1253.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1253.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1253.java
index b231f8b..c657a8e 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1253.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1253.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1253 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1253 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1253";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1254.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1254.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1254.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1254.java
index df65bbe..5661f1f 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1254.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1254.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1254 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1254 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1254";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1255.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1255.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1255.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1255.java
index 6adb2be..cb279d5 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1255.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1255.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1255 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1255 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1255";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1256.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1256.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1256.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1256.java
index 4284f78..99976b9 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1256.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1256.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1256 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1256 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1256";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1257.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1257.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1257.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1257.java
index c68b08c..4f60587 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1257.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1257.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1257 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1257 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1257";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1258.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1258.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1258.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1258.java
index 638db84..f40e5ff 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_windows_1258.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_windows_1258.java
@@ -13,23 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_windows_1258 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_windows_1258 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
charsetName = "windows-1258";
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_x_IBM874.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_x_IBM874.java
similarity index 87%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_x_IBM874.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_x_IBM874.java
index 81293d2..c6fd869 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_x_IBM874.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_SingleByte_x_IBM874.java
@@ -13,18 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+/** Note: ICU behaves differently from the RI */
-import java.nio.charset.CharacterCodingException;
-
-@AndroidOnly("icu different from RI")
-
-public class Charset_SingleByte_x_IBM874 extends Charset_SingleByteAbstractTest {
+public class OldCharset_SingleByte_x_IBM874 extends OldCharset_SingleByteAbstractTest {
protected void setUp() throws Exception {
// charsetName = "x-IBM874"; // ICU name "TIS-620", wanted Android name "CP874"
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_macintosh.java b/luni/src/test/java/libcore/java/nio/charset/OldCharset_macintosh.java
similarity index 84%
rename from luni/src/test/java/tests/api/java/nio/charset/Charset_macintosh.java
rename to luni/src/test/java/libcore/java/nio/charset/OldCharset_macintosh.java
index 9427d62..93f0d1f 100644
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_macintosh.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharset_macintosh.java
@@ -13,25 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package tests.api.java.nio.charset;
+package libcore.java.nio.charset;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-@AndroidOnly("icu")
-public class Charset_macintosh extends Charset_AbstractTest {
+/** Note: ICU only */
+public class OldCharset_macintosh extends OldCharset_AbstractTest {
@Override
protected void setUp() throws Exception {
diff --git a/luni/src/test/java/libcore/java/security/KeyStoreTest.java b/luni/src/test/java/libcore/java/security/KeyStoreTest.java
index 072bd6d..0c0db70 100644
--- a/luni/src/test/java/libcore/java/security/KeyStoreTest.java
+++ b/luni/src/test/java/libcore/java/security/KeyStoreTest.java
@@ -53,13 +53,9 @@
public class KeyStoreTest extends TestCase {
private static final PrivateKeyEntry PRIVATE_KEY
- = TestKeyStore.privateKey(TestKeyStore.getServer().keyStore,
- TestKeyStore.getServer().keyPassword,
- "RSA");
+ = TestKeyStore.getServer().getPrivateKey("RSA");
private static final PrivateKeyEntry PRIVATE_KEY_2
- = TestKeyStore.privateKey(TestKeyStore.getClientCertificate().keyStore,
- TestKeyStore.getClientCertificate().keyPassword,
- "RSA");
+ = TestKeyStore.getClientCertificate().getPrivateKey("RSA");
private static final SecretKey SECRET_KEY = generateSecretKey();
private static final SecretKey SECRET_KEY_2 = generateSecretKey();
@@ -91,7 +87,7 @@
private static final ProtectionParameter PARAM_KEY = new PasswordProtection(PASSWORD_KEY);
private static final ProtectionParameter PARAM_BAD = new PasswordProtection(PASSWORD_BAD);
- public static List<KeyStore> keyStores () throws Exception {
+ public static List<KeyStore> keyStores() throws Exception {
List<KeyStore> keyStores = new ArrayList<KeyStore>();
Provider[] providers = Security.getProviders();
for (Provider provider : providers) {
@@ -577,7 +573,8 @@
public void test_KeyStore_getCreationDate() throws Exception {
for (KeyStore keyStore : keyStores()) {
try {
- assertNotNull(keyStore.getCreationDate(null));
+ keyStore.getCreationDate(null);
+ fail();
} catch (KeyStoreException expected) {
}
}
@@ -905,6 +902,7 @@
} else {
try {
keyStore.setCertificateEntry(ALIAS_CERTIFICATE, null);
+ fail();
} catch (KeyStoreException expected) {
}
}
@@ -1379,7 +1377,7 @@
return null;
}
});
- assertEquals(0, keyStore.size());
+ fail();
} catch (UnsupportedOperationException expected) {
}
}
@@ -1762,6 +1760,7 @@
Builder.newInstance(keyStore.getType(),
keyStore.getProvider(),
null);
+ fail();
} catch (NullPointerException expected) {
}
}
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/text/SimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
index 5df96f8..78445bc 100644
--- a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
@@ -16,6 +16,7 @@
package libcore.java.text;
+import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
@@ -71,7 +72,9 @@
}
private String formatDate(Locale l, String fmt) {
- return new SimpleDateFormat(fmt, l).format(new Date(0));
+ DateFormat dateFormat = new SimpleDateFormat(fmt, l);
+ dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return dateFormat.format(new Date(0));
}
private Calendar parseDate(Locale l, String fmt, String value) {
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/libcore/java/util/zip/DeflaterInputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/DeflaterInputStreamTest.java
new file mode 100644
index 0000000..938b16e
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/zip/DeflaterInputStreamTest.java
@@ -0,0 +1,112 @@
+/*
+ * 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.util.zip;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.zip.DeflaterInputStream;
+import java.util.zip.InflaterInputStream;
+import junit.framework.TestCase;
+
+public final class DeflaterInputStreamTest extends TestCase {
+
+ public void testReadByteByByte() throws IOException {
+ byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+ InputStream in = new DeflaterInputStream(new ByteArrayInputStream(data));
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+
+ assertEquals(1, in.available());
+ int b;
+ while ((b = in.read()) != -1) {
+ out.write(b);
+ }
+ assertEquals(0, in.available());
+
+ assertEquals(Arrays.toString(data), Arrays.toString(inflate(out.toByteArray())));
+
+ in.close();
+ try {
+ in.available();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public byte[] inflate(byte[] bytes) throws IOException {
+ java.io.InputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes));
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[1024];
+ int count;
+ while ((count = in.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ return out.toByteArray();
+ }
+
+ public void testReadWithBuffer() throws IOException {
+ byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+ byte[] buffer = new byte[8];
+ InputStream in = new DeflaterInputStream(new ByteArrayInputStream(data));
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ assertEquals(1, in.available());
+ int count;
+ while ((count = in.read(buffer, 0, 5)) != -1) {
+ assertTrue(count <= 5);
+ out.write(buffer, 0, count);
+ }
+ assertEquals(0, in.available());
+
+ assertEquals(Arrays.toString(data), Arrays.toString(inflate(out.toByteArray())));
+
+ in.close();
+ try {
+ in.available();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testReadExceptions() throws IOException {
+ byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+ byte[] buffer = new byte[8];
+ InputStream in = new DeflaterInputStream(new ByteArrayInputStream(data));
+ try {
+ in.read(buffer, 0, 10);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ in.read(null, 0, 5);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ in.read(buffer, -1, 5);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ in.close();
+ try {
+ in.read(buffer, 0, 5);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/util/zip/DeflaterTest.java b/luni/src/test/java/libcore/java/util/zip/DeflaterTest.java
index 27f3c6a..30aa7f3 100644
--- a/luni/src/test/java/libcore/java/util/zip/DeflaterTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/DeflaterTest.java
@@ -72,4 +72,14 @@
assertEquals(expectedValue, decompressed[i]);
}
}
+
+ /**
+ * Deflating without calling setInput() is the same as deflating an empty
+ * byte array.
+ */
+ public void testDeflateWithoutSettingInput() throws Exception {
+ deflateInflate(Deflater.FULL_FLUSH);
+ assertTrue(totalDeflated > 0); // the deflated form should be non-empty
+ assertEquals(0, totalInflated);
+ }
}
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/ZipEntryTest.java b/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
index 4d43ba6..b18ebb4 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipEntryTest.java
@@ -21,13 +21,17 @@
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;
+import java.util.jar.JarEntry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipEntryTest extends junit.framework.TestCase {
- // http://code.google.com/p/android/issues/detail?id=4690
+
+ /**
+ * http://code.google.com/p/android/issues/detail?id=4690
+ */
public void test_utf8FileNames() throws Exception {
// Create a zip file containing non-ASCII filenames.
File f = File.createTempFile("your", "mum");
@@ -58,4 +62,18 @@
assertEquals(filenames.size(), entryCount);
in.close();
}
+
+ /**
+ * http://b/2099615
+ */
+ public void testClone() {
+ byte[] extra = { 5, 7, 9 };
+ JarEntry jarEntry = new JarEntry("foo");
+ jarEntry.setExtra(extra);
+ assertSame("Expected no defensive copy of extra", extra, jarEntry.getExtra());
+
+ ZipEntry clone = (ZipEntry) jarEntry.clone();
+ assertEquals(JarEntry.class, clone.getClass());
+ assertNotSame(extra, clone.getExtra());
+ }
}
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/crypto/KeyGeneratorTest.java b/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java
new file mode 100644
index 0000000..5d5b08d
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/crypto/KeyGeneratorTest.java
@@ -0,0 +1,153 @@
+/*
+ * 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.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Set;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import junit.framework.TestCase;
+
+public class KeyGeneratorTest extends TestCase {
+
+ private static boolean isUnsupported(KeyGenerator kg) {
+ // Don't bother testing "Sun..." KeyGenerators
+ return (kg.getAlgorithm().startsWith("Sun"));
+ }
+
+ public void test_getInstance() throws Exception {
+ Provider[] providers = Security.getProviders();
+ for (Provider provider : providers) {
+ Set<Provider.Service> services = provider.getServices();
+ for (Provider.Service service : services) {
+ String type = service.getType();
+ if (!type.equals("KeyGenerator")) {
+ continue;
+ }
+ String algorithm = service.getAlgorithm();
+ try {
+ // KeyGenerator.getInstance(String)
+ KeyGenerator kg1 = KeyGenerator.getInstance(algorithm);
+ assertEquals(algorithm, kg1.getAlgorithm());
+ test_KeyGenerator(kg1);
+
+ // KeyGenerator.getInstance(String, Provider)
+ KeyGenerator kg2 = KeyGenerator.getInstance(algorithm, provider);
+ assertEquals(algorithm, kg2.getAlgorithm());
+ assertEquals(provider, kg2.getProvider());
+ test_KeyGenerator(kg2);
+
+ // KeyGenerator.getInstance(String, String)
+ KeyGenerator kg3 = KeyGenerator.getInstance(algorithm, provider.getName());
+ assertEquals(algorithm, kg3.getAlgorithm());
+ assertEquals(provider, kg3.getProvider());
+ test_KeyGenerator(kg3);
+ } catch (Exception e) {
+ throw new Exception("Problem testing KeyPairGenerator." + algorithm, e);
+ }
+ }
+ }
+ }
+
+ private static final Map<String, List<Integer>> KEY_SIZES
+ = new HashMap<String, List<Integer>>();
+ private static void putKeySize(String algorithm, int keySize) {
+ algorithm = algorithm.toUpperCase();
+ List<Integer> keySizes = KEY_SIZES.get(algorithm);
+ if (keySizes == null) {
+ keySizes = new ArrayList<Integer>();
+ KEY_SIZES.put(algorithm, keySizes);
+ }
+ keySizes.add(keySize);
+ }
+ private static List<Integer> getKeySizes(String algorithm) throws Exception {
+ algorithm = algorithm.toUpperCase();
+ List<Integer> keySizes = KEY_SIZES.get(algorithm);
+ if (keySizes == null) {
+ throw new Exception("Unknown key sizes for KeyGenerator." + algorithm);
+ }
+ return keySizes;
+ }
+ static {
+ putKeySize("AES", 128);
+ putKeySize("AES", 192);
+ putKeySize("AES", 256);
+ putKeySize("ARCFOUR", 40);
+ putKeySize("ARCFOUR", 41);
+ putKeySize("ARCFOUR", 1024);
+ putKeySize("Blowfish", 32);
+ putKeySize("Blowfish", 40);
+ putKeySize("Blowfish", 448);
+ putKeySize("DES", 56);
+ putKeySize("DESede", 112);
+ putKeySize("DESede", 168);
+ putKeySize("RC2", 40);
+ putKeySize("RC2", 41);
+ putKeySize("RC2", 1024);
+ putKeySize("RC4", 40);
+ putKeySize("RC4", 41);
+ putKeySize("RC4", 1024);
+ putKeySize("HmacMD5", 1);
+ putKeySize("HmacMD5", 1025);
+ putKeySize("HmacSHA1", 1);
+ putKeySize("HmacSHA1", 1025);
+ putKeySize("HmacSHA256", 40);
+ putKeySize("HmacSHA256", 1025);
+ putKeySize("HmacSHA384", 40);
+ putKeySize("HmacSHA384", 1025);
+ putKeySize("HmacSHA512", 40);
+ putKeySize("HmacSHA512", 1025);
+ }
+
+ private void test_KeyGenerator(KeyGenerator kg) throws Exception {
+ if (isUnsupported(kg)) {
+ return;
+ }
+
+ kg.init((SecureRandom) null);
+ test_SecretKey(kg, kg.generateKey());
+
+ kg.init(new SecureRandom());
+ test_SecretKey(kg, kg.generateKey());
+
+ String algorithm = kg.getAlgorithm();
+ List<Integer> keySizes = getKeySizes(algorithm);
+ for (int keySize : keySizes) {
+ kg.init(keySize);
+ test_SecretKey(kg, kg.generateKey());
+
+ kg.init(keySize, (SecureRandom) null);
+ test_SecretKey(kg, kg.generateKey());
+
+ kg.init(keySize, new SecureRandom());
+ test_SecretKey(kg, kg.generateKey());
+ }
+ }
+
+ private void test_SecretKey(KeyGenerator kg, SecretKey sk) throws Exception {
+ assertNotNull(sk);
+ assertEquals(kg.getAlgorithm().toUpperCase(), sk.getAlgorithm().toUpperCase());
+ assertNotNull(sk.getEncoded());
+ assertNotNull(sk.getFormat());
+ }
+}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
index 06ba01c..3efdcc9 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
@@ -17,20 +17,24 @@
package libcore.javax.net.ssl;
import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore.Builder;
+import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Set;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.KeyStoreBuilderParameters;
+import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import junit.framework.TestCase;
+import libcore.java.security.StandardNames;
+import libcore.java.security.TestKeyStore;
public class KeyManagerFactoryTest extends TestCase {
@@ -48,10 +52,13 @@
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
assertEquals(StandardNames.KEY_MANAGER_FACTORY_DEFAULT, algorithm);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
- test_KeyManagerFactory(kmf);
+ test_KeyManagerFactory(kmf, false);
}
- private void test_KeyManagerFactory (KeyManagerFactory kmf) throws Exception {
+ private static class UseslessManagerFactoryParameters implements ManagerFactoryParameters {}
+
+ private void test_KeyManagerFactory(KeyManagerFactory kmf,
+ boolean supportsManagerFactoryParameters) throws Exception {
assertNotNull(kmf);
assertNotNull(kmf.getAlgorithm());
assertNotNull(kmf.getProvider());
@@ -59,30 +66,56 @@
// before init
try {
kmf.getKeyManagers();
+ fail();
} catch (IllegalStateException expected) {
}
- // init with ManagerFactoryParameters
+ // init with null ManagerFactoryParameters
try {
kmf.init(null);
+ fail();
} catch (InvalidAlgorithmParameterException expected) {
}
+ // init with useless ManagerFactoryParameters
+ try {
+ kmf.init(new UseslessManagerFactoryParameters());
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
+ }
+
+ // init with KeyStoreBuilderParameters ManagerFactoryParameters
+ PasswordProtection pp = new PasswordProtection(TEST_KEY_STORE.storePassword);
+ Builder builder = Builder.newInstance(TEST_KEY_STORE.keyStore, pp);
+ KeyStoreBuilderParameters ksbp = new KeyStoreBuilderParameters(builder);
+ if (supportsManagerFactoryParameters) {
+ kmf.init(ksbp);
+ test_KeyManagerFactory_getKeyManagers(kmf);
+ } else {
+ try {
+ kmf.init(ksbp);
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
+ }
+ }
+
+ // init with null for default behavior
kmf.init(null, null);
test_KeyManagerFactory_getKeyManagers(kmf);
+ // init with specific key store and password
kmf.init(TEST_KEY_STORE.keyStore, TEST_KEY_STORE.storePassword);
test_KeyManagerFactory_getKeyManagers(kmf);
}
- private void test_KeyManagerFactory_getKeyManagers (KeyManagerFactory kmf) {
+ private void test_KeyManagerFactory_getKeyManagers(KeyManagerFactory kmf) {
KeyManager[] keyManagers = kmf.getKeyManagers();
assertNotNull(keyManagers);
assertTrue(keyManagers.length > 0);
for (KeyManager keyManager : keyManagers) {
assertNotNull(keyManager);
if (keyManager instanceof X509KeyManager) {
- test_X509KeyManager((X509KeyManager)keyManager);
+ test_X509KeyManager((X509KeyManager) keyManager);
}
}
}
@@ -106,7 +139,7 @@
}
if (km instanceof X509ExtendedKeyManager) {
- test_X509ExtendedKeyManager((X509ExtendedKeyManager)km);
+ test_X509ExtendedKeyManager((X509ExtendedKeyManager) km);
}
}
@@ -136,10 +169,7 @@
assertEquals(keyType, privateKey.getAlgorithm());
}
- PrivateKeyEntry privateKeyEntry
- = TestKeyStore.privateKey(TEST_KEY_STORE.keyStore,
- TEST_KEY_STORE.storePassword,
- keyType);
+ PrivateKeyEntry privateKeyEntry = TEST_KEY_STORE.getPrivateKey(keyType);
assertEquals(Arrays.asList(privateKeyEntry.getCertificateChain()),
Arrays.asList(certificateChain));
assertEquals(privateKeyEntry.getPrivateKey(), privateKey);
@@ -155,11 +185,11 @@
continue;
}
String algorithm = service.getAlgorithm();
-
+ boolean supportsManagerFactoryParameters = algorithm.equals("NewSunX509");
{
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
assertEquals(algorithm, kmf.getAlgorithm());
- test_KeyManagerFactory(kmf);
+ test_KeyManagerFactory(kmf, supportsManagerFactoryParameters);
}
{
@@ -167,7 +197,7 @@
provider);
assertEquals(algorithm, kmf.getAlgorithm());
assertEquals(provider, kmf.getProvider());
- test_KeyManagerFactory(kmf);
+ test_KeyManagerFactory(kmf, supportsManagerFactoryParameters);
}
{
@@ -175,7 +205,7 @@
provider.getName());
assertEquals(algorithm, kmf.getAlgorithm());
assertEquals(provider, kmf.getProvider());
- test_KeyManagerFactory(kmf);
+ test_KeyManagerFactory(kmf, supportsManagerFactoryParameters);
}
}
}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java b/luni/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java
new file mode 100644
index 0000000..1e17a79
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/net/ssl/KeyStoreBuilderParametersTest.java
@@ -0,0 +1,84 @@
+/*
+ * 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.net.ssl;
+
+import java.security.KeyStore.Builder;
+import java.security.KeyStore.PasswordProtection;
+import javax.net.ssl.KeyStoreBuilderParameters;
+import java.util.Arrays;
+import java.util.List;
+import junit.framework.TestCase;
+import libcore.java.security.TestKeyStore;
+
+public class KeyStoreBuilderParametersTest extends TestCase {
+ public void test_init_Builder_null() {
+ // RI document claims they throw NullPointerException but they do not
+ test_init_Builder(null);
+ }
+
+ public void test_init_Builder() {
+ TestKeyStore testKeyStore = TestKeyStore.getClient();
+ Builder builder = Builder.newInstance(testKeyStore.keyStore,
+ new PasswordProtection(testKeyStore.storePassword));
+ test_init_Builder(builder);
+ }
+
+ private void test_init_Builder(Builder builder) {
+
+ KeyStoreBuilderParameters ksbp = new KeyStoreBuilderParameters(builder);
+ assertNotNull(ksbp);
+ assertNotNull(ksbp.getParameters());
+ assertEquals(1, ksbp.getParameters().size());
+ assertSame(builder, ksbp.getParameters().get(0));
+ }
+
+ public void test_init_List_null() {
+ try {
+ new KeyStoreBuilderParameters((List) null);
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_init_List() {
+ TestKeyStore testKeyStore1 = TestKeyStore.getClient();
+ TestKeyStore testKeyStore2 = TestKeyStore.getServer();
+ Builder builder1 = Builder.newInstance(testKeyStore1.keyStore,
+ new PasswordProtection(testKeyStore1.storePassword));
+ Builder builder2 = Builder.newInstance(testKeyStore2.keyStore,
+ new PasswordProtection(testKeyStore2.storePassword));
+
+ List list = Arrays.asList(builder1, builder2);
+ KeyStoreBuilderParameters ksbp = new KeyStoreBuilderParameters(list);
+ assertNotNull(ksbp);
+ assertNotNull(ksbp.getParameters());
+ assertNotSame(list, ksbp.getParameters());
+ assertEquals(2, ksbp.getParameters().size());
+ assertSame(builder1, ksbp.getParameters().get(0));
+ assertSame(builder2, ksbp.getParameters().get(1));
+
+ // confirm result is not modifiable
+ try {
+ ksbp.getParameters().set(0, builder2);
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ // confirm result is a copy of original
+ list.set(0, builder2);
+ assertSame(builder1, ksbp.getParameters().get(0));
+ }
+}
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..ed6beef 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
@@ -16,7 +16,6 @@
package libcore.javax.net.ssl;
-import dalvik.annotation.KnownFailure;
import libcore.java.security.StandardNames;
import libcore.java.security.TestKeyStore;
import java.util.Arrays;
@@ -64,11 +63,11 @@
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'")
public void test_SSLEngine_getSupportedCipherSuites_connect() throws Exception {
- // note the rare usage of DSA keys here in addition to RSA
+ // note the rare usage of non-RSA keys
TestKeyStore testKeyStore = TestKeyStore.create(new String[] { "RSA", "DSA" },
null,
null,
@@ -79,23 +78,33 @@
TestSSLContext c = TestSSLContext.create(testKeyStore, testKeyStore);
String[] cipherSuites = c.clientContext.createSSLEngine().getSupportedCipherSuites();
for (String cipherSuite : cipherSuites) {
- /*
- * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
- * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#KRBRequire
- */
- if (cipherSuite.startsWith("TLS_KRB5_")) {
- continue;
- }
- // System.out.println("Trying to connect cipher suite " + cipherSuite);
- final String[] cipherSuiteArray = new String[] { cipherSuite };
- assertConnected(TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
- @Override
- void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
- client.setEnabledCipherSuites(cipherSuiteArray);
- server.setEnabledCipherSuites(cipherSuiteArray);
+ try {
+ /*
+ * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
+ * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#KRBRequire
+ */
+ if (cipherSuite.startsWith("TLS_KRB5_")) {
+ continue;
}
- }));
+ /*
+ * Elliptic Curve cipher suites are not supported
+ */
+ if (cipherSuite.startsWith("TLS_EC")) {
+ continue;
+ }
+ final String[] cipherSuiteArray = new String[] { cipherSuite };
+ assertConnected(TestSSLEnginePair.create(c, new TestSSLEnginePair.Hooks() {
+ @Override
+ void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
+ client.setEnabledCipherSuites(cipherSuiteArray);
+ server.setEnabledCipherSuites(cipherSuiteArray);
+ }
+ }));
+ } catch (Exception e) {
+ throw new Exception("Problem trying to connect cipher suite " + cipherSuite, e);
+ }
}
+ c.close();
}
public void test_SSLEngine_getEnabledCipherSuites() throws Exception {
@@ -104,6 +113,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 +139,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 +148,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 +157,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 +182,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 +191,7 @@
SSLSession session = e.getSession();
assertNotNull(session);
assertFalse(session.isValid());
+ c.close();
}
public void test_SSLEngine_beginHandshake() throws Exception {
@@ -189,9 +204,10 @@
}
assertConnected(TestSSLEnginePair.create(null));
+
+ c.close();
}
- @KnownFailure("NO SERVER CERTIFICATE FOUND")
public void test_SSLEngine_beginHandshake_noKeyStore() throws Exception {
TestSSLContext c = TestSSLContext.create(null, null, null, null, null, null, null, null,
SSLContext.getDefault(), SSLContext.getDefault());
@@ -202,21 +218,23 @@
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")
public void test_SSLEngine_setUseClientMode() throws Exception {
// client is client, server is server
assertConnected(test_SSLEngine_setUseClientMode(true, false));
@@ -266,7 +284,6 @@
});
}
- @KnownFailure("init - invalid private key")
public void test_SSLEngine_clientAuth() throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLEngine e = c.clientContext.createSSLEngine();
@@ -305,15 +322,17 @@
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")
public void test_SSLEngine_setEnableSessionCreation_server() throws Exception {
TestSSLEnginePair p = TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() {
@Override
@@ -324,7 +343,6 @@
assertNotConnected(p);
}
- @KnownFailure("AlertException instead of SSLException")
public void test_SSLEngine_setEnableSessionCreation_client() throws Exception {
try {
TestSSLEnginePair.create(new TestSSLEnginePair.Hooks() {
@@ -357,6 +375,8 @@
assertEquals(p.getWantClientAuth(), e.getWantClientAuth());
assertEquals(p.getNeedClientAuth(), e.getNeedClientAuth());
+
+ c.close();
}
public void test_SSLEngine_setSSLParameters() throws Exception {
@@ -409,6 +429,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..4109222 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
@@ -50,7 +50,7 @@
}
public void test_SSLSocket_getSupportedCipherSuites_connect() throws Exception {
- // note the rare usage of DSA keys here in addition to RSA
+ // note the rare usage of non-RSA keys
TestKeyStore testKeyStore = TestKeyStore.create(new String[] { "RSA", "DSA" },
null,
null,
@@ -92,35 +92,46 @@
clientProvider, serverProvider);
String[] cipherSuites = c.clientContext.getSocketFactory().getSupportedCipherSuites();
for (String cipherSuite : cipherSuites) {
- /*
- * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
- * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#KRBRequire
- */
- if (cipherSuite.startsWith("TLS_KRB5_")) {
- continue;
- }
- // System.out.println("Trying to connect cipher suite " + cipherSuite
- // + " client=" + clientProvider
- // + " server=" + serverProvider);
- String[] cipherSuiteArray = new String[] { cipherSuite };
- SSLSocket[] pair = TestSSLSocketPair.connect(c, cipherSuiteArray, cipherSuiteArray);
+ try {
+ /*
+ * Kerberos cipher suites require external setup. See "Kerberos Requirements" in
+ * https://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#KRBRequire
+ */
+ if (cipherSuite.startsWith("TLS_KRB5_")) {
+ continue;
+ }
+ /*
+ * Elliptic Curve cipher suites are not supported
+ */
+ if (cipherSuite.startsWith("TLS_EC")) {
+ continue;
+ }
+ String[] cipherSuiteArray = new String[] { cipherSuite };
+ SSLSocket[] pair = TestSSLSocketPair.connect(c, cipherSuiteArray, cipherSuiteArray);
- SSLSocket server = pair[0];
- SSLSocket client = pair[1];
- server.getOutputStream().write(serverToClient);
- client.getOutputStream().write(clientToServer);
- // arrays are too big to make sure we get back only what we expect
- byte[] clientFromServer = new byte[serverToClient.length+1];
- byte[] serverFromClient = new byte[clientToServer.length+1];
- int readFromServer = client.getInputStream().read(clientFromServer);
- int readFromClient = server.getInputStream().read(serverFromClient);
- assertEquals(serverToClient.length, readFromServer);
- assertEquals(clientToServer.length, readFromClient);
- assertEquals(clientToServerString, new String(serverFromClient, 0, readFromClient));
- assertEquals(serverToClientString, new String(clientFromServer, 0, readFromServer));
- server.close();
- client.close();
+ SSLSocket server = pair[0];
+ SSLSocket client = pair[1];
+ server.getOutputStream().write(serverToClient);
+ client.getOutputStream().write(clientToServer);
+ // arrays are too big to make sure we get back only what we expect
+ byte[] clientFromServer = new byte[serverToClient.length+1];
+ byte[] serverFromClient = new byte[clientToServer.length+1];
+ int readFromServer = client.getInputStream().read(clientFromServer);
+ int readFromClient = server.getInputStream().read(serverFromClient);
+ assertEquals(serverToClient.length, readFromServer);
+ assertEquals(clientToServer.length, readFromClient);
+ assertEquals(clientToServerString, new String(serverFromClient, 0, readFromClient));
+ assertEquals(serverToClientString, new String(clientFromServer, 0, readFromServer));
+ client.close();
+ server.close();
+ } catch (Exception e) {
+ throw new Exception("Problem trying to connect cipher suite " + cipherSuite
+ + " client=" + clientProvider
+ + " server=" + serverProvider,
+ e);
+ }
}
+ c.close();
}
public void test_SSLSocket_getEnabledCipherSuites() throws Exception {
@@ -246,6 +257,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 +268,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 +297,9 @@
thread.start();
client.startHandshake();
thread.join();
+ client.close();
+ server.close();
+ c.close();
}
public void test_SSLSocket_HandshakeCompletedListener() throws Exception {
@@ -384,6 +403,9 @@
handshakeCompletedListenerCalled.wait();
}
}
+ client.close();
+ server.close();
+ c.close();
}
public void test_SSLSocket_HandshakeCompletedListener_RuntimeException() throws Exception {
@@ -410,6 +432,9 @@
});
client.startHandshake();
thread.join();
+ client.close();
+ server.close();
+ c.close();
}
public void test_SSLSocket_getUseClientMode() throws Exception {
@@ -419,6 +444,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 +527,9 @@
if (socketTimeoutException[0] != null) {
throw socketTimeoutException[0];
}
+ client.close();
+ server.close();
+ c.close();
}
public void test_SSLSocket_clientAuth() throws Exception {
@@ -544,6 +575,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 +587,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 +620,9 @@
} catch (SSLException expected) {
}
thread.join();
+ client.close();
+ server.close();
+ c.close();
}
public void test_SSLSocket_setEnableSessionCreation_client() throws Exception {
@@ -613,6 +653,9 @@
} catch (SSLException expected) {
}
thread.join();
+ client.close();
+ server.close();
+ c.close();
}
public void test_SSLSocket_getSSLParameters() throws Exception {
@@ -770,6 +813,8 @@
fail();
} catch (IllegalArgumentException expected) {
}
+
+ pair.close();
}
public void test_SSLSocket_setSoTimeout_basic() throws Exception {
@@ -794,6 +839,10 @@
}
public void test_SSLSocket_setSoTimeout_wrapper() throws Exception {
+ if (StandardNames.IS_RI) {
+ // RI cannot handle this case
+ return;
+ }
ServerSocket listening = new ServerSocket(0);
// setSoTimeout applies to read, not connect, so connect first
@@ -885,6 +934,7 @@
assertNotNull(test.client.getSession());
assertTrue(test.server.getSession().isValid());
assertTrue(test.client.getSession().isValid());
+ test.close();
}
/**
@@ -901,6 +951,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/libcore/javax/net/ssl/TrustManagerFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
new file mode 100644
index 0000000..df1d179
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
@@ -0,0 +1,236 @@
+/*
+ * 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.net.ssl;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore.PrivateKeyEntry;
+import java.security.KeyStore;
+import java.security.Provider;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.PKIXBuilderParameters;
+import java.security.cert.PKIXParameters;
+import java.security.cert.X509CertSelector;
+import java.security.cert.X509Certificate;
+import java.util.Set;
+import javax.net.ssl.CertPathTrustManagerParameters;
+import javax.net.ssl.ManagerFactoryParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+import junit.framework.TestCase;
+import libcore.java.security.StandardNames;
+import libcore.java.security.TestKeyStore;
+
+public class TrustManagerFactoryTest extends TestCase {
+
+ private static final String [] KEY_TYPES = new String[] { "RSA", "DSA" };
+ // note the rare usage of DSA keys here in addition to RSA
+ private static final TestKeyStore TEST_KEY_STORE
+ = TestKeyStore.create(KEY_TYPES,
+ null,
+ null,
+ "rsa-dsa",
+ TestKeyStore.localhost(),
+ true,
+ null);
+
+ public void test_TrustManagerFactory_getDefaultAlgorithm() throws Exception {
+ String algorithm = TrustManagerFactory.getDefaultAlgorithm();
+ assertEquals(StandardNames.TRUST_MANAGER_FACTORY_DEFAULT, algorithm);
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
+ test_TrustManagerFactory(tmf, StandardNames.IS_RI);
+ }
+
+ private static class UseslessManagerFactoryParameters implements ManagerFactoryParameters {}
+
+ private void test_TrustManagerFactory(TrustManagerFactory tmf,
+ boolean supportsManagerFactoryParameters)
+ throws Exception {
+ assertNotNull(tmf);
+ assertNotNull(tmf.getAlgorithm());
+ assertNotNull(tmf.getProvider());
+
+ // before init
+ try {
+ tmf.getTrustManagers();
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+
+ // init with null ManagerFactoryParameters
+ try {
+ tmf.init((ManagerFactoryParameters) null);
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
+ }
+
+ // init with useless ManagerFactoryParameters
+ try {
+ tmf.init(new UseslessManagerFactoryParameters());
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
+ }
+
+ // init with PKIXParameters ManagerFactoryParameters
+ try {
+ PKIXParameters pp = new PKIXParameters(TEST_KEY_STORE.keyStore);
+ CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pp);
+ tmf.init(cptmp);
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
+ }
+
+ // init with PKIXBuilderParameters ManagerFactoryParameters
+ X509CertSelector xcs = new X509CertSelector();
+ PKIXBuilderParameters pbp = new PKIXBuilderParameters(TEST_KEY_STORE.keyStore, xcs);
+ CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pbp);
+ if (supportsManagerFactoryParameters) {
+ tmf.init(cptmp);
+ test_TrustManagerFactory_getTrustManagers(tmf);
+ } else {
+ try {
+ tmf.init(cptmp);
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
+ }
+ }
+
+ // init with null for default KeyStore
+ tmf.init((KeyStore) null);
+ test_TrustManagerFactory_getTrustManagers(tmf);
+
+ // init with specific key store
+ tmf.init(TEST_KEY_STORE.keyStore);
+ test_TrustManagerFactory_getTrustManagers(tmf);
+ }
+
+ private void test_TrustManagerFactory_getTrustManagers(TrustManagerFactory tmf)
+ throws Exception {
+ TrustManager[] trustManagers = tmf.getTrustManagers();
+ assertNotNull(trustManagers);
+ assertTrue(trustManagers.length > 0);
+ for (TrustManager trustManager : trustManagers) {
+ assertNotNull(trustManager);
+ if (trustManager instanceof X509TrustManager) {
+ test_X509TrustManager((X509TrustManager) trustManager);
+ }
+ }
+ }
+
+ private void test_X509TrustManager(X509TrustManager tm) throws Exception {
+ for (String keyType : KEY_TYPES) {
+ X509Certificate[] issuers = tm.getAcceptedIssuers();
+ assertNotNull(issuers);
+ assertTrue(issuers.length > 1);
+ boolean defaultTrustmanager = (issuers.length > KEY_TYPES.length);
+
+ PrivateKeyEntry pke = TEST_KEY_STORE.getPrivateKey(keyType);
+ X509Certificate[] chain = (X509Certificate[]) pke.getCertificateChain();
+ if (defaultTrustmanager) {
+ try {
+ tm.checkClientTrusted(chain, keyType);
+ fail();
+ } catch (CertificateException expected) {
+ }
+ try {
+ tm.checkServerTrusted(chain, keyType);
+ fail();
+ } catch (CertificateException expected) {
+ }
+ } else {
+ tm.checkClientTrusted(chain, keyType);
+ tm.checkServerTrusted(chain, keyType);
+ }
+
+ }
+ }
+
+ public void test_TrustManagerFactory_getInstance() throws Exception {
+ Provider[] providers = Security.getProviders();
+ for (Provider provider : providers) {
+ Set<Provider.Service> services = provider.getServices();
+ for (Provider.Service service : services) {
+ String type = service.getType();
+ if (!type.equals("TrustManagerFactory")) {
+ continue;
+ }
+ String algorithm = service.getAlgorithm();
+ boolean supportsManagerFactoryParameters = algorithm.equals("PKIX");
+ {
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
+ assertEquals(algorithm, tmf.getAlgorithm());
+ test_TrustManagerFactory(tmf, supportsManagerFactoryParameters);
+ }
+
+ {
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm,
+ provider);
+ assertEquals(algorithm, tmf.getAlgorithm());
+ assertEquals(provider, tmf.getProvider());
+ test_TrustManagerFactory(tmf, supportsManagerFactoryParameters);
+ }
+
+ {
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm,
+ provider.getName());
+ assertEquals(algorithm, tmf.getAlgorithm());
+ assertEquals(provider, tmf.getProvider());
+ test_TrustManagerFactory(tmf, supportsManagerFactoryParameters);
+ }
+ }
+ }
+ }
+
+ public void test_TrustManagerFactory_intermediate() throws Exception {
+ // chain should be server/intermediate/root
+ PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA");
+ X509Certificate[] chain = (X509Certificate[])pke.getCertificateChain();
+ assertEquals(3, chain.length);
+
+ // keyStore should contain only the intermediate CA so we can
+ // test proper validation even if there are extra certs after
+ // the trusted one (in this case the original root is "extra")
+ KeyStore keyStore = TestKeyStore.createKeyStore();
+ keyStore.setCertificateEntry("alias", chain[1]);
+
+ Provider[] providers = Security.getProviders();
+ for (Provider provider : providers) {
+ Set<Provider.Service> services = provider.getServices();
+ for (Provider.Service service : services) {
+ String type = service.getType();
+ if (!type.equals("TrustManagerFactory")) {
+ continue;
+ }
+ String algorithm = service.getAlgorithm();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
+ tmf.init(keyStore);
+ TrustManager[] trustManagers = tmf.getTrustManagers();
+ for (TrustManager trustManager : trustManagers) {
+ if (!(trustManager instanceof X509TrustManager)) {
+ continue;
+ }
+ X509TrustManager tm = (X509TrustManager) trustManager;
+ tm.checkClientTrusted(chain, "RSA");
+ tm.checkServerTrusted(chain, "RSA");
+ }
+ }
+ }
+ }
+
+}
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/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/Adler32Test.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java
deleted file mode 100644
index f68c782..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java
+++ /dev/null
@@ -1,169 +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 java.util.zip.Adler32;
-
-public class Adler32Test extends junit.framework.TestCase {
-
- /**
- * @tests java.util.zip.Adler32#Adler32()
- */
- public void test_Constructor() {
- // test method of java.util.zip.Adler32()
- Adler32 adl = new Adler32();
- assertEquals("Constructor of adl32 failed", 1, adl.getValue());
- }
-
- /**
- * @tests java.util.zip.Adler32#getValue()
- */
- public void test_getValue() {
- // test methods of java.util.zip.getValue()
- Adler32 adl = new Adler32();
- assertEquals("GetValue should return a zero as a result of construction an object of Adler32",
- 1, adl.getValue());
-
- adl.reset();
- adl.update(1);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 131074
- assertEquals("update(int) failed to update the checksum to the correct value ",
- 131074, adl.getValue());
- adl.reset();
- assertEquals("reset failed to reset the checksum value to zero", 1, adl
- .getValue());
-
- adl.reset();
- adl.update(Integer.MIN_VALUE);
- // System.out.print("value of adl " + adl.getValue());
- // The value of the adl should be 65537
- assertEquals("update(min) failed to update the checksum to the correct value ",
- 65537L, adl.getValue());
- }
-
- /**
- * @tests java.util.zip.Adler32#reset()
- */
- public void test_reset() {
- // test methods of java.util.zip.reset()
- Adler32 adl = new Adler32();
- adl.update(1);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 131074
- assertEquals("update(int) failed to update the checksum to the correct value ",
- 131074, adl.getValue());
- adl.reset();
- assertEquals("reset failed to reset the checksum value to zero", 1, adl
- .getValue());
- }
-
- /**
- * @tests java.util.zip.Adler32#update(int)
- */
- public void test_updateI() {
- // test methods of java.util.zip.update(int)
- Adler32 adl = new Adler32();
- adl.update(1);
- // The value of the adl should be 131074
- assertEquals("update(int) failed to update the checksum to the correct value ",
- 131074, adl.getValue());
-
- adl.reset();
- adl.update(Integer.MAX_VALUE);
- // System.out.print("value of adl " + adl.getValue());
- // The value of the adl should be 16777472
- assertEquals("update(max) failed to update the checksum to the correct value ",
- 16777472L, adl.getValue());
-
- adl.reset();
- adl.update(Integer.MIN_VALUE);
- // System.out.print("value of adl " + adl.getValue());
- // The value of the adl should be 65537
- assertEquals("update(min) failed to update the checksum to the correct value ",
- 65537L, adl.getValue());
-
- }
-
- /**
- * @tests java.util.zip.Adler32#update(byte[])
- */
- public void test_update$B() {
- // test method of java.util.zip.update(byte[])
- byte byteArray[] = { 1, 2 };
- Adler32 adl = new Adler32();
- adl.update(byteArray);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 393220
- assertEquals("update(byte[]) failed to update the checksum to the correct value ",
- 393220, adl.getValue());
-
- adl.reset();
- byte byteEmpty[] = new byte[10000];
- adl.update(byteEmpty);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 655360001
- assertEquals("update(byte[]) failed to update the checksum to the correct value ",
- 655360001L, adl.getValue());
-
- }
-
- /**
- * @tests java.util.zip.Adler32#update(byte[], int, int)
- */
- public void test_update$BII() {
- // test methods of java.util.zip.update(byte[],int,int)
- byte[] byteArray = { 1, 2, 3 };
- Adler32 adl = new Adler32();
- int off = 2;// accessing the 2nd element of byteArray
- int len = 1;
- int lenError = 3;
- int offError = 4;
- adl.update(byteArray, off, len);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 262148
- assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ",
- 262148, adl.getValue());
- int r = 0;
-
- try {
- adl.update(byteArray, off, lenError);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off",
- 1, r);
-
- try {
- adl.update(byteArray, offError, len);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 2;
- }
- assertEquals("update(byte[],int,int) failed b/c offError>byte[].length",
- 2, r);
-
- }
-
- @Override
- protected void setUp() {
- }
-
- @Override
- protected void tearDown() {
- }
-
-}
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 cc0c46d..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java
+++ /dev/null
@@ -1,50 +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(Adler32Test.class);
- suite.addTestSuite(CheckedInputStreamTest.class);
- suite.addTestSuite(CheckedOutputStreamTest.class);
- suite.addTestSuite(CRC32Test.class);
- suite.addTestSuite(DataFormatExceptionTest.class);
- suite.addTestSuite(DeflaterInputStreamTest.class);
- suite.addTestSuite(DeflaterOutputStreamTest.class);
- suite.addTestSuite(DeflaterTest.class);
- suite.addTestSuite(GZIPInputStreamTest.class);
- suite.addTestSuite(GZIPOutputStreamTest.class);
- suite.addTestSuite(InflaterInputStreamTest.class);
- suite.addTestSuite(InflaterOutputStreamTest.class);
- suite.addTestSuite(InflaterTest.class);
- suite.addTestSuite(ZipEntryTest.class);
- suite.addTestSuite(ZipExceptionTest.class);
- suite.addTestSuite(ZipFileTest.class);
- suite.addTestSuite(ZipInputStreamTest.class);
- suite.addTestSuite(ZipOutputStreamTest.class);
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java
deleted file mode 100644
index ea076d7..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java
+++ /dev/null
@@ -1,186 +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 java.util.zip.CRC32;
-
-public class CRC32Test extends junit.framework.TestCase {
-
- /**
- * @tests java.util.zip.CRC32#CRC32()
- */
- public void test_Constructor() {
- // test methods of java.util.zip.CRC32()
- CRC32 crc = new CRC32();
- assertEquals("Constructor of CRC32 failed", 0, crc.getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#getValue()
- */
- public void test_getValue() {
- // test methods of java.util.zip.crc32.getValue()
- CRC32 crc = new CRC32();
- assertEquals("getValue() should return a zero as a result of constructing a CRC32 instance",
- 0, crc.getValue());
-
- crc.reset();
- crc.update(Integer.MAX_VALUE);
- // System.out.print("value of crc " + crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 4278190080
- assertEquals("update(max) failed to update the checksum to the correct value ",
- 4278190080L, crc.getValue());
-
- crc.reset();
- byte byteEmpty[] = new byte[10000];
- crc.update(byteEmpty);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 1295764014
- assertEquals("update(byte[]) failed to update the checksum to the correct value ",
- 1295764014L, crc.getValue());
-
- crc.reset();
- crc.update(1);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 2768625435
- // assertEquals("update(int) failed to update the checksum to the correct
- // value ",2768625435L, crc.getValue());
- crc.reset();
- assertEquals("reset failed to reset the checksum value to zero", 0, crc
- .getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#reset()
- */
- public void test_reset() {
- // test methods of java.util.zip.crc32.reset()
- CRC32 crc = new CRC32();
- crc.update(1);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 2768625435
- assertEquals("update(int) failed to update the checksum to the correct value ",
- 2768625435L, crc.getValue());
- crc.reset();
- assertEquals("reset failed to reset the checksum value to zero", 0, crc
- .getValue());
-
- }
-
- /**
- * @tests java.util.zip.CRC32#update(int)
- */
- public void test_updateI() {
- // test methods of java.util.zip.crc32.update(int)
- CRC32 crc = new CRC32();
- crc.update(1);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 2768625435
- assertEquals("update(1) failed to update the checksum to the correct value ",
- 2768625435L, crc.getValue());
-
- crc.reset();
- crc.update(Integer.MAX_VALUE);
- // System.out.print("value of crc " + crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 4278190080
- assertEquals("update(max) failed to update the checksum to the correct value ",
- 4278190080L, crc.getValue());
-
- crc.reset();
- crc.update(Integer.MIN_VALUE);
- // System.out.print("value of crc " + crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 3523407757
- assertEquals("update(min) failed to update the checksum to the correct value ",
- 3523407757L, crc.getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#update(byte[])
- */
- public void test_update$B() {
- // test methods of java.util.zip.crc32.update(byte[])
- byte byteArray[] = { 1, 2 };
- CRC32 crc = new CRC32();
- crc.update(byteArray);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 3066839698
- assertEquals("update(byte[]) failed to update the checksum to the correct value ",
- 3066839698L, crc.getValue());
-
- crc.reset();
- byte byteEmpty[] = new byte[10000];
- crc.update(byteEmpty);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 1295764014
- assertEquals("update(byte[]) failed to update the checksum to the correct value ",
- 1295764014L, crc.getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#update(byte[], int, int)
- */
- public void test_update$BII() {
- // test methods of java.util.zip.update(byte[],int,int)
- byte[] byteArray = { 1, 2, 3 };
- CRC32 crc = new CRC32();
- int off = 2;// accessing the 2nd element of byteArray
- int len = 1;
- int lenError = 3;
- int offError = 4;
- crc.update(byteArray, off, len);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 1259060791
- assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ",
- 1259060791L, crc.getValue());
- int r = 0;
- try {
- crc.update(byteArray, off, lenError);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off",
- 1, r);
-
- try {
- crc.update(byteArray, offError, len);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 2;
- }
- assertEquals("update(byte[],int,int) failed b/c offError>byte[].length",
- 2, r);
- }
-
- @Override
- protected void setUp() {
-
- }
-
- @Override
- protected void tearDown() {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java
deleted file mode 100644
index 748c9fa..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java
+++ /dev/null
@@ -1,144 +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 java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.io.IOException;
-import java.util.zip.CRC32;
-import java.util.zip.CheckedInputStream;
-
-import junit.framework.TestCase;
-import tests.support.resource.Support_Resources;
-
-public class CheckedInputStreamTest extends TestCase {
-
- @Override
- protected void tearDown() {
- try {
- File deletedFile = new File("empty.txt");
- deletedFile.delete();
- } catch (SecurityException e) {
- fail("Cannot delete file for security reasons");
- }
-
- }
-
- /**
- * @tests java.util.zip.CheckedInputStream#CheckedInputStream(java.io.InputStream,
- * java.util.zip.Checksum)
- */
- public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Checksum() throws Exception {
- InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
- assertEquals("constructor of checkedInputStream has failed", 0, checkIn.getChecksum()
- .getValue());
- checkInput.close();
- }
-
- /**
- * @tests java.util.zip.CheckedInputStream#getChecksum()
- */
- public void test_getChecksum() throws Exception {
- byte outBuf[] = new byte[100];
- // testing getChecksum for an empty file
- FileOutputStream outEmp = new FileOutputStream("empty.txt");
- outEmp.close();
- InputStream inEmp = new FileInputStream("empty.txt");
- CheckedInputStream checkEmpty = new CheckedInputStream(inEmp, new CRC32());
- while (checkEmpty.read() >= 0) {
- }
- assertEquals("the checkSum value of an empty file is not zero", 0, checkEmpty
- .getChecksum().getValue());
- inEmp.close();
-
- // testing getChecksum for the file checkInput
- InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
- while (checkIn.read() >= 0) {
- }
- // ran JDK and found that the checkSum value of this is 2036203193
- // System.out.print(" " + checkIn.getChecksum().getValue());
- assertEquals("the checksum value is incorrect", 2036203193, checkIn.getChecksum()
- .getValue());
- checkInput.close();
- // testing getChecksum for file checkInput
- checkInput = Support_Resources.getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn2 = new CheckedInputStream(checkInput, new CRC32());
- checkIn2.read(outBuf, 0, 10);
- // ran JDK and found that the checkSum value of this is 2235765342
- // System.out.print(" " + checkIn2.getChecksum().getValue());
- assertEquals("the checksum value is incorrect", 2235765342L, checkIn2.getChecksum()
- .getValue());
- checkInput.close();
- }
-
- /**
- * @tests java.util.zip.CheckedInputStream#skip(long)
- */
- public void test_skipJ() throws Exception {
- // testing that the return by skip is valid
- InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
- long skipValue = 5;
- assertEquals("the value returned by skip(n) is not the same as its parameter",
- skipValue, checkIn.skip(skipValue));
- checkIn.skip(skipValue);
- // ran JDK and found the checkSum value is 2235765342
- // System.out.print(checkIn.getChecksum().getValue());
- assertEquals("checkSum value is not correct", 2235765342L, checkIn.getChecksum()
- .getValue());
- checkInput.close();
- }
-
- public void test_read() throws Exception {
- // testing that the return by skip is valid
- InputStream checkInput = Support_Resources
- .getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput,
- new CRC32());
- checkIn.read();
- checkIn.close();
- try {
- checkIn.read();
- fail("IOException expected.");
- } catch (IOException ee) {
- // expected
- }
- checkInput.close();
- }
-
- public void test_read$byteII() throws Exception {
- // testing that the return by skip is valid
- InputStream checkInput = Support_Resources
- .getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput,
- new CRC32());
- byte buff[] = new byte[50];
- checkIn.read(buff, 10, 5);
- checkIn.close();
- try {
- checkIn.read(buff, 10, 5);
- fail("IOException expected.");
- } catch (IOException ee) {
- // expected
- }
- checkInput.close();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java
deleted file mode 100644
index 35ac7eb..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedOutputStreamTest.java
+++ /dev/null
@@ -1,165 +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 java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.zip.Adler32;
-import java.util.zip.CRC32;
-import java.util.zip.CheckedOutputStream;
-
-public class CheckedOutputStreamTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.zip.CheckedOutputStream#CheckedOutputStream(java.io.OutputStream,
- * java.util.zip.Checksum)
- */
- public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Checksum() {
- // test method java.util.zip.checkedOutputStream.constructor
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("chkOut", ".txt"));
- CheckedOutputStream chkOut = new CheckedOutputStream(outFile,
- new CRC32());
- assertEquals("the checkSum value of the constructor is not 0", 0,
- chkOut.getChecksum().getValue());
- outFile.close();
- } catch (IOException e) {
- fail("Unable to find file");
- } catch (SecurityException e) {
- fail("file cannot be opened for writing due to security reasons");
- }
- }
-
- /**
- * @tests java.util.zip.CheckedOutputStream#getChecksum()
- */
- public void test_getChecksum() {
- // test method java.util.zip.checkedOutputStream.getChecksum()
- byte byteArray[] = {1, 2, 3, 'e', 'r', 't', 'g', 3, 6};
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("chkOut", ".txt"));
- CheckedOutputStream chkOut = new CheckedOutputStream(outFile,
- new Adler32());
- chkOut.write(byteArray[4]);
- // ran JDK and found that checkSum value is 7536755
- // System.out.print(chkOut.getChecksum().getValue());
-
- assertEquals("the checkSum value for writeI is incorrect", 7536755,
- chkOut.getChecksum().getValue());
- chkOut.getChecksum().reset();
- chkOut.write(byteArray, 5, 4);
- // ran JDK and found that checkSum value is 51708133
- // System.out.print(" " +chkOut.getChecksum().getValue());
-
- assertEquals("the checkSum value for writeBII is incorrect ",
- 51708133, chkOut.getChecksum().getValue());
- outFile.close();
- } catch (IOException e) {
- fail("Unable to find file");
- } catch (SecurityException e) {
- fail("file cannot be opened for writing due to security reasons");
- }
- }
-
- /**
- * @tests java.util.zip.CheckedOutputStream#write(int)
- */
- public void test_writeI() {
- // test method java.util.zip.checkedOutputStream.writeI()
- CheckedOutputStream chkOut = null;
- byte byteArray[] = {1, 2, 3, 'e', 'r', 't', 'g', 3, 6};
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("chkOut", ".txt"));
- chkOut = new CheckedOutputStream(outFile, new CRC32());
- for (byte element : byteArray) {
- chkOut.write(element);
- }
- assertTrue(
- "the checkSum value is zero, no bytes are written to the output file",
- chkOut.getChecksum().getValue() != 0);
- outFile.close();
- } catch (IOException e) {
- fail("Unable to find file");
- } catch (SecurityException e) {
- fail("File cannot be opened for writing due to security reasons");
- }
- try {
- chkOut.write(0);
- fail("IOException expected");
- } catch (IOException e) {
- // expected.
- }
- }
-
- /**
- * @tests java.util.zip.CheckedOutputStream#write(byte[], int, int)
- */
- public void test_write$BII() {
- // test method java.util.zip.checkOutputStream.writeBII()
- CheckedOutputStream chkOut = null;
- byte byteArray[] = {1, 2, 3, 'e', 'r', 't', 'g', 3, 6};
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("chkOut", ".txt"));
- chkOut = new CheckedOutputStream(outFile, new CRC32());
- chkOut.write(byteArray, 4, 5);
- assertTrue(
- "the checkSum value is zero, no bytes are written to the output file",
- chkOut.getChecksum().getValue() != 0);
- int r = 0;
- try {
- chkOut.write(byteArray, 4, 6);
- } catch (IndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("boundary check is not performed", 1, r);
- outFile.close();
- } catch (IOException e) {
- fail("Unable to find file");
- } catch (SecurityException e) {
- fail("file cannot be opened for writing due to security reasons");
- } catch (IndexOutOfBoundsException e) {
- fail("Index for write is out of bounds");
- }
- try {
- chkOut.write(byteArray, 4, 5);
- fail("IOException expected");
- } catch (IOException e) {
- // expected
- }
- }
-
- @Override
- protected void setUp() {
- }
-
- @Override
- protected void tearDown() {
- try {
- File deletedFile = new File("chkOut.txt");
- deletedFile.delete();
- } catch (SecurityException e) {
- fail("Cannot delete file for security reasons");
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterInputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterInputStreamTest.java
deleted file mode 100644
index 81874c1..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterInputStreamTest.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 java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.zip.Deflater;
-import java.util.zip.DeflaterInputStream;
-
-import junit.framework.TestCase;
-
-public class DeflaterInputStreamTest extends TestCase {
-
- String testStr = "Hi,this is a test";
-
- InputStream is;
-
- /**
- * @tests DeflaterInputStream#available()
- */
- public void testAvailable() throws IOException {
- byte[] buf = new byte[1024];
- DeflaterInputStream dis = new DeflaterInputStream(is);
- assertEquals(1, dis.available());
- assertEquals(120, dis.read());
- assertEquals(1, dis.available());
- assertEquals(22, dis.read(buf, 0, 1024));
- assertEquals(1, dis.available());
- assertEquals(-1, dis.read());
- assertEquals(0, dis.available());
- dis.close();
- try {
- dis.available();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests DeflaterInputStream#close()
- */
- public void testClose() throws IOException {
- byte[] buf = new byte[1024];
- DeflaterInputStream dis = new DeflaterInputStream(is);
- assertEquals(1, dis.available());
- dis.close();
- try {
- dis.available();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(buf, 0, 1024);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- // can close after close
- dis.close();
- }
-
- /**
- * @tests DeflaterInputStream#mark()
- */
- public void testMark() throws IOException {
- // mark do nothing
- DeflaterInputStream dis = new DeflaterInputStream(is);
- dis.mark(-1);
- dis.mark(0);
- dis.mark(1);
- dis.close();
- dis.mark(1);
- }
-
- /**
- * @tests DeflaterInputStream#markSupported()
- */
- public void testMarkSupported() throws IOException {
- DeflaterInputStream dis = new DeflaterInputStream(is);
- assertFalse(dis.markSupported());
- dis.close();
- assertFalse(dis.markSupported());
- }
-
- /**
- * @tests DeflaterInputStream#read()
- */
- public void testRead() throws IOException {
- DeflaterInputStream dis = new DeflaterInputStream(is);
- assertEquals(1, dis.available());
- assertEquals(120, dis.read());
- assertEquals(1, dis.available());
- assertEquals(156, dis.read());
- assertEquals(1, dis.available());
- assertEquals(243, dis.read());
- assertEquals(1, dis.available());
- dis.close();
- try {
- dis.read();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests DeflaterInputStream#read(byte[],int,int)
- */
- public void testReadByteArrayIntInt() throws IOException {
- byte[] buf1 = new byte[256];
- byte[] buf2 = new byte[256];
- DeflaterInputStream dis = new DeflaterInputStream(is);
- assertEquals(23, dis.read(buf1, 0, 256));
- dis = new DeflaterInputStream(is);
- assertEquals(8, dis.read(buf2, 0, 256));
- is = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
- dis = new DeflaterInputStream(is);
- assertEquals(1, dis.available());
- assertEquals(120, dis.read());
- assertEquals(1, dis.available());
- assertEquals(22, dis.read(buf2, 0, 256));
- assertEquals(1, dis.available());
- assertEquals(-1, dis.read());
- assertEquals(0, dis.available());
- try {
- dis.read(buf1, 0, 512);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- dis.read(null, 0, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- dis.read(null, -1, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- dis.read(null, -1, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- dis.read(buf1, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- dis.read(buf1, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- dis.close();
- try {
- dis.read(buf1, 0, 512);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(buf1, 0, 1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(null, 0, 0);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(null, -1, 0);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(null, -1, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(buf1, -1, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.read(buf1, 0, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests DeflaterInputStream#reset()
- */
- public void testReset() throws IOException {
- DeflaterInputStream dis = new DeflaterInputStream(is);
- try {
- dis.reset();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- dis.close();
- try {
- dis.reset();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests DeflaterInputStream#skip()
- */
- public void testSkip() throws IOException {
- byte[] buf = new byte[1024];
- DeflaterInputStream dis = new DeflaterInputStream(is);
- assertEquals(1, dis.available());
- dis.skip(1);
- assertEquals(1, dis.available());
- assertEquals(22, dis.read(buf, 0, 1024));
- assertEquals(1, dis.available());
- dis.skip(1);
- assertEquals(0, dis.available());
- is = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
- dis = new DeflaterInputStream(is);
- assertEquals(1, dis.available());
- dis.skip(56);
- assertEquals(0, dis.available());
- assertEquals(-1, dis.read(buf, 0, 1024));
- try {
- dis.skip(-1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- assertEquals(0, dis.available());
- // can still skip
- dis.skip(1);
- dis.close();
- try {
- dis.skip(1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- dis.skip(-1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- is = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
- dis = new DeflaterInputStream(is);
- assertEquals(23, dis.skip(Long.MAX_VALUE));
- assertEquals(0, dis.available());
- }
-
- /**
- * @tests DeflaterInputStream#DeflaterInputStream(InputStream)
- */
- public void testDeflaterInputStreamInputStream() {
- // ok
- new DeflaterInputStream(is);
- // fail
- try {
- new DeflaterInputStream(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests DeflaterInputStream#DeflaterInputStream(InputStream,Deflater)
- */
- public void testDeflaterInputStreamInputStreamDeflater() {
- // ok
- new DeflaterInputStream(is, new Deflater());
- // fail
- try {
- new DeflaterInputStream(is, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new DeflaterInputStream(null, new Deflater());
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests DeflaterInputStream#DeflaterInputStream(InputStream,Deflater,int)
- */
- public void testDeflaterInputStreamInputStreamDeflaterInt() {
- // ok
- new DeflaterInputStream(is, new Deflater(), 1024);
- // fail
- try {
- new DeflaterInputStream(is, null, 1024);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new DeflaterInputStream(null, new Deflater(), 1024);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new DeflaterInputStream(is, new Deflater(), -1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- new DeflaterInputStream(null, new Deflater(), -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new DeflaterInputStream(is, null, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- is = new ByteArrayInputStream(testStr.getBytes("UTF-8"));
- }
-
- @Override
- protected void tearDown() throws Exception {
- is.close();
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java
deleted file mode 100644
index c31e654..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java
+++ /dev/null
@@ -1,402 +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 java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.zip.Deflater;
-import java.util.zip.DeflaterOutputStream;
-import java.util.zip.InflaterInputStream;
-
-import junit.framework.TestCase;
-
-public class DeflaterOutputStreamTest extends TestCase {
-
- private class MyDeflaterOutputStream extends DeflaterOutputStream {
- boolean deflateFlag = false;
-
- MyDeflaterOutputStream(OutputStream out) {
- super(out);
- }
-
- MyDeflaterOutputStream(OutputStream out, Deflater defl) {
- super(out, defl);
- }
-
- MyDeflaterOutputStream(OutputStream out, Deflater defl, int size) {
- super(out, defl, size);
- }
-
- byte[] getProtectedBuf() {
- return buf;
- }
-
- protected void deflate() throws IOException {
- deflateFlag = true;
- super.deflate();
- }
-
- boolean getDaflateFlag() {
- return deflateFlag;
- }
- }
-
- private byte outPutBuf[] = new byte[500];
-
- @Override
- protected void setUp() {
- // setting up a deflater to be used
- byte byteArray[] = { 1, 3, 4, 7, 8 };
- int x = 0;
- Deflater deflate = new Deflater(1);
- deflate.setInput(byteArray);
- while (!(deflate.needsInput())) {
- x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- deflate.finish();
- while (!(deflate.finished())) {
- x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- deflate.end();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream,
- * java.util.zip.Deflater)
- */
- public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Deflater() throws Exception {
- byte byteArray[] = { 1, 3, 4, 7, 8 };
- File f1 = new File("hyts_Constru(OD).tst");
- FileOutputStream fos = new FileOutputStream(f1);
- Deflater defl = null;
- MyDeflaterOutputStream dos;
- // Test for a null Deflater.
- try {
- dos = new MyDeflaterOutputStream(fos, defl);
- fail("NullPointerException Not Thrown");
- } catch (NullPointerException e) {
- }
- defl = new Deflater();
- dos = new MyDeflaterOutputStream(fos, defl);
-
- // Test to see if DeflaterOutputStream was created with the correct
- // buffer.
- assertEquals("Incorrect Buffer Size", 512, dos.getProtectedBuf().length);
-
- dos.write(byteArray);
- dos.close();
- f1.delete();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream)
- */
- public void test_ConstructorLjava_io_OutputStream() throws Exception {
- File f1 = new File("hyts_Constru(O).tst");
- FileOutputStream fos = new FileOutputStream(f1);
- MyDeflaterOutputStream dos = new MyDeflaterOutputStream(fos);
-
- // Test to see if DeflaterOutputStream was created with the correct
- // buffer.
- assertEquals("Incorrect Buffer Size", 512, dos.getProtectedBuf().length);
-
- dos.write(outPutBuf);
- dos.close();
- f1.delete();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream,
- * java.util.zip.Deflater, int)
- */
- public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_DeflaterI()
- throws Exception {
- int buf = 5;
- int negBuf = -5;
- int zeroBuf = 0;
- byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 };
- File f1 = new File("hyts_Constru(ODI).tst");
- FileOutputStream fos = new FileOutputStream(f1);
- Deflater defl = null;
- MyDeflaterOutputStream dos;
-
- // Test for a null Deflater.
- try {
- dos = new MyDeflaterOutputStream(fos, defl, buf);
- fail("NullPointerException Not Thrown");
- } catch (NullPointerException e) {
- }
- defl = new Deflater();
-
- // Test for a negative buf.
- try {
- dos = new MyDeflaterOutputStream(fos, defl, negBuf);
- fail("IllegalArgumentException Not Thrown");
- } catch (IllegalArgumentException e) {
- }
-
- // Test for a zero buf.
- try {
- dos = new MyDeflaterOutputStream(fos, defl, zeroBuf);
- fail("IllegalArgumentException Not Thrown");
- } catch (IllegalArgumentException e) {
- }
-
- // Test to see if DeflaterOutputStream was created with the correct
- // buffer.
- dos = new MyDeflaterOutputStream(fos, defl, buf);
- assertEquals("Incorrect Buffer Size", 5, dos.getProtectedBuf().length);
-
- dos.write(byteArray);
- dos.close();
- f1.delete();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#close()
- */
- public void test_close() throws Exception {
- File f1 = File.createTempFile("close", ".tst");
-
- InflaterInputStream iis = new InflaterInputStream(new FileInputStream(f1));
- try {
- iis.read();
- fail("EOFException Not Thrown");
- } catch (EOFException e) {
- }
-
- FileOutputStream fos = new FileOutputStream(f1);
- DeflaterOutputStream dos = new DeflaterOutputStream(fos);
- byte byteArray[] = {1, 3, 4, 6};
- dos.write(byteArray);
- dos.close();
-
- iis = new InflaterInputStream(new FileInputStream(f1));
-
- // Test to see if the finish method wrote the bytes to the file.
- assertEquals("Incorrect Byte Returned.", 1, iis.read());
- assertEquals("Incorrect Byte Returned.", 3, iis.read());
- assertEquals("Incorrect Byte Returned.", 4, iis.read());
- assertEquals("Incorrect Byte Returned.", 6, iis.read());
- assertEquals("Incorrect Byte Returned.", -1, iis.read());
- assertEquals("Incorrect Byte Returned.", -1, iis.read());
- iis.close();
-
- // Not sure if this test will stay.
- FileOutputStream fos2 = new FileOutputStream(f1);
- DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
- fos2.close();
- try {
- dos2.close();
- fail("IOException not thrown");
- } catch (IOException e) {
- }
-
- // Test to write to a closed DeflaterOutputStream
- try {
- dos.write(5);
- fail("DeflaterOutputStream Able To Write After Being Closed.");
- } catch (IOException e) {
- }
-
- // Test to write to a FileOutputStream that should have been closed
- // by
- // the DeflaterOutputStream.
- try {
- fos.write(("testing").getBytes());
- fail("FileOutputStream Able To Write After Being Closed.");
- } catch (IOException e) {
- }
-
- f1.delete();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#finish()
- */
- public void test_finish() throws Exception {
- // Need test to see if method finish() actually finishes
- // Only testing possible errors, not if it actually works
-
- File f1 = new File("finish.tst");
- FileOutputStream fos1 = new FileOutputStream(f1);
- DeflaterOutputStream dos = new DeflaterOutputStream(fos1);
- byte byteArray[] = { 1, 3, 4, 6 };
- dos.write(byteArray);
- dos.finish();
-
- // Test to see if the same FileOutputStream can be used with the
- // DeflaterOutputStream after finish is called.
- try {
- dos.write(1);
- fail("IOException not thrown");
- } catch (IOException e) {
- }
-
- // Test for writing with a new FileOutputStream using the same
- // DeflaterOutputStream.
- FileOutputStream fos2 = new FileOutputStream(f1);
- dos = new DeflaterOutputStream(fos2);
- dos.write(1);
-
- // Test for writing to FileOutputStream fos1, which should be open.
- fos1.write(("testing").getBytes());
-
- // Test for writing to FileOutputStream fos2, which should be open.
- fos2.write(("testing").getBytes());
-
- // Not sure if this test will stay.
- FileOutputStream fos3 = new FileOutputStream(f1);
- DeflaterOutputStream dos3 = new DeflaterOutputStream(fos3);
- fos3.close();
- try {
- dos3.finish();
- fail("IOException not thrown");
- } catch (IOException e) {
- }
-
- // dos.close() won't close fos1 because it has been re-assigned to
- // fos2
- fos1.close();
- dos.close();
- f1.delete();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#write(int)
- */
- public void test_writeI() throws Exception {
- File f1 = new File("writeI1.tst");
- FileOutputStream fos = new FileOutputStream(f1);
- DeflaterOutputStream dos = new DeflaterOutputStream(fos);
- for (int i = 0; i < 3; i++) {
- dos.write(i);
- }
- dos.close();
- FileInputStream fis = new FileInputStream(f1);
- InflaterInputStream iis = new InflaterInputStream(fis);
- for (int i = 0; i < 3; i++) {
- assertEquals("Incorrect Byte Returned.", i, iis.read());
- }
- assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
- assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
- iis.close();
-
- // Not sure if this test is that important.
- // Checks to see if you can write using the DeflaterOutputStream
- // after
- // the FileOutputStream has been closed.
- FileOutputStream fos2 = new FileOutputStream(f1);
- DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
- fos2.close();
- try {
- dos2.write(2);
- fail("IOException not thrown");
- } catch (IOException e) {
- }
-
- f1.delete();
- }
-
- /**
- * @tests java.util.zip.DeflaterOutputStream#write(byte[], int, int)
- */
- public void test_write$BII() throws Exception {
- byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 };
-
- // Test to see if the correct bytes are saved.
- File f1 = new File("writeBII.tst");
- FileOutputStream fos1 = new FileOutputStream(f1);
- DeflaterOutputStream dos1 = new DeflaterOutputStream(fos1);
- dos1.write(byteArray, 2, 3);
- dos1.close();
- FileInputStream fis = new FileInputStream(f1);
- InflaterInputStream iis = new InflaterInputStream(fis);
- assertEquals("Incorrect Byte Returned.", 4, iis.read());
- assertEquals("Incorrect Byte Returned.", 7, iis.read());
- assertEquals("Incorrect Byte Returned.", 8, iis.read());
- assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
- assertEquals("Incorrect Byte Returned (EOF).", -1, iis.read());
- iis.close();
- f1.delete();
-
- // Test for trying to write more bytes than available from the array
- File f2 = new File("writeBII2.tst");
- FileOutputStream fos2 = new FileOutputStream(f2);
- DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
- try {
- dos2.write(byteArray, 2, 10);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- }
-
- // Test for trying to write a negative number of bytes.
- try {
- dos2.write(byteArray, 2, Integer.MIN_VALUE);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- }
-
- // Test for trying to start writing from a byte < 0 from the array.
- try {
- dos2.write(byteArray, Integer.MIN_VALUE, 2);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- }
-
- // Test for trying to start writing from a byte > than the array
- // size.
- try {
- dos2.write(byteArray, 10, 2);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- }
- dos2.close();
-
- // Not sure if this test is that important.
- // Checks to see if you can write using the DeflaterOutputStream
- // after
- // the FileOutputStream has been closed.
- FileOutputStream fos3 = new FileOutputStream(f2);
- DeflaterOutputStream dos3 = new DeflaterOutputStream(fos3);
- fos3.close();
- try {
- dos3.write(byteArray, 2, 3);
- fail("IOException not thrown");
- } catch (IOException e) {
- }
-
- f2.delete();
- }
-
- public void test_deflate() throws Exception {
- File f1 = File.createTempFile("writeI1", ".tst");
- FileOutputStream fos = new FileOutputStream(f1);
- MyDeflaterOutputStream dos = new MyDeflaterOutputStream(fos);
- assertFalse(dos.getDaflateFlag());
- for (int i = 0; i < 3; i++) {
- dos.write(i);
- }
- assertTrue(dos.getDaflateFlag());
- dos.close();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java
deleted file mode 100644
index 8d3e7cd..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java
+++ /dev/null
@@ -1,1102 +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 java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.zip.Adler32;
-import java.util.zip.DataFormatException;
-import java.util.zip.Deflater;
-import java.util.zip.Inflater;
-
-import junit.framework.TestCase;
-import tests.support.resource.Support_Resources;
-
-public class DeflaterTest extends TestCase {
-
- class MyDeflater extends Deflater {
- MyDeflater() {
- super();
- }
-
- MyDeflater(int lvl) {
- super(lvl);
- }
-
- MyDeflater(int lvl, boolean noHeader) {
- super(lvl, noHeader);
- }
-
- void myFinalize() {
- finalize();
- }
-
- int getDefCompression() {
- return DEFAULT_COMPRESSION;
- }
-
- int getDefStrategy() {
- return DEFAULT_STRATEGY;
- }
-
- int getHuffman() {
- return HUFFMAN_ONLY;
- }
-
- int getFiltered() {
- return FILTERED;
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#deflate(byte[])
- */
- public void test_deflate$B() {
- byte outPutBuf[] = new byte[50];
- byte byteArray[] = { 1, 3, 4, 7, 8 };
- byte outPutInf[] = new byte[50];
- int x = 0;
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- x += defl.deflate(outPutBuf);
- }
- assertEquals("Deflater at end of stream, should return 0", 0, defl
- .deflate(outPutBuf));
- int totalOut = defl.getTotalOut();
- int totalIn = defl.getTotalIn();
- assertEquals(x, totalOut);
- assertEquals(byteArray.length, totalIn);
- defl.end();
-
- Inflater infl = new Inflater();
- try {
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- assertEquals(totalIn, infl.getTotalOut());
- assertEquals(totalOut, infl.getTotalIn());
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals(byteArray[i], outPutInf[i]);
- }
- assertEquals("Final decompressed data contained more bytes than original",
- 0, outPutInf[byteArray.length]);
- infl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#deflate(byte[], int, int)
- */
- public void test_deflate$BII() {
- byte outPutBuf[] = new byte[50];
- byte byteArray[] = { 5, 2, 3, 7, 8 };
- byte outPutInf[] = new byte[50];
- int offSet = 1;
- int length = outPutBuf.length - 1;
- int x = 0;
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- x += defl.deflate(outPutBuf, offSet, length);
- }
- assertEquals("Deflater at end of stream, should return 0", 0, defl.deflate(
- outPutBuf, offSet, length));
- int totalOut = defl.getTotalOut();
- int totalIn = defl.getTotalIn();
- assertEquals(x, totalOut);
- assertEquals(byteArray.length, totalIn);
- defl.end();
-
- Inflater infl = new Inflater();
- try {
- infl.setInput(outPutBuf, offSet, length);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- assertEquals(totalIn, infl.getTotalOut());
- assertEquals(totalOut, infl.getTotalIn());
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals(byteArray[i], outPutInf[i]);
- }
- assertEquals("Final decompressed data contained more bytes than original",
- 0, outPutInf[byteArray.length]);
- infl.end();
-
- // Set of tests testing the boundaries of the offSet/length
- defl = new Deflater();
- outPutBuf = new byte[100];
- defl.setInput(byteArray);
- for (int i = 0; i < 2; i++) {
- if (i == 0) {
- offSet = outPutBuf.length + 1;
- length = outPutBuf.length;
- } else {
- offSet = 0;
- length = outPutBuf.length + 1;
- }
- try {
- defl.deflate(outPutBuf, offSet, length);
- fail("Test " + i
- + ": ArrayIndexOutOfBoundsException not thrown");
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- }
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#end()
- */
- public void test_end() {
- byte byteArray[] = { 5, 2, 3, 7, 8 };
- byte outPutBuf[] = new byte[100];
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- defl.end();
- helper_end_test(defl, "end");
- }
-
- /**
- * @tests java.util.zip.Deflater#finalize()
- */
- public void test_finalize() {
- MyDeflater mdefl = new MyDeflater();
- mdefl.myFinalize();
- System.gc();
- helper_end_test(mdefl, "finalize");
- }
-
- /**
- * @tests java.util.zip.Deflater#finish()
- */
- public void test_finish() throws Exception {
- // This test already here, its the same as test_deflate()
- byte byteArray[] = { 5, 2, 3, 7, 8 };
- byte outPutBuf[] = new byte[100];
- byte outPutInf[] = new byte[100];
- int x = 0;
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
-
- // needsInput should never return true after finish() is called
- if (System.getProperty("java.vendor").startsWith("IBM")) {
- assertFalse("needsInput() should return false after finish() is called", defl
- .needsInput());
- }
-
- while (!defl.finished()) {
- x += defl.deflate(outPutBuf);
- }
- int totalOut = defl.getTotalOut();
- int totalIn = defl.getTotalIn();
- assertEquals(x, totalOut);
- assertEquals(byteArray.length, totalIn);
- defl.end();
-
- Inflater infl = new Inflater();
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- assertEquals(totalIn, infl.getTotalOut());
- assertEquals(totalOut, infl.getTotalIn());
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals(byteArray[i], outPutInf[i]);
- }
- assertEquals("Final decompressed data contained more bytes than original",
- 0, outPutInf[byteArray.length]);
- infl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#finished()
- */
- public void test_finished() {
- byte byteArray[] = { 5, 2, 3, 7, 8 };
- byte outPutBuf[] = new byte[100];
- Deflater defl = new Deflater();
- assertTrue("Test 1: Deflater should not be finished.", !defl.finished());
- defl.setInput(byteArray);
- assertTrue("Test 2: Deflater should not be finished.", !defl.finished());
- defl.finish();
- assertTrue("Test 3: Deflater should not be finished.", !defl.finished());
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertTrue("Test 4: Deflater should be finished.", defl.finished());
- defl.end();
- assertTrue("Test 5: Deflater should be finished.", defl.finished());
- }
-
- /**
- * @tests java.util.zip.Deflater#getAdler()
- */
- public void test_getAdler() {
- byte byteArray[] = { 'a', 'b', 'c', 1, 2, 3 };
- byte outPutBuf[] = new byte[100];
- Deflater defl = new Deflater();
-
- // getting the checkSum value using the Adler
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- long checkSumD = defl.getAdler();
- defl.end();
-
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(byteArray);
- long checkSumR = adl.getValue();
- assertEquals(
- "The checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
- checkSumD, checkSumR);
- }
-
- /**
- * @tests java.util.zip.Deflater#getTotalIn()
- */
- public void test_getTotalIn() {
- byte outPutBuf[] = new byte[5];
- byte byteArray[] = { 1, 3, 4, 7, 8 };
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertEquals(byteArray.length, defl.getTotalIn());
- defl.end();
-
- defl = new Deflater();
- int offSet = 2;
- int length = 3;
- outPutBuf = new byte[5];
- defl.setInput(byteArray, offSet, length);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertEquals(length, defl.getTotalIn());
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#getTotalOut()
- */
- public void test_getTotalOut() {
- // the getTotalOut should equal the sum of value returned by deflate()
- byte outPutBuf[] = new byte[5];
- byte byteArray[] = { 5, 2, 3, 7, 8 };
- int x = 0;
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- x += defl.deflate(outPutBuf);
- }
- assertEquals(x, defl.getTotalOut());
- defl.end();
-
- x = 0;
- int offSet = 2;
- int length = 3;
- defl = new Deflater();
- outPutBuf = new byte[5];
- defl.setInput(byteArray, offSet, length);
- defl.finish();
- while (!defl.finished()) {
- x += defl.deflate(outPutBuf);
- }
- assertEquals(x, defl.getTotalOut());
- }
-
- /**
- * @tests java.util.zip.Deflater#needsInput()
- */
- public void test_needsInput() {
- Deflater defl = new Deflater();
- assertTrue(
- "needsInput give the wrong boolean value as a result of no input buffer",
- defl.needsInput());
- byte byteArray[] = { 1, 2, 3 };
- defl.setInput(byteArray);
- assertFalse(
- "needsInput give wrong boolean value as a result of a full input buffer",
- defl.needsInput());
- byte[] outPutBuf = new byte[50];
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- byte emptyByteArray[] = new byte[0];
- defl.setInput(emptyByteArray);
- assertTrue(
- "needsInput give wrong boolean value as a result of an empty input buffer",
- defl.needsInput());
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- // needsInput should NOT return true after finish() has been
- // called.
- if (System.getProperty("java.vendor").startsWith("IBM")) {
- assertFalse(
- "needsInput gave wrong boolean value as a result of finish() being called",
- defl.needsInput());
- }
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#reset()
- */
- public void test_reset() {
- byte outPutBuf[] = new byte[100];
- byte outPutInf[] = new byte[100];
- byte curArray[] = new byte[5];
- byte byteArray[] = { 1, 3, 4, 7, 8 };
- byte byteArray2[] = { 8, 7, 4, 3, 1 };
- int x = 0;
- int orgValue = 0;
- Deflater defl = new Deflater();
-
- for (int i = 0; i < 3; i++) {
- if (i == 0) {
- curArray = byteArray;
- } else if (i == 1) {
- curArray = byteArray2;
- } else {
- defl.reset();
- }
-
- defl.setInput(curArray);
- defl.finish();
- while (!defl.finished()) {
- x += defl.deflate(outPutBuf);
- }
-
- if (i == 0) {
- assertEquals(x, defl.getTotalOut());
- } else if (i == 1) {
- assertEquals(x, orgValue);
- } else {
- assertEquals(x, orgValue * 2);
- }
-
- if (i == 0) {
- orgValue = x;
- }
-
- try {
- Inflater infl = new Inflater();
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- infl.end();
- } catch (DataFormatException e) {
- fail("Test " + i + ": Invalid input to be decompressed");
- }
-
- if (i == 1) {
- curArray = byteArray;
- }
-
- for (int j = 0; j < curArray.length; j++) {
- assertEquals(curArray[j], outPutInf[j]);
- }
- assertEquals(0, outPutInf[curArray.length]);
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setDictionary(byte[])
- */
- public void test_setDictionary$B() {
- // This test is very close to getAdler()
- byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
- byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
- 'w', 'r' };
- byte outPutBuf[] = new byte[100];
-
- Deflater defl = new Deflater();
- long deflAdler = defl.getAdler();
- assertEquals("No dictionary set, no data deflated, getAdler should return 1",
- 1, deflAdler);
- defl.setDictionary(dictionaryArray);
- deflAdler = defl.getAdler();
-
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(dictionaryArray);
- long realAdler = adl.getValue();
- assertEquals(deflAdler, realAdler);
-
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- deflAdler = defl.getAdler();
- adl = new Adler32();
- adl.update(byteArray);
- realAdler = adl.getValue();
- // Deflate is finished and there were bytes deflated that did not occur
- // in the dictionaryArray, therefore a new dictionary was automatically
- // set.
- assertEquals(realAdler, deflAdler);
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#setDictionary(byte[], int, int)
- */
- public void test_setDictionary$BII() {
- // This test is very close to getAdler()
- byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't' };
- byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
- 'w', 'r', 't', 'u', 'i', 'o', 4, 5, 6, 7 };
- byte outPutBuf[] = new byte[500];
-
- int offSet = 4;
- int length = 5;
-
- Deflater defl = new Deflater();
- long deflAdler = defl.getAdler();
- assertEquals("No dictionary set, no data deflated, getAdler should return 1",
- 1, deflAdler);
- defl.setDictionary(dictionaryArray, offSet, length);
- deflAdler = defl.getAdler();
-
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(dictionaryArray, offSet, length);
- long realAdler = adl.getValue();
- assertEquals(deflAdler, realAdler);
-
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- deflAdler = defl.getAdler();
- adl = new Adler32();
- adl.update(byteArray);
- realAdler = adl.getValue();
- // Deflate is finished and there were bytes deflated that did not occur
- // in the dictionaryArray, therefore a new dictionary was automatically
- // set.
- assertEquals(realAdler, deflAdler);
- defl.end();
-
- // boundary check
- defl = new Deflater();
- for (int i = 0; i < 2; i++) {
- if (i == 0) {
- offSet = 0;
- length = dictionaryArray.length + 1;
- } else {
- offSet = dictionaryArray.length + 1;
- length = 1;
- }
- try {
- defl.setDictionary(dictionaryArray, offSet, length);
- fail(
- "Test "
- + i
- + ": boundary check for setDictionary failed for offset "
- + offSet + " and length " + length);
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setInput(byte[])
- */
- public void test_setInput$B() {
- byte[] byteArray = { 1, 2, 3 };
- byte[] outPutBuf = new byte[50];
- byte[] outPutInf = new byte[50];
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- assertTrue("the array buffer in setInput() is empty", !defl
- .needsInput());
- // The second setInput() should be ignored since needsInput() return
- // false
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- defl.end();
-
- Inflater infl = new Inflater();
- try {
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals(byteArray[i], outPutInf[i]);
- }
- assertEquals(byteArray.length, infl.getTotalOut());
- infl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#setInput(byte[], int, int)
- */
- public void test_setInput$BII() throws Exception {
- byte[] byteArray = { 1, 2, 3, 4, 5 };
- byte[] outPutBuf = new byte[50];
- byte[] outPutInf = new byte[50];
- int offSet = 1;
- int length = 3;
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray, offSet, length);
- assertFalse("the array buffer in setInput() is empty", defl.needsInput());
- // The second setInput() should be ignored since needsInput() return
- // false
- defl.setInput(byteArray, offSet, length);
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- defl.end();
-
- Inflater infl = new Inflater();
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- for (int i = 0; i < length; i++) {
- assertEquals(byteArray[i + offSet], outPutInf[i]);
- }
- assertEquals(length, infl.getTotalOut());
- infl.end();
-
- // boundary check
- defl = new Deflater();
- for (int i = 0; i < 2; i++) {
- if (i == 0) {
- offSet = 0;
- length = byteArray.length + 1;
- } else {
- offSet = byteArray.length + 1;
- length = 1;
- }
- try {
- defl.setInput(byteArray, offSet, length);
- fail("Test " + i
- + ": boundary check for setInput failed for offset "
- + offSet + " and length " + length);
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setLevel(int)
- */
- public void test_setLevelI() throws Exception {
- // Very similar to test_Constructor(int)
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- byte[] outPutBuf;
- int totalOut;
- for (int i = 0; i < 10; i++) {
- Deflater defl = new Deflater();
- defl.setLevel(i);
- outPutBuf = new byte[500];
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- totalOut = defl.getTotalOut();
- defl.end();
-
- outPutBuf = new byte[500];
- defl = new Deflater(i);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertEquals(totalOut, defl.getTotalOut());
- defl.end();
- }
-
- // testing boundaries
- try {
- Deflater boundDefl = new Deflater();
- // Level must be between 0-9
- boundDefl.setLevel(-2);
- fail(
- "IllegalArgumentException not thrown when setting level to a number < 0.");
- } catch (IllegalArgumentException e) {
- }
- try {
- Deflater boundDefl = new Deflater();
- boundDefl.setLevel(10);
- fail(
- "IllegalArgumentException not thrown when setting level to a number > 9.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setStrategy(int)
- */
- public void test_setStrategyI() throws Exception {
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- for (int i = 0; i < 3; i++) {
- byte outPutBuf[] = new byte[500];
- MyDeflater mdefl = new MyDeflater();
-
- if (i == 0) {
- mdefl.setStrategy(mdefl.getDefStrategy());
- } else if (i == 1) {
- mdefl.setStrategy(mdefl.getHuffman());
- } else {
- mdefl.setStrategy(mdefl.getFiltered());
- }
-
- mdefl.setInput(byteArray);
- while (!mdefl.needsInput()) {
- mdefl.deflate(outPutBuf);
- }
- mdefl.finish();
- while (!mdefl.finished()) {
- mdefl.deflate(outPutBuf);
- }
-
- if (i == 0) {
- // System.out.println(mdefl.getTotalOut());
- // ran JDK and found that getTotalOut() = 86 for this particular
- // file
- assertEquals("getTotalOut() for the default strategy did not correspond with JDK",
- 86, mdefl.getTotalOut());
- } else if (i == 1) {
- // System.out.println(mdefl.getTotalOut());
- // ran JDK and found that getTotalOut() = 100 for this
- // particular file
- assertEquals("getTotalOut() for the Huffman strategy did not correspond with JDK",
- 100, mdefl.getTotalOut());
- } else {
- // System.out.println(mdefl.getTotalOut());
- // ran JDK and found that totalOut = 93 for this particular file
- assertEquals("Total Out for the Filtered strategy did not correspond with JDK",
- 93, mdefl.getTotalOut());
- }
- mdefl.end();
- }
-
- // Attempting to setStrategy to an invalid value
- try {
- Deflater defl = new Deflater();
- defl.setStrategy(-412);
- fail(
- "IllegalArgumentException not thrown when setting strategy to an invalid value.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#Deflater()
- */
- public void test_Constructor() throws Exception {
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- Deflater defl = new Deflater();
- byte[] outPutBuf = new byte[500];
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- int totalOut = defl.getTotalOut();
- defl.end();
-
- // creating a Deflater using the DEFAULT_COMPRESSION as the int
- MyDeflater mdefl = new MyDeflater();
- mdefl = new MyDeflater(mdefl.getDefCompression());
- outPutBuf = new byte[500];
- mdefl.setInput(byteArray);
- while (!mdefl.needsInput()) {
- mdefl.deflate(outPutBuf);
- }
- mdefl.finish();
- while (!mdefl.finished()) {
- mdefl.deflate(outPutBuf);
- }
- assertEquals(totalOut, mdefl.getTotalOut());
- mdefl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#Deflater(int, boolean)
- */
- public void test_ConstructorIZ() throws Exception {
- byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
- 'w', 'r' };
-
- Deflater defl = new Deflater();
- byte outPutBuf[] = new byte[500];
- defl.setLevel(2);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- int totalOut = defl.getTotalOut();
- defl.end();
-
- outPutBuf = new byte[500];
- defl = new Deflater(2, false);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertEquals(totalOut, defl.getTotalOut());
- defl.end();
-
- outPutBuf = new byte[500];
- defl = new Deflater(2, true);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertTrue(
- "getTotalOut() should not be equal comparing two Deflaters with different header options.",
- defl.getTotalOut() != totalOut);
- defl.end();
-
- byte outPutInf[] = new byte[500];
- Inflater infl = new Inflater(true);
- while (!infl.finished()) {
- if (infl.needsInput()) {
- infl.setInput(outPutBuf);
- }
- infl.inflate(outPutInf);
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals(byteArray[i], outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - constructorIZ",
- 0, outPutInf[byteArray.length]);
- infl.end();
-
- infl = new Inflater(false);
- outPutInf = new byte[500];
- int r = 0;
- try {
- while (!infl.finished()) {
- if (infl.needsInput()) {
- infl.setInput(outPutBuf);
- }
- infl.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- r = 1;
- }
- assertEquals("header option did not correspond", 1, r);
-
- // testing boundaries
- try {
- Deflater boundDefl = new Deflater();
- // Level must be between 0-9
- boundDefl.setLevel(-2);
- fail("IllegalArgumentException not thrown when setting level to a number < 0.");
- } catch (IllegalArgumentException e) {
- }
- try {
- Deflater boundDefl = new Deflater();
- boundDefl.setLevel(10);
- fail("IllegalArgumentException not thrown when setting level to a number > 9.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#Deflater(int)
- */
- public void test_ConstructorI() throws Exception {
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- byte outPutBuf[] = new byte[500];
- Deflater defl = new Deflater(3);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- int totalOut = defl.getTotalOut();
- defl.end();
-
- // test to see if the compression ratio is the same as setting the level
- // on a deflater
- outPutBuf = new byte[500];
- defl = new Deflater();
- defl.setLevel(3);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
- defl.deflate(outPutBuf);
- }
- defl.finish();
- while (!defl.finished()) {
- defl.deflate(outPutBuf);
- }
- assertEquals(totalOut, defl.getTotalOut());
- defl.end();
-
- // testing boundaries
- try {
- Deflater boundDefl = new Deflater();
- // Level must be between 0-9
- boundDefl.setLevel(-2);
- fail("IllegalArgumentException not thrown when setting level to a number < 0.");
- } catch (IllegalArgumentException e) {
- }
- try {
- Deflater boundDefl = new Deflater();
- boundDefl.setLevel(10);
- fail("IllegalArgumentException not thrown when setting level to a number > 9.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- private void helper_end_test(Deflater defl, String desc) {
- // Help tests for test_end() and test_reset().
- byte byteArray[] = { 5, 2, 3, 7, 8 };
-
- // Methods where we expect IllegalStateException or NullPointerException
- // to be thrown
- try {
- defl.getTotalOut();
- fail("defl.getTotalOut() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getTotalIn();
- fail("defl.getTotalIn() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getAdler();
- fail("defl.getAdler() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- byte[] dict = { 'a', 'b', 'c' };
- defl.setDictionary(dict);
- fail("defl.setDictionary() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getTotalIn();
- fail("defl.getTotalIn() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getTotalIn();
- fail("defl.getTotalIn() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.deflate(byteArray);
- fail("defl.deflate() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
-
- // Methods where we expect NullPointerException to be thrown
- try {
- defl.reset();
- fail("defl.reset() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (NullPointerException e) {
- }
-
- // Methods that should be allowed to be called after end() is called
- defl.needsInput();
- defl.setStrategy(1);
- defl.setLevel(1);
- defl.end();
-
- // Methods where exceptions should be thrown
- String vendor = System.getProperty("java.vendor");
- if (vendor.indexOf("IBM") != -1) {
- try {
- defl.setInput(byteArray);
- fail("defl.setInput() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- }
- }
- }
-
- /**
- * @tests java.util.zip.Deflater()
- */
- public void test_needsDictionary() {
- Deflater inf = new Deflater();
- assertEquals(0, inf.getTotalIn());
- assertEquals(0, inf.getTotalOut());
- assertEquals(0, inf.getBytesRead());
- assertEquals(0, inf.getBytesWritten());
- }
-
- /**
- * @throws DataFormatException
- * @throws UnsupportedEncodingException
- * @tests java.util.zip.Deflater#getBytesRead()
- */
- public void test_getBytesRead() throws DataFormatException,
- UnsupportedEncodingException {
- // Regression test for HARMONY-158
- Deflater def = new Deflater();
- assertEquals(0, def.getTotalIn());
- assertEquals(0, def.getTotalOut());
- assertEquals(0, def.getBytesRead());
- // Encode a String into bytes
- String inputString = "blahblahblah??";
- byte[] input = inputString.getBytes("UTF-8");
-
- // Compress the bytes
- byte[] output = new byte[100];
- def.setInput(input);
- def.finish();
- int compressedDataLength = def.deflate(output);
- assertEquals(14, def.getTotalIn());
- assertEquals(compressedDataLength, def.getTotalOut());
- assertEquals(14, def.getBytesRead());
- }
-
- /**
- * @throws DataFormatException
- * @throws UnsupportedEncodingException
- * @tests java.util.zip.Deflater#getBytesRead()
- */
- public void test_getBytesWritten() throws DataFormatException,
- UnsupportedEncodingException {
- // Regression test for HARMONY-158
- Deflater def = new Deflater();
- assertEquals(0, def.getTotalIn());
- assertEquals(0, def.getTotalOut());
- assertEquals(0, def.getBytesWritten());
- // Encode a String into bytes
- String inputString = "blahblahblah??";
- byte[] input = inputString.getBytes("UTF-8");
-
- // Compress the bytes
- byte[] output = new byte[100];
- def.setInput(input);
- def.finish();
- int compressedDataLength = def.deflate(output);
- assertEquals(14, def.getTotalIn());
- assertEquals(compressedDataLength, def.getTotalOut());
- assertEquals(compressedDataLength, def.getBytesWritten());
- }
-
- //Regression Test for HARMONY-2481
- public void test_deflate_beforeSetInput() throws Exception {
- Deflater deflater = new Deflater();
- deflater.finish();
- byte[] buffer = new byte[1024];
- assertEquals(8, deflater.deflate(buffer));
- byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 };
- for (int i = 0; i < expectedBytes.length; i++) {
- assertEquals(expectedBytes[i], buffer[i]);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java
deleted file mode 100644
index e969387..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java
+++ /dev/null
@@ -1,297 +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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.zip.Checksum;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
-
-import tests.support.resource.Support_Resources;
-
-public class GZIPInputStreamTest extends junit.framework.TestCase {
- File resources;
-
- class TestGZIPInputStream extends GZIPInputStream {
- TestGZIPInputStream(InputStream in) throws IOException {
- super(in);
- }
-
- TestGZIPInputStream(InputStream in, int size) throws IOException {
- super(in, size);
- }
-
- Checksum getChecksum() {
- return crc;
- }
-
- boolean endofInput() {
- return eos;
- }
- }
-
- /**
- * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream)
- */
- public void test_ConstructorLjava_io_InputStream() {
- // test method java.util.zip.GZIPInputStream.constructor
- try {
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- final URL gInput = new File(resources.toString()
- + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream());
- assertNotNull("the constructor for GZIPInputStream is null",
- inGZIP);
- assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP
- .getChecksum().getValue());
- inGZIP.close();
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to open the input file");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream,
- * int)
- */
- public void test_ConstructorLjava_io_InputStreamI() {
- // test method java.util.zip.GZIPInputStream.constructorI
- try {
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- final URL gInput = new File(resources.toString()
- + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream(), 200);
- assertNotNull("the constructor for GZIPInputStream is null",
- inGZIP);
- assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP
- .getChecksum().getValue());
- inGZIP.close();
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to open the input file");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPInputStream#read(byte[], int, int)
- */
- public void test_read$BII() throws IOException {
- // test method java.util.zip.GZIPInputStream.readBII
- byte orgBuf[] = { '3', '5', '2', 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
- byte outBuf[] = new byte[100];
- int result = 0;
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- String resPath = resources.toString();
- if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
- resPath = resPath.substring(1);
- }
- final URL gInput = new URL("file:/" + resPath
- + "/GZIPInputStream/hyts_gInput.txt.gz");
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream());
- while (!(inGZIP.endofInput())) {
- result += inGZIP.read(outBuf, result, outBuf.length - result);
- }
- assertEquals(
- "the checkSum value of the compressed and decompressed data does not equal",
- 2074883667L, inGZIP.getChecksum().getValue());
- for (int i = 0; i < orgBuf.length; i++) {
- assertTrue(
- "the decompressed data does not equal the original data decompressed",
- orgBuf[i] == outBuf[i]);
- // System.out.println(orgBuf[i] + " " + outBuf[i]);
- }
- int r = 0;
- try {
- inGZIP.read(outBuf, 100, 1);
- } catch (IndexOutOfBoundsException e) {
- r = 1;
- }
- inGZIP.close();
- // line below fails on RI also, comment out.
- // assertEquals("Boundary Check was not present", 1, r);
-
- // Create compressed data which is exactly 512 bytes (after the
- // header),
- // the size of the InflaterStream internal buffer
- byte[] test = new byte[507];
- for (int i = 0; i < 256; i++) {
- test[i] = (byte) i;
- }
- for (int i = 256; i < test.length; i++) {
- test[i] = (byte) (256 - i);
- }
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- GZIPOutputStream out = new GZIPOutputStream(bout);
- out.write(test);
- out.close();
- byte[] comp = bout.toByteArray();
- GZIPInputStream gin2 = new GZIPInputStream(new ByteArrayInputStream(
- comp), 512);
- int total = 0;
- while ((result = gin2.read(test)) != -1) {
- total += result;
- }
- assertEquals("Should return -1", -1, gin2.read());
- gin2.close();
- assertTrue("Incorrectly decompressed", total == test.length);
-
- gin2 = new GZIPInputStream(new ByteArrayInputStream(comp), 512);
- total = 0;
- while ((result = gin2.read(new byte[200])) != -1) {
- total += result;
- }
- assertEquals("Should return -1", -1, gin2.read());
- gin2.close();
- assertTrue("Incorrectly decompressed", total == test.length);
-
- gin2 = new GZIPInputStream(new ByteArrayInputStream(comp), 516);
- total = 0;
- while ((result = gin2.read(new byte[200])) != -1) {
- total += result;
- }
- assertEquals("Should return -1", -1, gin2.read());
- gin2.close();
- assertTrue("Incorrectly decompressed", total == test.length);
-
- comp[40] = 0;
- gin2 = new GZIPInputStream(new ByteArrayInputStream(comp), 512);
- boolean exception = false;
- try {
- while (gin2.read(test) != -1) {
- ;
- }
- } catch (IOException e) {
- exception = true;
- }
- assertTrue("Exception expected", exception);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- GZIPOutputStream zipout = new GZIPOutputStream(baos);
- zipout.write(test);
- zipout.close();
- outBuf = new byte[530];
- GZIPInputStream in= new GZIPInputStream(new ByteArrayInputStream(baos.toByteArray()));
- try {
- in.read(outBuf, 530, 1);
- fail("Test failed IOOBE was not thrown");
- } catch (IndexOutOfBoundsException e) {
- }
- while (true) {
- result = in.read(outBuf, 0, 5);
- if (result == -1) {
- //"EOF was reached";
- break;
- }
- }
- result = -10;
- result = in.read(null, 100, 1);
- result = in.read(outBuf, -100, 1);
- result = in.read(outBuf, -1, 1);// 100, 1);
- }
-
- /**
- * @tests java.util.zip.GZIPInputStream#close()
- */
- public void test_close() {
- // test method java.util.zip.GZIPInputStream.close
- byte outBuf[] = new byte[100];
- try {
- int result = 0;
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- String resPath = resources.toString();
- if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
- resPath = resPath.substring(1);
- }
- final URL gInput = new URL("file:/" + resPath
- + "/GZIPInputStream/hyts_gInput.txt.gz");
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream());
- while (!(inGZIP.endofInput())) {
- result += inGZIP.read(outBuf, result, outBuf.length - result);
- }
- assertEquals("the checkSum value of the compressed and decompressed data does not equal",
- 2074883667L, inGZIP.getChecksum().getValue());
- inGZIP.close();
- int r = 0;
- try {
- inGZIP.read(outBuf, 0, 1);
- } catch (IOException e) {
- r = 1;
- }
- assertEquals("GZIPInputStream can still be used after close is called",
- 1, r);
- } catch (IOException e) {
- e.printStackTrace();
- fail("unexpected: " + e);
- }
- }
-
- /**
- * Regression test for HARMONY-3703.
- * @tests java.util.zip.GZIPInputStream#read()
- */
- public void test_read() throws IOException {
- GZIPInputStream gis = null;
- int result = 0;
- byte[] buffer = new byte[] {1,2,3,4,5,6,7,8,9,10};
- File f = new File(resources.getAbsolutePath() + "test.gz");
- FileOutputStream out = new FileOutputStream(f);
- GZIPOutputStream gout = new GZIPOutputStream(out);
-
- // write 100 bytes to the stream
- for(int i = 0; i < 10; i++) {
- gout.write(buffer);
- }
- gout.finish();
- out.write(1);
- out.close();
-
- gis = new GZIPInputStream(new FileInputStream(f));
- buffer = new byte[100];
- gis.read(buffer);
- result = gis.read();
- gis.close();
- f.delete();
-
- assertEquals("Incorrect value returned at the end of the file", -1, result);
- }
-
- @Override
- protected void setUp() {
- resources = Support_Resources.createTempFolder();
- }
-
- @Override
- protected void tearDown() {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java
deleted file mode 100644
index f381cd1..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java
+++ /dev/null
@@ -1,182 +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 java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.zip.Checksum;
-import java.util.zip.GZIPOutputStream;
-
-public class GZIPOutputStreamTest extends junit.framework.TestCase {
-
- class TestGZIPOutputStream extends GZIPOutputStream {
- TestGZIPOutputStream(OutputStream out) throws IOException {
- super(out);
- }
-
- TestGZIPOutputStream(OutputStream out, int size) throws IOException {
- super(out, size);
- }
-
- Checksum getChecksum() {
- return crc;
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream)
- */
- public void test_ConstructorLjava_io_OutputStream() {
- try {
- FileOutputStream outFile = new FileOutputStream("GZIPOutCon.txt");
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
- assertNotNull("the constructor for GZIPOutputStream is null",
- outGZIP);
- assertEquals("the CRC value of the outputStream is not zero", 0, outGZIP
- .getChecksum().getValue());
- outGZIP.close();
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream,
- * int)
- */
- public void test_ConstructorLjava_io_OutputStreamI() {
- try {
- FileOutputStream outFile = new FileOutputStream("GZIPOutCon.txt");
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile,
- 100);
- assertNotNull("the constructor for GZIPOutputStream is null",
- outGZIP);
- assertEquals("the CRC value of the outputStream is not zero", 0, outGZIP
- .getChecksum().getValue());
- outGZIP.close();
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#finish()
- */
- public void test_finish() {
- // test method java.util.zip.GZIPOutputStream.finish()
- byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
- try {
- FileOutputStream outFile = new FileOutputStream("GZIPOutFinish.txt");
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
-
- outGZIP.finish();
- int r = 0;
- try {
- outGZIP.write(byteArray, 0, 1);
- } catch (IOException e) {
- r = 1;
- }
-
- assertEquals("GZIP instance can still be used after finish is called",
- 1, r);
- outGZIP.close();
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#close()
- */
- public void test_close() {
- // test method java.util.zip.GZIPOutputStream.close()
- byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
- try {
- FileOutputStream outFile = new FileOutputStream("GZIPOutClose2.txt");
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
- outGZIP.close();
- int r = 0;
- try {
- outGZIP.write(byteArray, 0, 1);
- } catch (IOException e) {
- r = 1;
- }
- assertEquals("GZIP instance can still be used after close is called",
- 1, r);
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#write(byte[], int, int)
- */
- public void test_write$BII() {
- // test method java.util.zip.GZIPOutputStream.writeBII
- byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
- try {
- FileOutputStream outFile = new FileOutputStream("GZIPOutWrite.txt");
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
- outGZIP.write(byteArray, 0, 10);
- // ran JDK and found this CRC32 value is 3097700292
- // System.out.print(outGZIP.getChecksum().getValue());
- assertEquals("the checksum value was incorrect result of write from GZIP",
- 3097700292L, outGZIP.getChecksum().getValue());
-
- // test for boundary check
- int r = 0;
- try {
- outGZIP.write(byteArray, 0, 11);
- } catch (IndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("out of bounds exception is not present", 1, r);
- outGZIP.close();
- } catch (IOException e) {
- fail(
- "an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- @Override
- protected void setUp() {
- }
-
- @Override
- protected void tearDown() {
-
- try {
- File dFile = new File("GZIPOutCon.txt");
- dFile.delete();
- File dFile2 = new File("GZIPOutFinish.txt");
- dFile2.delete();
- File dFile3 = new File("GZIPOutWrite.txt");
- dFile3.delete();
- File dFile4 = new File("GZIPOutClose2.txt");
- dFile4.delete();
- } catch (SecurityException e) {
- fail("Cannot delete file for security reasons");
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java
deleted file mode 100644
index 8f37652..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java
+++ /dev/null
@@ -1,416 +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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.zip.DeflaterOutputStream;
-import java.util.zip.Inflater;
-import java.util.zip.InflaterInputStream;
-
-import junit.framework.TestCase;
-import tests.support.resource.Support_Resources;
-
-public class InflaterInputStreamTest extends TestCase {
-
- // files hyts_constru(O),hyts_constru(OD),hyts_constru(ODI) needs to be
- // included as resources
- // android-changed: we removed the parentheses for the benefit of our broken build system.
- byte outPutBuf[] = new byte[500];
-
- class MyInflaterInputStream extends InflaterInputStream {
- MyInflaterInputStream(InputStream in) {
- super(in);
- }
-
- MyInflaterInputStream(InputStream in, Inflater infl) {
- super(in, infl);
- }
-
- MyInflaterInputStream(InputStream in, Inflater infl, int size) {
- super(in, infl, size);
- }
-
- void myFill() throws IOException {
- fill();
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream)
- */
- public void test_ConstructorLjava_io_InputStream() throws IOException {
- //FIXME This test doesn't pass in Harmony classlib or Sun 5.0_7 RI
- /*
- int result = 0;
- int buffer[] = new int[500];
- InputStream infile = Support_Resources
- .getStream("hyts_constru_O.txt"); // android-changed
-
- InflaterInputStream inflatIP = new InflaterInputStream(infile);
-
- int i = 0;
- while ((result = inflatIP.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP.close();
- */
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
- * java.util.zip.Inflater)
- */
- public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Inflater() throws IOException {
- byte byteArray[] = new byte[100];
- InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); // android-changed
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile,
- inflate);
-
- inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes
- inflatIP.close();
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
- * java.util.zip.Inflater, int)
- */
- public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI() throws IOException {
- int result = 0;
- int buffer[] = new int[500];
- InputStream infile = Support_Resources.getStream("hyts_constru_ODI.txt"); // android-changed
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile,
- inflate, 1);
-
- int i = 0;
- while ((result = inflatIP.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP.close();
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#mark(int)
- */
- public void test_markI() {
- InputStream is = new ByteArrayInputStream(new byte[10]);
- InflaterInputStream iis = new InflaterInputStream(is);
- // mark do nothing, do no check
- iis.mark(0);
- iis.mark(-1);
- iis.mark(10000000);
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#markSupported()
- */
- public void test_markSupported() {
- InputStream is = new ByteArrayInputStream(new byte[10]);
- InflaterInputStream iis = new InflaterInputStream(is);
- assertFalse(iis.markSupported());
- assertTrue(is.markSupported());
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#read()
- */
- public void test_read() throws IOException {
- int result = 0;
- int buffer[] = new int[500];
- byte orgBuffer[] = { 1, 3, 4, 7, 8 };
- InputStream infile = Support_Resources
- .getStream("hyts_constru_OD.txt"); // android-changed
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile,
- inflate);
-
- int i = 0;
- while ((result = inflatIP.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP.close();
-
- for (int j = 0; j < orgBuffer.length; j++) {
- assertTrue(
- "original compressed data did not equal decompressed data",
- buffer[j] == orgBuffer[j]);
- }
- }
-
- public void testAvailableNonEmptySource() throws Exception {
- // this byte[] is a deflation of these bytes: { 1, 3, 4, 6 }
- byte[] deflated = { 72, -119, 99, 100, 102, 97, 3, 0, 0, 31, 0, 15, 0 };
- InputStream in = new InflaterInputStream(new ByteArrayInputStream(deflated));
- // InflaterInputStream.available() returns either 1 or 0, even though
- // that contradicts the behavior defined in InputStream.available()
- assertEquals(1, in.read());
- assertEquals(1, in.available());
- assertEquals(3, in.read());
- assertEquals(1, in.available());
- assertEquals(4, in.read());
- assertEquals(1, in.available());
- assertEquals(6, in.read());
- assertEquals(0, in.available());
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
- }
-
- public void testAvailableSkip() throws Exception {
- // this byte[] is a deflation of these bytes: { 1, 3, 4, 6 }
- byte[] deflated = { 72, -119, 99, 100, 102, 97, 3, 0, 0, 31, 0, 15, 0 };
- InputStream in = new InflaterInputStream(new ByteArrayInputStream(deflated));
- assertEquals(1, in.available());
- assertEquals(4, in.skip(4));
- assertEquals(0, in.available());
- }
-
- public void testAvailableEmptySource() throws Exception {
- // this byte[] is a deflation of the empty file
- byte[] deflated = { 120, -100, 3, 0, 0, 0, 0, 1 };
- InputStream in = new InflaterInputStream(new ByteArrayInputStream(deflated));
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
- assertEquals(0, in.available());
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#read(byte[], int, int)
- */
- public void test_read$BII() throws IOException{
- byte[] test = new byte[507];
- for (int i = 0; i < 256; i++) {
- test[i] = (byte) i;
- }
- for (int i = 256; i < test.length; i++) {
- test[i] = (byte) (256 - i);
- }
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DeflaterOutputStream dos = new DeflaterOutputStream(baos);
- dos.write(test);
- dos.close();
- InputStream is = new ByteArrayInputStream(baos.toByteArray());
- InflaterInputStream iis = new InflaterInputStream(is);
- byte[] outBuf = new byte[530];
- int result = 0;
- while (true) {
- result = iis.read(outBuf, 0, 5);
- if (result == -1) {
- //"EOF was reached";
- break;
- }
- }
- try {
- iis.read(outBuf, -1, 10);
- fail("should throw IOOBE.");
- } catch (IndexOutOfBoundsException e) {
- // expected;
- }
- }
-
- public void test_read$BII2() throws IOException {
- File resources = Support_Resources.createTempFolder();
- Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
- FileInputStream fis = new FileInputStream(new File(resources,
- "Broken_manifest.jar"));
- InflaterInputStream iis = new InflaterInputStream(fis);
- byte[] outBuf = new byte[530];
-
- iis.close();
- try {
- iis.read(outBuf, 0, 5);
- fail("IOException expected");
- } catch (IOException ee) {
- // expected.
- }
- }
-
- public void test_read$BII3() throws IOException {
- File resources = Support_Resources.createTempFolder();
- Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
- FileInputStream fis = new FileInputStream(new File(resources,
- "Broken_manifest.jar"));
- InflaterInputStream iis = new InflaterInputStream(fis);
- byte[] outBuf = new byte[530];
-
- try {
- iis.read();
- fail("IOException expected.");
- } catch (IOException ee) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#reset()
- */
- public void test_reset() {
- InputStream is = new ByteArrayInputStream(new byte[10]);
- InflaterInputStream iis = new InflaterInputStream(is);
- try {
- iis.reset();
- fail("Should throw IOException");
- } catch (IOException e) {
- // correct
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#skip(long)
- */
- public void test_skipJ() throws IOException {
- InputStream is = Support_Resources.getStream("hyts_available.tst");
- InflaterInputStream iis = new InflaterInputStream(is);
-
- // Tests for skipping a negative number of bytes.
- try {
- iis.skip(-3);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- assertEquals("Incorrect Byte Returned.", 5, iis.read());
-
- try {
- iis.skip(Integer.MIN_VALUE);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- assertEquals("Incorrect Byte Returned.", 4, iis.read());
-
- // Test to make sure the correct number of bytes were skipped
- assertEquals("Incorrect Number Of Bytes Skipped.", 3, iis.skip(3));
-
- // Test to see if the number of bytes skipped returned is true.
- assertEquals("Incorrect Byte Returned.", 7, iis.read());
-
- assertEquals("Incorrect Number Of Bytes Skipped.", 0, iis.skip(0));
- assertEquals("Incorrect Byte Returned.", 0, iis.read());
-
- // Test for skipping more bytes than available in the stream
- assertEquals("Incorrect Number Of Bytes Skipped.", 2, iis.skip(4));
- assertEquals("Incorrect Byte Returned.", -1, iis.read());
- iis.close();
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#skip(long)
- */
- public void test_skipJ2() throws IOException {
- int result = 0;
- int buffer[] = new int[100];
- byte orgBuffer[] = { 1, 3, 4, 7, 8 };
-
- // testing for negative input to skip
- InputStream infile = Support_Resources
- .getStream("hyts_constru_OD.txt"); // android-changed
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile,
- inflate, 10);
- long skip;
- try {
- skip = inflatIP.skip(Integer.MIN_VALUE);
- fail("Expected IllegalArgumentException when skip() is called with negative parameter");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- inflatIP.close();
-
- // testing for number of bytes greater than input.
- InputStream infile2 = Support_Resources
- .getStream("hyts_constru_OD.txt"); // android-changed
- InflaterInputStream inflatIP2 = new InflaterInputStream(infile2);
-
- // looked at how many bytes the skip skipped. It is
- // 5 and its supposed to be the entire input stream.
-
- skip = inflatIP2.skip(Integer.MAX_VALUE);
- // System.out.println(skip);
- assertEquals("method skip() returned wrong number of bytes skipped",
- 5, skip);
-
- // test for skipping of 2 bytes
- InputStream infile3 = Support_Resources
- .getStream("hyts_constru_OD.txt"); // android-changed
- InflaterInputStream inflatIP3 = new InflaterInputStream(infile3);
- skip = inflatIP3.skip(2);
- assertEquals("the number of bytes returned by skip did not correspond with its input parameters",
- 2, skip);
- int i = 0;
- result = 0;
- while ((result = inflatIP3.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP2.close();
-
- for (int j = 2; j < orgBuffer.length; j++) {
- assertTrue(
- "original compressed data did not equal decompressed data",
- buffer[j - 2] == orgBuffer[j]);
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#available()
- */
- public void test_available() throws IOException {
- InputStream is = Support_Resources.getStream("hyts_available.tst");
- InflaterInputStream iis = new InflaterInputStream(is);
-
- int available;
- for (int i = 0; i < 11; i++) {
- iis.read();
- available = iis.available();
- if (available == 0) {
- assertEquals("Expected no more bytes to read", -1, iis.read());
- } else {
- assertEquals("Bytes Available Should Return 1.", 1, available);
- }
- }
-
- iis.close();
- try {
- iis.available();
- fail("available after close should throw IOException.");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#close()
- */
- public void test_close() throws IOException {
- InflaterInputStream iin = new InflaterInputStream(
- new ByteArrayInputStream(new byte[0]));
- iin.close();
-
- // test for exception
- iin.close();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterOutputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterOutputStreamTest.java
deleted file mode 100644
index cf3e20e..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterOutputStreamTest.java
+++ /dev/null
@@ -1,392 +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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.zip.Deflater;
-import java.util.zip.Inflater;
-import java.util.zip.InflaterOutputStream;
-import java.util.zip.ZipException;
-
-import junit.framework.TestCase;
-
-public class InflaterOutputStreamTest extends TestCase {
-
- private ByteArrayOutputStream os = new ByteArrayOutputStream();
-
- private byte[] compressedBytes = new byte[100];
-
- private String testString = "Hello world";
-
- /**
- * @tests java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream)
- */
- public void test_ConstructorLjava_io_OutputStream() throws IOException {
- new InflaterOutputStream(os);
-
- try {
- new InflaterOutputStream(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream,Inflater)
- */
- public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Inflater() {
- new InflaterOutputStream(os, new Inflater());
-
- try {
- new InflaterOutputStream(null, new Inflater());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- new InflaterOutputStream(os, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#InflaterOutputStream(java.io.OutputStream,Inflater,int)
- */
- public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_InflaterI() {
- new InflaterOutputStream(os, new Inflater(), 20);
-
- try {
- new InflaterOutputStream(null, null, 10);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- new InflaterOutputStream(null, new Inflater(), -1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- new InflaterOutputStream(os, null, -1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- new InflaterOutputStream(null, null, -1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- new InflaterOutputStream(os, new Inflater(), 0);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- new InflaterOutputStream(os, new Inflater(), -10000);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#close()
- */
- public void test_close() throws IOException {
- InflaterOutputStream ios = new InflaterOutputStream(os);
- ios.close();
- // multiple close
- ios.close();
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#flush()
- */
- public void test_flush() throws IOException {
- InflaterOutputStream ios = new InflaterOutputStream(os);
- ios.close();
- try {
- ios.flush();
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- ios = new InflaterOutputStream(os);
- ios.flush();
- ios.flush();
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#finish()
- */
- public void test_finish() throws IOException {
- InflaterOutputStream ios = new InflaterOutputStream(os);
- ios.close();
- try {
- ios.finish();
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- ios = new InflaterOutputStream(os);
- ios.finish();
- ios.finish();
- ios.flush();
- ios.flush();
- ios.finish();
-
- byte[] bytes1 = {10,20,30,40,50};
- Deflater defaultDeflater = new Deflater(Deflater.BEST_SPEED);
- defaultDeflater.setInput(bytes1);
- defaultDeflater.finish();
- int length1 = defaultDeflater.deflate(compressedBytes);
-
- byte[] bytes2 = {100,90,80,70,60};
- Deflater bestDeflater = new Deflater(Deflater.BEST_COMPRESSION );
- bestDeflater.setInput(bytes2);
- bestDeflater.finish();
- int length2 = bestDeflater.deflate(compressedBytes,length1,compressedBytes.length-length1);
-
- ios = new InflaterOutputStream(os);
- for (int i = 0; i < length1; i++) {
- ios.write(compressedBytes[i]);
- }
- ios.finish();
- ios.close();
-
- byte[] result = os.toByteArray();
- for(int i =0;i<bytes1.length; i++){
- assertEquals(bytes1[i],result[i]);
- }
-
- ios = new InflaterOutputStream(os);
- for (int i = length1; i < length2*2; i++) {
- ios.write(compressedBytes[i]);
- }
- ios.finish();
- ios.close();
-
- result = os.toByteArray();
- for(int i =0;i<bytes2.length; i++){
- assertEquals(bytes2[i],result[bytes1.length+i]);
- }
-
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#write(int)
- */
- public void test_write_I() throws IOException {
- int length = compressToBytes(testString);
-
- // uncompress the data stored in the compressedBytes
- InflaterOutputStream ios = new InflaterOutputStream(os);
- for (int i = 0; i < length; i++) {
- ios.write(compressedBytes[i]);
- }
-
- String result = new String(os.toByteArray());
- assertEquals(testString, result);
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#write(int)
- */
- public void test_write_I_Illegal() throws IOException {
-
- // write after close
- InflaterOutputStream ios = new InflaterOutputStream(os);
- ios.close();
- try {
- ios.write(-1);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#write(byte[],int,int)
- */
- public void test_write_$BII() throws IOException {
- int length = compressToBytes(testString);
-
- // uncompress the data stored in the compressedBytes
- InflaterOutputStream ios = new InflaterOutputStream(os);
- ios.write(compressedBytes, 0, length);
-
- String result = new String(os.toByteArray());
- assertEquals(testString, result);
- }
-
- /**
- * @tests java.util.zip.InflaterOutputStream#write(byte[],int,int)
- */
- public void test_write_$BII_Illegal() throws IOException {
- // write error compression (ZIP) format
- InflaterOutputStream ios = new InflaterOutputStream(os);
- byte[] bytes = { 0, 1, 2, 3 };
- try {
- ios.write(bytes, 0, 4);
- fail("Should throw ZipException");
- } catch (ZipException e) {
- // expected
- }
- try {
- ios.flush();
- fail("Should throw ZipException");
- } catch (ZipException e) {
- // expected
- }
-
- // write after close
- ios = new InflaterOutputStream(os);
- ios.close();
- try {
- ios.write(bytes, 0, 4);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- ios.write(bytes, -1, 4);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- ios.write(bytes, -1, -4);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- ios.write(bytes, 0, 400);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- try {
- ios.write(null, -1, 4);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- ios = new InflaterOutputStream(os);
- try {
- ios.write(null, 0, 4);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- ios.write(null, -1, 4);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- ios.write(null, 0, -4);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- ios.write(null, 0, 1000);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- ios.write(bytes, -1, 4);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ios.write(bytes, 0, -4);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ios.write(bytes, 0, 100);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ios.write(bytes, -100, 100);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- ios = new InflaterOutputStream(os);
- ios.finish();
-
- try {
- ios.write(bytes, -1,-100);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ios.write(null, -1,-100);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- ios = new InflaterOutputStream(os);
- ios.flush();
- try {
- ios.write(bytes, 0, 4);
- fail("Should throw ZipException");
- } catch (ZipException e) {
- // expected
- }
- }
-
- // Compress the test string into compressedBytes
- private int compressToBytes(String string) {
- byte[] input = string.getBytes();
- Deflater deflater = new Deflater();
- deflater.setInput(input);
- deflater.finish();
- return deflater.deflate(compressedBytes);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java
deleted file mode 100644
index 9ec9213..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java
+++ /dev/null
@@ -1,1031 +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 java.io.BufferedInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.zip.Adler32;
-import java.io.UnsupportedEncodingException;
-import java.util.zip.DataFormatException;
-import java.util.zip.Deflater;
-import java.util.zip.Inflater;
-import java.util.zip.ZipException;
-
-import tests.support.resource.Support_Resources;
-
-public class InflaterTest extends junit.framework.TestCase {
- byte outPutBuff1[] = new byte[500];
-
- byte outPutDiction[] = new byte[500];
-
- /**
- * @tests java.util.zip.Inflater#end()
- */
- public void test_end() {
- // test method of java.util.zip.inflater.end()
- byte byteArray[] = { 5, 2, 3, 7, 8 };
-
- int r = 0;
- Inflater inflate = new Inflater();
- inflate.setInput(byteArray);
- inflate.end();
- try {
- inflate.reset();
- inflate.setInput(byteArray);
- } catch (NullPointerException e) {
- r = 1;
- }
- assertEquals("inflate can still be used after end is called", 1, r);
-
- Inflater i = new Inflater();
- i.end();
- // check for exception
- i.end();
- }
-
- /**
- * @tests java.util.zip.Inflater#finished()
- */
- public void test_finished() {
- // test method of java.util.zip.inflater.finished()
- byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
- Inflater inflate = new Inflater(false);
- byte outPutInf[] = new byte[500];
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
-
- inflate.inflate(outPutInf);
- }
- assertTrue(
- "the method finished() returned false when no more data needs to be decompressed",
- inflate.finished());
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - finished()",
- 0, outPutInf[byteArray.length]);
- }
-
- /**
- * @tests java.util.zip.Inflater#getAdler()
- */
- public void test_getAdler() {
- // test method of java.util.zip.inflater.getAdler()
- byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
-
- Inflater inflateDiction = new Inflater();
- inflateDiction.setInput(outPutDiction);
- if (inflateDiction.needsDictionary() == true) {
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(dictionaryArray);
- long checkSumR = adl.getValue();
- assertTrue(
- "the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
- checkSumR == inflateDiction.getAdler());
- }
- }
-
- /**
- * @tests java.util.zip.Inflater#getRemaining()
- */
- public void test_getRemaining() {
- // test method of java.util.zip.inflater.getRemaining()
- byte byteArray[] = { 1, 3, 5, 6, 7 };
- Inflater inflate = new Inflater();
- assertEquals("upon creating an instance of inflate, getRemaining returned a non zero value",
- 0, inflate.getRemaining());
- inflate.setInput(byteArray);
- assertTrue(
- "getRemaining returned zero when there is input in the input buffer",
- inflate.getRemaining() != 0);
- }
-
- /**
- * @tests java.util.zip.Inflater#getTotalIn()
- */
- public void test_getTotalIn() {
- // test method of java.util.zip.inflater.getTotalIn()
- // creating the decompressed data
- byte outPutBuf[] = new byte[500];
- byte byteArray[] = { 1, 3, 4, 7, 8 };
- byte outPutInf[] = new byte[500];
- int x = 0;
- Deflater deflate = new Deflater(1);
- deflate.setInput(byteArray);
- while (!(deflate.needsInput())) {
- x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- deflate.finish();
- while (!(deflate.finished())) {
- x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
-
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuf);
- }
-
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - getTotalIn");
- }
- // System.out.print(deflate.getTotalOut() + " " + inflate.getTotalIn());
- assertTrue(
- "the total byte in outPutBuf did not equal the byte returned in getTotalIn",
- inflate.getTotalIn() == deflate.getTotalOut());
-
- Inflater inflate2 = new Inflater();
- int offSet = 0;// seems only can start as 0
- int length = 4;
- try {
- // seems no while loops allowed
- if (inflate2.needsInput()) {
- inflate2.setInput(outPutBuff1, offSet, length);
- }
-
- inflate2.inflate(outPutInf);
-
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - getTotalIn");
- }
- // System.out.print(inflate2.getTotalIn() + " " + length);
- assertTrue(
- "total byte dictated by length did not equal byte returned in getTotalIn",
- inflate2.getTotalIn() == length);
- }
-
- /**
- * @tests java.util.zip.Inflater#getTotalOut()
- */
- public void test_getTotalOut() {
- // test method of java.util.zip.inflater.Inflater()
- // creating the decompressed data
- byte outPutBuf[] = new byte[500];
- byte byteArray[] = { 1, 3, 4, 7, 8 };
- int y = 0;
- int x = 0;
- Deflater deflate = new Deflater(1);
- deflate.setInput(byteArray);
- while (!(deflate.needsInput())) {
- x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- deflate.finish();
- while (!(deflate.finished())) {
- x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
-
- Inflater inflate = new Inflater();
- byte outPutInf[] = new byte[500];
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuf);
- }
-
- y += inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - getTotalIn");
- }
-
- assertTrue(
- "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
- y == inflate.getTotalOut());
- assertTrue(
- "the total number of bytes to be compressed does not equal the total bytes decompressed",
- inflate.getTotalOut() == deflate.getTotalIn());
-
- // testing inflate(byte,int,int)
- inflate.reset();
- y = 0;
- int offSet = 0;// seems only can start as 0
- int length = 4;
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuf);
- }
-
- y += inflate.inflate(outPutInf, offSet, length);
- }
- } catch (DataFormatException e) {
- System.out
- .println("Input to inflate is invalid or corrupted - getTotalIn");
- }
- assertTrue(
- "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
- y == inflate.getTotalOut());
- assertTrue(
- "the total number of bytes to be compressed does not equal the total bytes decompressed",
- inflate.getTotalOut() == deflate.getTotalIn());
- }
-
- /**
- * @tests java.util.zip.Inflater#inflate(byte[])
- */
- public void test_inflate$B() {
- // test method of java.util.zip.inflater.inflate(byte)
-
- byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
- byte outPutInf[] = new byte[500];
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - inflateB",
- 0, outPutInf[byteArray.length]);
- // testing for an empty input array
- byte outPutBuf[] = new byte[500];
- byte emptyArray[] = new byte[11];
- int x = 0;
- Deflater defEmpty = new Deflater(3);
- defEmpty.setInput(emptyArray);
- while (!(defEmpty.needsInput())) {
- x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- defEmpty.finish();
- while (!(defEmpty.finished())) {
- x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- assertTrue(
- "the total number of byte from deflate did not equal getTotalOut - inflate(byte)",
- x == defEmpty.getTotalOut());
- assertTrue(
- "the number of input byte from the array did not correspond with getTotalIn - inflate(byte)",
- defEmpty.getTotalIn() == emptyArray.length);
- Inflater infEmpty = new Inflater();
- try {
- while (!(infEmpty.finished())) {
- if (infEmpty.needsInput()) {
- infEmpty.setInput(outPutBuf);
- }
- infEmpty.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < emptyArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- emptyArray[i] == outPutInf[i]);
- assertEquals("Final decompressed data does not equal zero",
- 0, outPutInf[i]);
- }
- assertEquals("Final decompressed data contains more element than original data",
- 0, outPutInf[emptyArray.length]);
- }
-
- public void test_inflate$B1() {
- byte codedData[] = {
- 120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87,
- 72, -50, -49, 43, 73, -52, -52, 43, 86, 72, 2, 10, 34, 99,
- -123, -60, -68, 20, -80, 32, 0, -101, -69, 17, 84};
- String codedString = "blah string contains blahblahblahblah and blah";
-
- Inflater infl1 = new Inflater();
- Inflater infl2 = new Inflater();
-
- byte[] result = new byte[100];
- int decLen = 0;
-
- infl1.setInput(codedData, 0, codedData.length);
- try {
- decLen = infl1.inflate(result);
- } catch (DataFormatException e) {
- fail("Unexpected DataFormatException");
- }
-
- infl1.end();
- assertEquals(codedString, new String(result, 0, decLen));
- codedData[5] = 0;
-
- infl2.setInput(codedData, 0, codedData.length);
- try {
- decLen = infl2.inflate(result);
- fail("Expected DataFormatException");
- } catch (DataFormatException e) {
- // expected
- }
-
- infl2.end();
- }
-
- /**
- * @tests java.util.zip.Inflater#inflate(byte[], int, int)
- */
- public void test_inflate$BII() {
- // test method of java.util.zip.inflater.inflate(byte,int,int)
-
- byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
- byte outPutInf[] = new byte[100];
- int y = 0;
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- y += inflate.inflate(outPutInf, y, outPutInf.length - y);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - inflateB",
- 0, outPutInf[byteArray.length]);
-
- // test boundary checks
- inflate.reset();
- int r = 0;
- int offSet = 0;
- int lengthError = 101;
- try {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- inflate.inflate(outPutInf, offSet, lengthError);
-
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("out of bounds error did not get caught", 1, r);
- }
-
- public void test_inflate$BII1() {
- byte codedData[] = {
- 120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87,
- 72, -50, -49, 43, 73, -52, -52, 43, 86, 72, 2, 10, 34, 99,
- -123, -60, -68, 20, -80, 32, 0, -101, -69, 17, 84};
- String codedString = "blah string";
-
- Inflater infl1 = new Inflater();
- Inflater infl2 = new Inflater();
-
- byte[] result = new byte[100];
- int decLen = 0;
-
- infl1.setInput(codedData, 0, codedData.length);
- try {
- decLen = infl1.inflate(result, 10, 11);
- } catch (DataFormatException e) {
- fail("Unexpected DataFormatException");
- }
-
- infl1.end();
- assertEquals(codedString, new String(result, 10, decLen));
- codedData[5] = 0;
-
- infl2.setInput(codedData, 0, codedData.length);
- try {
- decLen = infl2.inflate(result, 10, 11);
- fail("Expected DataFormatException");
- } catch (DataFormatException e) {
- // expected
- }
-
- infl2.end();
- }
-
- /**
- * @tests java.util.zip.Inflater#Inflater()
- */
- public void test_Constructor() {
- // test method of java.util.zip.inflater.Inflater()
- Inflater inflate = new Inflater();
- assertNotNull("failed to create the instance of inflater",
- inflate);
- }
-
- /**
- * @tests java.util.zip.Inflater#Inflater(boolean)
- */
- public void test_ConstructorZ() {
- // test method of java.util.zip.inflater.Inflater(boolean)
- // note does not throw exception if deflater has a header, but inflater
- // doesn't or vice versa.
- byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
- Inflater inflate = new Inflater(true);
- assertNotNull("failed to create the instance of inflater", inflate);
- byte outPutInf[] = new byte[500];
- int r = 0;
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
-
- inflate.inflate(outPutInf);
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals("the output array from inflate should contain 0 because the header of inflate and deflate did not match, but this failed",
- 0, outPutBuff1[i]);
- }
- } catch (DataFormatException e) {
- r = 1;
- }
- assertEquals("Error: exception should be thrown because of header inconsistency",
- 1, r);
-
- }
-
- /**
- * @tests java.util.zip.Inflater#needsDictionary()
- */
- public void test_needsDictionary() {
- // test method of java.util.zip.inflater.needsDictionary()
- // note: this flag is set after inflate is called
- byte outPutInf[] = new byte[500];
-
- // testing with dictionary set.
- Inflater inflateDiction = new Inflater();
- if (inflateDiction.needsInput()) {
- inflateDiction.setInput(outPutDiction);
- }
- try {
- assertEquals("should return 0 because needs dictionary",
- 0, inflateDiction.inflate(outPutInf));
- } catch (DataFormatException e) {
- fail("Should not cause exception");
- }
- assertTrue(
- "method needsDictionary returned false when dictionary was used in deflater",
- inflateDiction.needsDictionary());
-
- // testing without dictionary
- Inflater inflate = new Inflater();
- try {
- inflate.setInput(outPutBuff1);
- inflate.inflate(outPutInf);
- assertFalse(
- "method needsDictionary returned true when dictionary was not used in deflater",
- inflate.needsDictionary());
- } catch (DataFormatException e) {
- fail(
- "Input to inflate is invalid or corrupted - needsDictionary");
- }
-
- // Regression test for HARMONY-86
- Inflater inf = new Inflater();
- assertFalse(inf.needsDictionary());
- assertEquals(0,inf.getTotalIn());
- assertEquals(0,inf.getTotalOut());
- assertEquals(0,inf.getBytesRead());
- assertEquals(0,inf.getBytesWritten());
- }
-
- /**
- * @tests java.util.zip.Inflater#needsInput()
- */
- public void test_needsInput() {
- // test method of java.util.zip.inflater.needsInput()
- Inflater inflate = new Inflater();
- assertTrue(
- "needsInput give the wrong boolean value as a result of no input buffer",
- inflate.needsInput());
-
- byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
- inflate.setInput(byteArray);
- assertFalse(
- "methodNeedsInput returned true when the input buffer is full",
- inflate.needsInput());
-
- inflate.reset();
- byte byteArrayEmpty[] = new byte[0];
- inflate.setInput(byteArrayEmpty);
- assertTrue(
- "needsInput give wrong boolean value as a result of an empty input buffer",
- inflate.needsInput());
- }
-
- /**
- * @tests java.util.zip.Inflater#reset()
- */
- public void test_reset() {
- // test method of java.util.zip.inflater.reset()
- byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
- byte outPutInf[] = new byte[100];
- int y = 0;
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- y += inflate.inflate(outPutInf, y, outPutInf.length - y);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - reset",
- 0, outPutInf[byteArray.length]);
-
- // testing that resetting the inflater will also return the correct
- // decompressed data
-
- inflate.reset();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - reset",
- 0, outPutInf[byteArray.length]);
-
- }
-
- /**
- * @tests java.util.zip.Inflater#setDictionary(byte[])
- */
- public void test_setDictionary$B() {
- //FIXME This test doesn't pass in Harmony classlib or Sun 5.0_7 RI
- /*
- // test method of java.util.zip.inflater.setDictionary(byte)
- byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
- byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
- 'w', 'r' };
-
- byte outPutInf[] = new byte[100];
-
- // trying to inflate without setting a dictionary
-
- Inflater inflateWO = new Inflater();
- byte outPutInf2[] = new byte[100];
- int r = 0;
- try {
- while (!(inflateWO.finished())) {
- if (inflateWO.needsInput()) {
- inflateWO.setInput(outPutDiction);
- }
- inflateWO.inflate(outPutInf2);
- }
- } catch (DataFormatException e) {
- r = 1;
- }
- assertEquals("invalid input to be decompressed due to dictionary not set",
- 1, r);
- // now setting the dictionary in inflater
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutDiction);
- }
- if (inflate.needsDictionary()) {
- inflate.setDictionary(dictionaryArray);
- }
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals("final decompressed data contained more bytes than original - deflateB",
- 0, outPutInf[byteArray.length]);
- */
- }
-
- /**
- * @tests java.util.zip.Inflater#setInput(byte[])
- */
- public void test_setInput$B() {
- // test method of java.util.zip.inflater.setInput(byte)
- byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
- Inflater inflate = new Inflater();
- inflate.setInput(byteArray);
- assertTrue("setInputB did not deliver any byte to the input buffer",
- inflate.getRemaining() != 0);
- }
-
- /**
- * @tests java.util.zip.Inflater#setInput(byte[], int, int)
- */
- public void test_setInput$BII() {
- // test method of java.util.zip.inflater.setInput(byte,int,int)
- byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
- int offSet = 6;
- int length = 6;
- Inflater inflate = new Inflater();
- inflate.setInput(byteArray, offSet, length);
- assertTrue(
- "setInputBII did not deliver the right number of bytes to the input buffer",
- inflate.getRemaining() == length);
- // boundary check
- inflate.reset();
- int r = 0;
- try {
- inflate.setInput(byteArray, 100, 100);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("boundary check is not present for setInput", 1, r);
- }
-
- @Override
- protected void setUp() {
- try {
- java.io.InputStream infile = Support_Resources
- .getStream("hyts_compressD.txt");
- BufferedInputStream inflatIP = new BufferedInputStream(infile);
- inflatIP.read(outPutBuff1, 0, outPutBuff1.length);
- inflatIP.close();
-
- java.io.InputStream infile2 = Support_Resources
- .getStream("hyts_compDiction.txt");
- BufferedInputStream inflatIP2 = new BufferedInputStream(infile2);
- inflatIP2.read(outPutDiction, 0, outPutDiction.length);
- inflatIP2.close();
-
- } catch (FileNotFoundException e) {
- fail(
- "input file to test InflaterInputStream constructor is not found");
- } catch (ZipException e) {
- fail(
- "read() threw an zip exception while testing constructor");
- } catch (IOException e) {
- fail("read() threw an exception while testing constructor");
- }
- }
-
- @Override
- protected void tearDown() {
- }
-
- /**
- * @tests java.util.zip.Deflater#getBytesRead()
- */
- public void test_getBytesRead() throws DataFormatException,
- UnsupportedEncodingException {
- // Regression test for HARMONY-158
- Deflater def = new Deflater();
- Inflater inf = new Inflater();
- assertEquals(0, def.getTotalIn());
- assertEquals(0, def.getTotalOut());
- assertEquals(0, def.getBytesRead());
- // Encode a String into bytes
- String inputString = "blahblahblah??";
- byte[] input = inputString.getBytes("UTF-8");
-
- // Compress the bytes
- byte[] output = new byte[100];
- def.setInput(input);
- def.finish();
- def.deflate(output);
- inf.setInput(output);
- int compressedDataLength =inf.inflate(input);
- assertEquals(16, inf.getTotalIn());
- assertEquals(compressedDataLength, inf.getTotalOut());
- assertEquals(16, inf.getBytesRead());
- }
-
- /**
- * @tests java.util.zip.Deflater#getBytesRead()
- */
- public void test_getBytesWritten() throws DataFormatException, UnsupportedEncodingException {
- // Regression test for HARMONY-158
- Deflater def = new Deflater();
- Inflater inf = new Inflater();
- assertEquals(0, def.getTotalIn());
- assertEquals(0, def.getTotalOut());
- assertEquals(0, def.getBytesWritten());
- // Encode a String into bytes
- String inputString = "blahblahblah??";
- byte[] input = inputString.getBytes("UTF-8");
-
- // Compress the bytes
- byte[] output = new byte[100];
- def.setInput(input);
- def.finish();
- def.deflate(output);
- inf.setInput(output);
- int compressedDataLength =inf.inflate(input);
- assertEquals(16, inf.getTotalIn());
- assertEquals(compressedDataLength, inf.getTotalOut());
- assertEquals(14, inf.getBytesWritten());
- }
-
- /**
- * @tests java.util.zip.Deflater#inflate(byte[], int, int)
- */
- public void testInflate() throws Exception {
- // Regression for HARMONY-81
- Inflater inf = new Inflater();
- int res = inf.inflate(new byte[0], 0, 0);
-
- assertEquals(0, res);
-
- // Regression for HARMONY-2508
- Inflater inflater = new Inflater();
- byte[] b = new byte[1024];
- assertEquals(0, inflater.inflate(b));
- inflater.end();
-
- // Regression for HARMONY-2510
- inflater = new Inflater();
- inflater.setInput(new byte[] { -1 });
- try {
- inflater.inflate(b);
-
- // The RI detects malformed data on the malformed input { -1 }. Both
- // this implementation and the native zlib API return "need input"
- // on that data. This is an error if the stream is exhausted, but
- // not one that results in an exception in the Inflater API.
- assertTrue(inflater.needsInput());
- } catch (DataFormatException e) {
- // expected
- }
-
- inflater = new Inflater();
- inflater.setInput(new byte[] { -1, -1, -1 });
- try {
- inflater.inflate(b);
- } catch (DataFormatException e) {
- // expected
- }
- }
-
- public void testSetDictionary$B() throws Exception {
- int i = 0;
- String inputString = "blah string contains blahblahblahblah and blah";
- String dictionary1 = "blah";
- String dictionary2 = "1234";
-
- byte[] outputNo = new byte[100];
- byte[] output1 = new byte[100];
- byte[] output2 = new byte[100];
- Deflater defDictNo = new Deflater(9);
- Deflater defDict1 = new Deflater(9);
- Deflater defDict2 = new Deflater(9);
-
- defDict1.setDictionary(dictionary1.getBytes());
- defDict2.setDictionary(dictionary2.getBytes());
-
- defDictNo.setInput(inputString.getBytes());
- defDict1.setInput(inputString.getBytes());
- defDict2.setInput(inputString.getBytes());
-
- defDictNo.finish();
- defDict1.finish();
- defDict2.finish();
-
- int dataLenNo = defDictNo.deflate(outputNo);
- int dataLen1 = defDict1.deflate(output1);
- int dataLen2 = defDict2.deflate(output2);
-
- boolean passNo1 = false;
- boolean passNo2 = false;
- boolean pass12 = false;
-
- for (i = 0; i < (dataLenNo < dataLen1 ? dataLenNo : dataLen1); i++) {
- if (outputNo[i] != output1[i]) {
- passNo1 = true;
- break;
- }
- }
- for (i = 0; i < (dataLenNo < dataLen1 ? dataLenNo : dataLen2); i++) {
- if (outputNo[i] != output2[i]) {
- passNo2 = true;
- break;
- }
- }
- for (i = 0; i < (dataLen1 < dataLen2 ? dataLen1 : dataLen2); i++) {
- if (output1[i] != output2[i]) {
- pass12 = true;
- break;
- }
- }
-
- assertTrue(
- "Compressed data the same for stream with dictionary and without it.",
- passNo1);
- assertTrue(
- "Compressed data the same for stream with dictionary and without it.",
- passNo2);
- assertTrue(
- "Compressed data the same for stream with different dictionaries.",
- pass12);
-
- Inflater inflNo = new Inflater();
- Inflater infl1 = new Inflater();
- Inflater infl2 = new Inflater();
-
- byte[] result = new byte[100];
- int decLen;
-
- inflNo.setInput(outputNo, 0, dataLenNo);
- decLen = inflNo.inflate(result);
-
- assertFalse(inflNo.needsDictionary());
- inflNo.end();
- assertEquals(inputString, new String(result, 0, decLen));
-
- infl1.setInput(output1, 0, dataLen1);
- decLen = infl1.inflate(result);
-
- assertTrue(infl1.needsDictionary());
- infl1.setDictionary(dictionary1.getBytes());
- decLen = infl1.inflate(result);
- infl1.end();
- assertEquals(inputString, new String(result, 0, decLen));
-
- infl2.setInput(output2, 0, dataLen2);
- decLen = infl2.inflate(result);
-
- assertTrue(infl2.needsDictionary());
- infl2.setDictionary(dictionary2.getBytes());
- decLen = infl2.inflate(result);
- infl2.end();
- assertEquals(inputString, new String(result, 0, decLen));
-
-
- inflNo = new Inflater();
- infl1 = new Inflater();
- inflNo.setInput(outputNo, 0, dataLenNo);
- try {
- infl1.setDictionary(dictionary1.getBytes());
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException ee) {
- // expected.
- }
- inflNo.end();
-
- infl1.setInput(output1, 0, dataLen1);
- decLen = infl1.inflate(result);
-
- assertTrue(infl1.needsDictionary());
- try {
- infl1.setDictionary(dictionary2.getBytes());
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException ee) {
- // expected.
- }
- infl1.end();
- }
-
- public void testSetDictionary$BII() throws Exception {
- int i = 0;
- String inputString = "blah string contains blahblahblahblah and blah";
- String dictionary1 = "blah";
- String dictionary2 = "blahblahblah";
-
- byte[] output1 = new byte[100];
- byte[] output2 = new byte[100];
- byte[] output3 = new byte[100];
-
- Deflater defDict1 = new Deflater(9);
- Deflater defDict2 = new Deflater(9);
- Deflater defDict3 = new Deflater(9);
-
- defDict1.setDictionary(dictionary1.getBytes());
- defDict2.setDictionary(dictionary2.getBytes());
- defDict3.setDictionary(dictionary2.getBytes(), 4, 4);
-
- defDict1.setInput(inputString.getBytes());
- defDict2.setInput(inputString.getBytes());
- defDict3.setInput(inputString.getBytes());
-
- defDict1.finish();
- defDict2.finish();
- defDict3.finish();
-
- int dataLen1 = defDict1.deflate(output1);
- int dataLen2 = defDict2.deflate(output2);
- int dataLen3 = defDict3.deflate(output3);
-
- boolean pass12 = false;
- boolean pass23 = false;
- boolean pass13 = true;
-
- for (i = 0; i < (dataLen1 < dataLen2 ? dataLen1 : dataLen2); i++) {
- if (output1[i] != output2[i]) {
- pass12 = true;
- break;
- }
- }
- for (i = 0; i < (dataLen2 < dataLen3 ? dataLen2 : dataLen3); i++) {
- if (output2[i] != output3[i]) {
- pass23 = true;
- break;
- }
- }
- for (i = 0; i < (dataLen1 < dataLen3 ? dataLen1 : dataLen3); i++) {
- if (output1[i] != output3[i]) {
- pass13 = false;
- break;
- }
- }
-
- assertTrue(
- "Compressed data the same for stream with different dictionaries.",
- pass12);
- assertTrue(
- "Compressed data the same for stream with different dictionaries.",
- pass23);
- assertTrue(
- "Compressed data the differs for stream with the same dictionaries.",
- pass13);
-
- Inflater infl1 = new Inflater();
- Inflater infl2 = new Inflater();
- Inflater infl3 = new Inflater();
-
- byte[] result = new byte[100];
- int decLen;
-
- infl1.setInput(output1, 0, dataLen1);
- decLen = infl1.inflate(result);
-
- assertTrue(infl1.needsDictionary());
- infl1.setDictionary(dictionary2.getBytes(), 4, 4);
- decLen = infl1.inflate(result);
- infl1.end();
- assertEquals(inputString, new String(result, 0, decLen));
-
- infl2.setInput(output2, 0, dataLen2);
- decLen = infl2.inflate(result);
-
- assertTrue(infl2.needsDictionary());
- try {
- infl2.setDictionary(dictionary1.getBytes());
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException ee) {
- // expected
- }
- infl2.end();
-
- infl3.setInput(output3, 0, dataLen3);
- decLen = infl3.inflate(result);
-
- assertTrue(infl3.needsDictionary());
- infl3.setDictionary(dictionary1.getBytes());
- decLen = infl3.inflate(result);
- infl3.end();
- assertEquals(inputString, new String(result, 0, decLen));
-
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java
deleted file mode 100644
index 9754134..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.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.zip;
-
-import java.util.TimeZone;
-import java.util.zip.ZipEntry;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import tests.support.resource.Support_Resources;
-
-public class ZipEntryTest 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();
- }
-
- // zip file hyts_ZipFile.zip must be included as a resource
- java.util.zip.ZipEntry zentry;
-
- java.util.zip.ZipFile zfile;
-
- private static final String platformId = System.getProperty(
- "com.ibm.oti.configuration", "JDK")
- + System.getProperty("java.vm.version");
-
- static final String tempFileName = platformId + "zfzezi.zip";
-
- long orgSize;
-
- long orgCompressedSize;
-
- long orgCrc;
-
- long orgTime;
-
- String orgComment;
-
- /**
- * @tests java.util.zip.ZipEntry#ZipEntry(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.zip.ZipEntry(java.lang.String)
- zentry = zfile.getEntry("File3.txt");
- assertNotNull("Failed to create ZipEntry", zentry);
- try {
- zentry = zfile.getEntry(null);
- fail("NullPointerException not thrown");
- } catch (NullPointerException e) {
- }
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < 65535; i++) {
- s.append('a');
- }
- try {
- zentry = new ZipEntry(s.toString());
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException During Test.");
- }
- try {
- s.append('a');
- zentry = new ZipEntry(s.toString());
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- String n = null;
- zentry = new ZipEntry(n);
- fail("NullPointerException not thrown");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getComment()
- */
- public void test_getComment() {
- // Test for method java.lang.String java.util.zip.ZipEntry.getComment()
- ZipEntry zipEntry = new ZipEntry("zippy.zip");
- assertNull("Incorrect Comment Returned.", zipEntry.getComment());
- zipEntry.setComment("This Is A Comment");
- assertEquals("Incorrect Comment Returned.",
- "This Is A Comment", zipEntry.getComment());
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getCompressedSize()
- */
- public void test_getCompressedSize() {
- // Test for method long java.util.zip.ZipEntry.getCompressedSize()
- assertTrue("Incorrect compressed size returned", zentry
- .getCompressedSize() == orgCompressedSize);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getCrc()
- */
- public void test_getCrc() {
- // Test for method long java.util.zip.ZipEntry.getCrc()
- assertTrue("Failed to get Crc", zentry.getCrc() == orgCrc);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getExtra()
- */
- public void test_getExtra() {
- // Test for method byte [] java.util.zip.ZipEntry.getExtra()
- assertNull("Incorrect extra information returned",
- zentry.getExtra());
- byte[] ba = { 'T', 'E', 'S', 'T' };
- zentry = new ZipEntry("test.tst");
- zentry.setExtra(ba);
- assertTrue("Incorrect Extra Information Returned.",
- zentry.getExtra() == ba);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getMethod()
- */
- public void test_getMethod() {
- // Test for method int java.util.zip.ZipEntry.getMethod()
- zentry = zfile.getEntry("File1.txt");
- assertTrue("Incorrect compression method returned",
- zentry.getMethod() == java.util.zip.ZipEntry.STORED);
- zentry = zfile.getEntry("File3.txt");
- assertTrue("Incorrect compression method returned",
- zentry.getMethod() == java.util.zip.ZipEntry.DEFLATED);
- zentry = new ZipEntry("test.tst");
- assertEquals("Incorrect Method Returned.", -1, zentry.getMethod());
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getName()
- */
- public void test_getName() {
- // Test for method java.lang.String java.util.zip.ZipEntry.getName()
- assertEquals("Incorrect name returned - Note return result somewhat ambiguous in spec",
- "File1.txt", zentry.getName());
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getSize()
- */
- public void test_getSize() {
- // Test for method long java.util.zip.ZipEntry.getSize()
- assertTrue("Incorrect size returned", zentry.getSize() == orgSize);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getTime()
- */
- public void test_getTime() {
- // Test for method long java.util.zip.ZipEntry.getTime()
- assertTrue("Failed to get time", zentry.getTime() == orgTime);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#isDirectory()
- */
- public void test_isDirectory() {
- // Test for method boolean java.util.zip.ZipEntry.isDirectory()
- assertTrue("Entry should not answer true to isDirectory", !zentry
- .isDirectory());
- zentry = new ZipEntry("Directory/");
- assertTrue("Entry should answer true to isDirectory", zentry
- .isDirectory());
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setComment(java.lang.String)
- */
- public void test_setCommentLjava_lang_String() {
- // Test for method void
- // java.util.zip.ZipEntry.setComment(java.lang.String)
- zentry = zfile.getEntry("File1.txt");
- zentry.setComment("Set comment using api");
- assertEquals("Comment not correctly set",
- "Set comment using api", zentry.getComment());
- String n = null;
- zentry.setComment(n);
- assertNull("Comment not correctly set", zentry.getComment());
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < 0xFFFF; i++) {
- s.append('a');
- }
- try {
- zentry.setComment(s.toString());
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException During Test.");
- }
- try {
- s.append('a');
- zentry.setComment(s.toString());
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setCompressedSize(long)
- */
- public void test_setCompressedSizeJ() {
- // Test for method void java.util.zip.ZipEntry.setCompressedSize(long)
- zentry.setCompressedSize(orgCompressedSize + 10);
- assertTrue("Set compressed size failed",
- zentry.getCompressedSize() == (orgCompressedSize + 10));
- zentry.setCompressedSize(0);
- assertEquals("Set compressed size failed",
- 0, zentry.getCompressedSize());
- zentry.setCompressedSize(-25);
- assertEquals("Set compressed size failed",
- -25, zentry.getCompressedSize());
- zentry.setCompressedSize(4294967296l);
- assertTrue("Set compressed size failed",
- zentry.getCompressedSize() == 4294967296l);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setCrc(long)
- */
- public void test_setCrcJ() {
- // Test for method void java.util.zip.ZipEntry.setCrc(long)
- zentry.setCrc(orgCrc + 100);
- assertTrue("Failed to set Crc", zentry.getCrc() == (orgCrc + 100));
- zentry.setCrc(0);
- assertEquals("Failed to set Crc", 0, zentry.getCrc());
- try {
- zentry.setCrc(-25);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- zentry.setCrc(4294967295l);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException during test");
- }
- try {
- zentry.setCrc(4294967296l);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setExtra(byte[])
- */
- public void test_setExtra$B() {
- // Test for method void java.util.zip.ZipEntry.setExtra(byte [])
- zentry = zfile.getEntry("File1.txt");
- zentry.setExtra("Test setting extra information".getBytes());
- assertEquals("Extra information not written properly", "Test setting extra information", new String(zentry
- .getExtra(), 0, zentry.getExtra().length)
- );
- zentry = new ZipEntry("test.tst");
- byte[] ba = new byte[0xFFFF];
- try {
- zentry.setExtra(ba);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException during test");
- }
- try {
- ba = new byte[0xFFFF + 1];
- zentry.setExtra(ba);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
-
- // One constructor
- ZipEntry zeInput = new ZipEntry("InputZIP");
- byte[] extraB = { 'a', 'b', 'd', 'e' };
- zeInput.setExtra(extraB);
- assertEquals(extraB, zeInput.getExtra());
- assertEquals(extraB[3], zeInput.getExtra()[3]);
- assertEquals(extraB.length, zeInput.getExtra().length);
-
- // test another constructor
- ZipEntry zeOutput = new ZipEntry(zeInput);
- assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]);
- assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length);
- assertEquals(extraB[3], zeOutput.getExtra()[3]);
- assertEquals(extraB.length, zeOutput.getExtra().length);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setMethod(int)
- */
- public void test_setMethodI() {
- // Test for method void java.util.zip.ZipEntry.setMethod(int)
- zentry = zfile.getEntry("File3.txt");
- zentry.setMethod(ZipEntry.STORED);
- assertTrue("Failed to set compression method",
- zentry.getMethod() == ZipEntry.STORED);
- zentry.setMethod(ZipEntry.DEFLATED);
- assertTrue("Failed to set compression method",
- zentry.getMethod() == ZipEntry.DEFLATED);
- try {
- int error = 1;
- zentry = new ZipEntry("test.tst");
- zentry.setMethod(error);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setSize(long)
- */
- public void test_setSizeJ() {
- // Test for method void java.util.zip.ZipEntry.setSize(long)
- zentry.setSize(orgSize + 10);
- assertTrue("Set size failed", zentry.getSize() == (orgSize + 10));
- zentry.setSize(0);
- assertEquals("Set size failed", 0, zentry.getSize());
- try {
- zentry.setSize(-25);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- zentry.setCrc(4294967295l);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException during test");
- }
- try {
- zentry.setCrc(4294967296l);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setTime(long)
- */
- public void test_setTimeJ() {
- // Test for method void java.util.zip.ZipEntry.setTime(long)
- zentry.setTime(orgTime + 10000);
- assertTrue("Test 1: Failed to set time: " + zentry.getTime(), zentry
- .getTime() == (orgTime + 10000));
- zentry.setTime(orgTime - 10000);
- assertTrue("Test 2: Failed to set time: " + zentry.getTime(), zentry
- .getTime() == (orgTime - 10000));
- TimeZone zone = TimeZone.getDefault();
- try {
- TimeZone.setDefault(TimeZone.getTimeZone("EST"));
- zentry.setTime(0);
- assertTrue("Test 3: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
- assertTrue("Test 3a: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315532800000L);
- zentry.setTime(0);
- TimeZone.setDefault(TimeZone.getTimeZone("EST"));
- assertTrue("Test 3b: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
-
- zentry.setTime(-25);
- assertTrue("Test 4: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
- zentry.setTime(4354837200000L);
- assertTrue("Test 5: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
- } finally {
- TimeZone.setDefault(zone);
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#toString()
- */
- public void test_toString() {
- // Test for method java.lang.String java.util.zip.ZipEntry.toString()
- assertTrue("Returned incorrect entry name", zentry.toString().indexOf(
- "File1.txt") >= 0);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#ZipEntry(java.util.zip.ZipEntry)
- */
- public void test_ConstructorLjava_util_zip_ZipEntry() {
- // Test for method java.util.zip.ZipEntry(util.zip.ZipEntry)
- zentry.setSize(2);
- zentry.setCompressedSize(4);
- zentry.setComment("Testing");
- ZipEntry zentry2 = new ZipEntry(zentry);
- assertEquals("ZipEntry Created With Incorrect Size.",
- 2, zentry2.getSize());
- assertEquals("ZipEntry Created With Incorrect Compressed Size.", 4, zentry2
- .getCompressedSize());
- assertEquals("ZipEntry Created With Incorrect Comment.", "Testing", zentry2
- .getComment());
- assertTrue("ZipEntry Created With Incorrect Crc.",
- zentry2.getCrc() == orgCrc);
- assertTrue("ZipEntry Created With Incorrect Time.",
- zentry2.getTime() == orgTime);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#clone()
- */
- public void test_clone() {
- // Test for method java.util.zip.ZipEntry.clone()
- Object obj = zentry.clone();
- assertTrue("toString()", obj.toString().equals(zentry.toString()));
- assertTrue("hashCode()", obj.hashCode() == zentry.hashCode());
-
- // One constructor
- ZipEntry zeInput = new ZipEntry("InputZIP");
- byte[] extraB = { 'a', 'b', 'd', 'e' };
- zeInput.setExtra(extraB);
- assertEquals(extraB, zeInput.getExtra());
- assertEquals(extraB[3], zeInput.getExtra()[3]);
- assertEquals(extraB.length, zeInput.getExtra().length);
-
- // test Clone()
- ZipEntry zeOutput = (ZipEntry) zeInput.clone();
- assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]);
- assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length);
- assertEquals(extraB[3], zeOutput.getExtra()[3]);
- assertEquals(extraB.length, zeOutput.getExtra().length);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
-
- @Override
- protected void setUp() {
- java.io.File f = null;
- try {
- // Create a local copy of the file since some tests want to alter
- // information.
- f = new java.io.File(tempFileName);
- // Create absolute filename as ZipFile does not resolve using
- // user.dir
- f = new java.io.File(f.getAbsolutePath());
- f.delete();
- java.io.InputStream is = Support_Resources
- .getStream("hyts_ZipFile.zip");
- java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
- byte[] rbuf = getAllBytesFromStream(is);
- fos.write(rbuf, 0, rbuf.length);
- is.close();
- fos.close();
- zfile = new java.util.zip.ZipFile(f);
- zentry = zfile.getEntry("File1.txt");
- orgSize = zentry.getSize();
- orgCompressedSize = zentry.getCompressedSize();
- orgCrc = zentry.getCrc();
- orgTime = zentry.getTime();
- orgComment = zentry.getComment();
- } catch (Exception e) {
- System.out.println("Exception during ZipFile setup <"
- + f.getAbsolutePath() + ">: ");
- 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) {
- zfile.close();
- }
- java.io.File f = new java.io.File(tempFileName);
- f.delete();
- } catch (java.io.IOException e) {
- System.out.println("Exception during tearDown");
- }
- }
-
-}
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/archive/tests/java/util/zip/ZipOutputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java
deleted file mode 100644
index 58cfe1e..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java
+++ /dev/null
@@ -1,290 +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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.zip.CRC32;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-public class ZipOutputStreamTest extends junit.framework.TestCase {
-
- ZipOutputStream zos;
-
- ByteArrayOutputStream bos;
-
- ZipInputStream zis;
-
- static final String data = "HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld";
-
- /**
- * @tests java.util.zip.ZipOutputStream#close()
- */
- public void test_close() throws Exception {
- try {
- zos.close();
- fail("Close on empty stream failed to throw exception");
- } catch (ZipException e) {
- // expected
- }
-
- zos = new ZipOutputStream(bos);
- zos.putNextEntry(new ZipEntry("XX"));
- zos.closeEntry();
- zos.close();
-
- // Regression for HARMONY-97
- ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream());
- zos.putNextEntry(new ZipEntry("myFile"));
- zos.close();
- zos.close(); // Should be a no-op
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#closeEntry()
- */
- public void test_closeEntry() throws IOException {
- ZipEntry ze = new ZipEntry("testEntry");
- ze.setTime(System.currentTimeMillis());
- zos.putNextEntry(ze);
- zos.write("Hello World".getBytes("UTF-8"));
- zos.closeEntry();
- assertTrue("closeEntry failed to update required fields",
- ze.getSize() == 11 && ze.getCompressedSize() == 13);
-
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#finish()
- */
- public void test_finish() throws Exception {
- ZipEntry ze = new ZipEntry("test");
- zos.putNextEntry(ze);
- zos.write("Hello World".getBytes());
- zos.finish();
- assertEquals("Finish failed to closeCurrentEntry", 11, ze.getSize());
-
- ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream());
- zos.putNextEntry(new ZipEntry("myFile"));
- zos.finish();
- zos.close();
- try {
- zos.finish();
- fail("Assert 0: Expected IOException");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#putNextEntry(java.util.zip.ZipEntry)
- */
- public void test_putNextEntryLjava_util_zip_ZipEntry() throws IOException {
- ZipEntry ze = new ZipEntry("testEntry");
- ze.setTime(System.currentTimeMillis());
- zos.putNextEntry(ze);
- zos.write("Hello World".getBytes());
- zos.closeEntry();
- zos.close();
- zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()));
- ZipEntry ze2 = zis.getNextEntry();
- zis.closeEntry();
- assertTrue("Failed to write correct entry", ze.getName().equals(
- ze2.getName())
- && ze.getCrc() == ze2.getCrc());
- try {
- zos.putNextEntry(ze);
- fail("Entry with incorrect setting failed to throw exception");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#setComment(java.lang.String)
- */
- public void test_setCommentLjava_lang_String() {
- // There is no way to get the comment back, so no way to determine if
- // the comment is set correct
- zos.setComment("test setComment");
-
- try {
- zos.setComment(new String(new byte[0xFFFF + 1]));
- fail("Comment over 0xFFFF in length should throw exception");
- } catch (IllegalArgumentException e) {
- // Passed
- }
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#setLevel(int)
- */
- public void test_setLevelI() throws IOException {
- ZipEntry ze = new ZipEntry("test");
- zos.putNextEntry(ze);
- zos.write(data.getBytes());
- zos.closeEntry();
- long csize = ze.getCompressedSize();
- zos.setLevel(9); // Max Compression
- zos.putNextEntry(ze = new ZipEntry("test2"));
- zos.write(data.getBytes());
- zos.closeEntry();
- assertTrue("setLevel failed", csize <= ze.getCompressedSize());
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#setMethod(int)
- */
- public void test_setMethodI() throws IOException {
- ZipEntry ze = new ZipEntry("test");
- zos.setMethod(ZipOutputStream.STORED);
- CRC32 tempCrc = new CRC32();
- tempCrc.update(data.getBytes());
- ze.setCrc(tempCrc.getValue());
- ze.setSize(new String(data).length());
- zos.putNextEntry(ze);
- zos.write(data.getBytes());
- zos.closeEntry();
- long csize = ze.getCompressedSize();
- zos.setMethod(ZipOutputStream.DEFLATED);
- zos.putNextEntry(ze = new ZipEntry("test2"));
- zos.write(data.getBytes());
- zos.closeEntry();
- assertTrue("setLevel failed", csize >= ze.getCompressedSize());
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#write(byte[], int, int)
- */
- public void test_write$BII() throws IOException {
- ZipEntry ze = new ZipEntry("test");
- zos.putNextEntry(ze);
- zos.write(data.getBytes());
- zos.closeEntry();
- zos.close();
- zos = null;
- zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()));
- zis.getNextEntry();
- byte[] b = new byte[data.length()];
- int r = 0;
- int count = 0;
- while (count != b.length && (r = zis.read(b, count, b.length)) != -1) {
- count += r;
- }
- zis.closeEntry();
- assertTrue("Write failed to write correct bytes", new String(b)
- .equals(data));
-
- File f = File.createTempFile("testZip", "tst");
- f.deleteOnExit();
- FileOutputStream stream = new FileOutputStream(f);
- ZipOutputStream zip = new ZipOutputStream(stream);
- zip.setMethod(ZipEntry.STORED);
-
- try {
- zip.putNextEntry(new ZipEntry("Second"));
- fail("Not set an entry. Should have thrown ZipException.");
- } catch (ZipException e) {
- // expected -- We have not set an entry
- }
-
- try {
- // We try to write data without entry
- zip.write(new byte[2]);
- fail("Writing data without an entry. Should have thrown IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- // Try to write without an entry and with nonsense offset and
- // length
- zip.write(new byte[2], 0, 12);
- fail("Writing data without an entry. Should have thrown IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // Regression for HARMONY-4405
- try {
- zip.write(null, 0, -2);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // Close stream because ZIP is invalid
- stream.close();
- }
-
- /**
- * @tests java.util.zip.ZipOutputStream#write(byte[], int, int)
- */
- public void test_write$BII_2() throws IOException {
- // Regression for HARMONY-577
- File f1 = File.createTempFile("testZip1", "tst");
- f1.deleteOnExit();
- FileOutputStream stream1 = new FileOutputStream(f1);
- ZipOutputStream zip1 = new ZipOutputStream(stream1);
- zip1.putNextEntry(new ZipEntry("one"));
- zip1.setMethod(ZipOutputStream.STORED);
- zip1.setMethod(ZipEntry.STORED);
-
- zip1.write(new byte[2]);
-
- try {
- zip1.putNextEntry(new ZipEntry("Second"));
- fail("ZipException expected");
- } catch (ZipException e) {
- // expected - We have not set an entry
- }
-
- try {
- zip1.write(new byte[2]); // try to write data without entry
- fail("expected IOE there");
- } catch (IOException e2) {
- // expected
- }
-
- zip1.close();
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- zos = new ZipOutputStream(bos = new ByteArrayOutputStream());
- }
-
- @Override
- protected void tearDown() throws Exception {
- try {
- if (zos != null) {
- zos.close();
- }
- if (zis != null) {
- zis.close();
- }
- } catch (Exception e) {}
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherThread.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherThread.java
index 4895708..4dac176 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherThread.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/CipherThread.java
@@ -35,7 +35,7 @@
private String paddingMode = null;
private int fails = 0;
- abstract public void crypt() throws Exception;
+ public abstract void crypt() throws Exception;
CipherThread(String name, int[] keys, String[] modes, String[] paddings) {
algName = name;
diff --git a/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HeaderTest.java b/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpHeadersTest.java
similarity index 74%
rename from luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HeaderTest.java
rename to luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpHeadersTest.java
index 4f01c6f..ff9aa58 100644
--- a/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HeaderTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpHeadersTest.java
@@ -17,13 +17,12 @@
package org.apache.harmony.luni.internal.net.www.protocol.http;
import java.util.Arrays;
-import junit.framework.Test;
-import junit.framework.TestSuite;
+import junit.framework.TestCase;
-public class HeaderTest extends junit.framework.TestCase {
+public class HttpHeadersTest extends TestCase {
// http://code.google.com/p/android/issues/detail?id=6684
public void test_caseInsensitiveButCasePreserving() {
- Header h = new Header();
+ HttpHeaders h = new HttpHeaders();
h.add("Content-Type", "text/plain");
// Case-insensitive:
assertEquals("text/plain", h.get("Content-Type"));
@@ -31,25 +30,25 @@
assertEquals("text/plain", h.get("content-type"));
assertEquals("text/plain", h.get("CONTENT-TYPE"));
// ...but case-preserving:
- assertEquals("Content-Type", h.getFieldMap().keySet().toArray()[0]);
+ assertEquals("Content-Type", h.toMultimap().keySet().toArray()[0]);
// We differ from the RI in that the Map we return is also case-insensitive.
// Our behavior seems more consistent. (And code that works on the RI will work on Android.)
- assertEquals(Arrays.asList("text/plain"), h.getFieldMap().get("Content-Type"));
- assertEquals(Arrays.asList("text/plain"), h.getFieldMap().get("Content-type")); // RI fails this.
+ assertEquals(Arrays.asList("text/plain"), h.toMultimap().get("Content-Type"));
+ assertEquals(Arrays.asList("text/plain"), h.toMultimap().get("Content-type")); // RI fails this.
}
// The copy constructor used to be broken for headers with multiple values.
// http://code.google.com/p/android/issues/detail?id=6722
public void test_copyConstructor() {
- Header h1 = new Header();
+ HttpHeaders h1 = new HttpHeaders();
h1.add("key", "value1");
h1.add("key", "value2");
- Header h2 = new Header(h1.getFieldMap());
+ HttpHeaders h2 = HttpHeaders.fromMultimap(h1.toMultimap());
assertEquals(2, h2.length());
assertEquals("key", h2.getKey(0));
- assertEquals("value1", h2.get(0));
+ assertEquals("value1", h2.getValue(0));
assertEquals("key", h2.getKey(1));
- assertEquals("value2", h2.get(1));
+ assertEquals("value2", h2.getValue(1));
}
}
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 e5dbedc..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
@@ -23,109 +23,98 @@
* Tests org.apache.harmony.luni.platform.OSMemory.
*/
public class OSMemoryTest extends TestCase {
- public void testMemset() {
- int byteCount = 32;
- int ptr = OSMemory.malloc(byteCount);
- try {
- // Ensure our newly-allocated block isn't zeroed.
- OSMemory.setByte(ptr, (byte) 1);
- assertEquals((byte) 1, OSMemory.getByte(ptr));
- // Check that we can clear memory.
- OSMemory.memset(ptr, (byte) 0, byteCount);
- assertBytesEqual((byte) 0, ptr, byteCount);
- // Check that we can set an arbitrary value.
- OSMemory.memset(ptr, (byte) 1, byteCount);
- assertBytesEqual((byte) 1, ptr, byteCount);
- } finally {
- OSMemory.free(ptr);
- }
- }
-
- void assertBytesEqual(byte value, int ptr, int byteCount) {
- for (int i = 0; i < byteCount; ++i) {
- assertEquals(value, OSMemory.getByte(ptr + i));
- }
- }
-
public void testSetIntArray() {
int[] values = { 3, 7, 31, 127, 8191, 131071, 524287, 2147483647 };
int[] swappedValues = new int[values.length];
for (int i = 0; i < values.length; ++i) {
- swappedValues[i] = swapInt(values[i]);
+ swappedValues[i] = Integer.reverseBytes(values[i]);
}
- int scale = PlatformAddress.SIZEOF_JINT;
- int ptr = OSMemory.malloc(scale * values.length);
+ int scale = 4;
+ int ptr;
+
+ ptr = OSMemory.malloc(scale * values.length);
try {
- // Regular copy. Memset first so we start from a known state.
- OSMemory.memset(ptr, (byte) 0, scale * values.length);
- OSMemory.setIntArray(ptr, values, 0, values.length, false);
- assertIntsEqual(values, ptr);
+ // Regular copy.
+ OSMemory.pokeIntArray(ptr, values, 0, values.length, false);
+ assertIntsEqual(values, ptr, false);
+ assertIntsEqual(swappedValues, ptr, true);
+ } finally {
+ OSMemory.free(ptr);
+ }
+ ptr = OSMemory.malloc(scale * values.length);
+ try {
// Swapped copy.
- OSMemory.memset(ptr, (byte) 0, scale * values.length);
- OSMemory.setIntArray(ptr, values, 0, values.length, true);
- assertIntsEqual(swappedValues, ptr);
+ OSMemory.pokeIntArray(ptr, values, 0, values.length, true);
+ assertIntsEqual(values, ptr, true);
+ assertIntsEqual(swappedValues, ptr, false);
+ } finally {
+ OSMemory.free(ptr);
+ }
+ ptr = OSMemory.malloc(scale * values.length);
+ try {
// Swapped copies of slices (to ensure we test non-zero offsets).
- OSMemory.memset(ptr, (byte) 0, scale * values.length);
for (int i = 0; i < values.length; ++i) {
- OSMemory.setIntArray(ptr + i * scale, values, i, 1, true);
+ OSMemory.pokeIntArray(ptr + i * scale, values, i, 1, true);
}
- assertIntsEqual(swappedValues, ptr);
+ assertIntsEqual(values, ptr, true);
+ assertIntsEqual(swappedValues, ptr, false);
} finally {
OSMemory.free(ptr);
}
}
- private void assertIntsEqual(int[] expectedValues, int ptr) {
+ private void assertIntsEqual(int[] expectedValues, int ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
- assertEquals(expectedValues[i], OSMemory.getInt(ptr + PlatformAddress.SIZEOF_JINT * i));
+ assertEquals(expectedValues[i], OSMemory.peekInt(ptr + 4 * i, swap));
}
}
- private static int swapInt(int n) {
- return (((n >> 0) & 0xff) << 24) |
- (((n >> 8) & 0xff) << 16) |
- (((n >> 16) & 0xff) << 8) |
- (((n >> 24) & 0xff) << 0);
- }
-
public void testSetShortArray() {
short[] values = { 0x0001, 0x0020, 0x0300, 0x4000 };
short[] swappedValues = { 0x0100, 0x2000, 0x0003, 0x0040 };
- int scale = PlatformAddress.SIZEOF_JSHORT;
- int ptr = OSMemory.malloc(scale * values.length);
+ int scale = 2;
+ int ptr;
+
+ ptr = OSMemory.malloc(scale * values.length);
try {
// Regular copy. Memset first so we start from a known state.
- OSMemory.memset(ptr, (byte) 0, scale * values.length);
- OSMemory.setShortArray(ptr, values, 0, values.length, false);
- assertShortsEqual(values, ptr);
+ OSMemory.pokeShortArray(ptr, values, 0, values.length, false);
+ assertShortsEqual(values, ptr, false);
+ assertShortsEqual(swappedValues, ptr, true);
+ } finally {
+ OSMemory.free(ptr);
+ }
+ ptr = OSMemory.malloc(scale * values.length);
+ try {
// Swapped copy.
- OSMemory.memset(ptr, (byte) 0, scale * values.length);
- OSMemory.setShortArray(ptr, values, 0, values.length, true);
- assertShortsEqual(swappedValues, ptr);
+ OSMemory.pokeShortArray(ptr, values, 0, values.length, true);
+ assertShortsEqual(values, ptr, true);
+ assertShortsEqual(swappedValues, ptr, false);
+ } finally {
+ OSMemory.free(ptr);
+ }
+ ptr = OSMemory.malloc(scale * values.length);
+ try {
// Swapped copies of slices (to ensure we test non-zero offsets).
- OSMemory.memset(ptr, (byte) 0, scale * values.length);
for (int i = 0; i < values.length; ++i) {
- OSMemory.setShortArray(ptr + i * scale, values, i, 1, true);
+ OSMemory.pokeShortArray(ptr + i * scale, values, i, 1, true);
}
- assertShortsEqual(swappedValues, ptr);
+ assertShortsEqual(values, ptr, true);
+ assertShortsEqual(swappedValues, ptr, false);
} finally {
OSMemory.free(ptr);
}
}
- private void assertShortsEqual(short[] expectedValues, int ptr) {
+ private void assertShortsEqual(short[] expectedValues, int ptr, boolean swap) {
for (int i = 0; i < expectedValues.length; ++i) {
- assertEquals(expectedValues[i], OSMemory.getShort(ptr + PlatformAddress.SIZEOF_JSHORT * i));
+ assertEquals(expectedValues[i], OSMemory.peekShort(ptr + 2 * i, swap));
}
}
-
- private static short swapShort(short n) {
- return (short) ((((n >> 0) & 0xff) << 8) | (((n >> 8) & 0xff) << 0));
- }
}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
index 0f30aa7..88d476b 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
@@ -34,6 +34,7 @@
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -59,6 +60,16 @@
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManagerFactory;
+import junit.framework.TestCase;
/**
* Implementation independent test for HttpsURLConnection.
@@ -848,8 +859,10 @@
if (store != null) {
String ksFileName = "org/apache/harmony/luni/tests/key_store."
+ KeyStore.getDefaultType().toLowerCase();
- InputStream in = getClass().getClassLoader()
- .getResourceAsStream(ksFileName);
+ InputStream in = getClass().getClassLoader().getResourceAsStream(ksFileName);
+ if (in == null) {
+ throw new IllegalStateException("Couldn't find resource: " + ksFileName);
+ }
FileOutputStream out = new FileOutputStream(store);
BufferedInputStream bufIn = new BufferedInputStream(in, 8192);
while (bufIn.available() > 0) {
@@ -1003,16 +1016,28 @@
ClientConnectionWork client = new ClientConnectionWork(clientConnection);
ExecutorService executorService = Executors.newFixedThreadPool(2);
- try {
- Future<Void> serverFuture = executorService.submit(server);
- Future<Void> clientFuture = executorService.submit(client);
+ Future<Void> serverFuture = executorService.submit(server);
+ Future<Void> clientFuture = executorService.submit(client);
+ Throwable failure = null;
+ try {
serverFuture.get(30, TimeUnit.SECONDS);
+ } catch (ExecutionException e) {
+ failure = e.getCause();
+ }
+ try {
clientFuture.get(30, TimeUnit.SECONDS);
} catch (ExecutionException e) {
- throw e.getCause();
- } finally {
- executorService.shutdown();
+ if (failure != null) {
+ failure.printStackTrace(); // print it before we overwrite it
+ }
+ failure = e.getCause();
+ }
+
+ executorService.shutdown();
+
+ if (failure != null) {
+ throw failure;
}
return server.peerSocket;
@@ -1348,13 +1373,13 @@
// read the content of HTTP(s) response
InputStream is = connection.getInputStream();
log("Input Stream obtained");
- byte[] buff = new byte[2048];
- int num = 0;
- int byt = 0;
- while ((num < buff.length) && ((byt = is.read()) != -1)) {
- buff[num++] = (byte) byt;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buffer = new byte[1024];
+ int count;
+ while ((count = is.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
}
- String message = new String(buff, 0, num);
+ String message = new String(out.toByteArray());
log("Got content:\n" + message);
log("------------------");
log("Response code: " + connection.getResponseCode());
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java
deleted file mode 100644
index e266b7c..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java
+++ /dev/null
@@ -1,50 +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.
- */
-
-package org.apache.harmony.luni.tests.java.io;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = new TestSuite("Tests for java.io");
-
- suite.addTestSuite(BufferedReaderTest.class);
- suite.addTestSuite(FilePermissionTest.class);
- suite.addTestSuite(FileTest.class);
- suite.addTestSuite(InputStreamReaderTest.class);
- suite.addTestSuite(ObjectInputStreamTest.class);
- suite.addTestSuite(ObjectStreamConstantsTest.class);
- suite.addTestSuite(OutputStreamWriterTest.class);
- suite.addTestSuite(PushBackInputStreamTest.class);
- suite.addTestSuite(RandomAccessFileTest.class);
- suite.addTestSuite(ReaderTest.class);
- suite.addTestSuite(WriterTest.class);
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java
deleted file mode 100644
index 0581ecc..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java
+++ /dev/null
@@ -1,592 +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.luni.tests.java.io;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.CharArrayReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PipedReader;
-import java.io.Reader;
-import java.io.StringReader;
-
-import junit.framework.TestCase;
-import tests.support.Support_StringReader;
-
-public class BufferedReaderTest extends TestCase {
-
- BufferedReader br;
-
- String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * The spec says that BufferedReader.readLine() considers only "\r", "\n"
- * and "\r\n" to be line separators. We must not permit additional separator
- * characters.
- */
- public void test_readLine_IgnoresEbcdic85Characters() throws IOException {
- assertLines("A\u0085B", "A\u0085B");
- }
-
- public void test_readLine_Separators() throws IOException {
- assertLines("A\nB\nC", "A", "B", "C");
- assertLines("A\rB\rC", "A", "B", "C");
- assertLines("A\r\nB\r\nC", "A", "B", "C");
- assertLines("A\n\rB\n\rC", "A", "", "B", "", "C");
- assertLines("A\n\nB\n\nC", "A", "", "B", "", "C");
- assertLines("A\r\rB\r\rC", "A", "", "B", "", "C");
- assertLines("A\n\n", "A", "");
- assertLines("A\n\r", "A", "");
- assertLines("A\r\r", "A", "");
- assertLines("A\r\n", "A");
- assertLines("A\r\n\r\n", "A", "");
- }
-
- private void assertLines(String in, String... lines) throws IOException {
- BufferedReader bufferedReader
- = new BufferedReader(new Support_StringReader(in));
- for (String line : lines) {
- assertEquals(line, bufferedReader.readLine());
- }
- assertNull(bufferedReader.readLine());
- }
-
- /**
- * @tests java.io.BufferedReader#BufferedReader(java.io.Reader)
- */
- public void test_ConstructorLjava_io_Reader() {
- // Test for method java.io.BufferedReader(java.io.Reader)
- assertTrue("Used in tests", true);
- }
-
- /**
- * @tests java.io.BufferedReader#BufferedReader(java.io.Reader, int)
- */
- public void test_ConstructorLjava_io_ReaderI() {
- // Test for method java.io.BufferedReader(java.io.Reader, int)
- assertTrue("Used in tests", true);
- }
-
- /**
- * @tests java.io.BufferedReader#close()
- */
- public void test_close() {
- // Test for method void java.io.BufferedReader.close()
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.close();
- br.read();
- fail("Read on closed stream");
- } catch (IOException x) {
- return;
- }
- }
-
- /**
- * @tests java.io.BufferedReader#mark(int)
- */
- public void test_markI() throws IOException {
- // Test for method void java.io.BufferedReader.mark(int)
- char[] buf = null;
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- br.mark(1000);
- br.skip(250);
- br.reset();
- buf = new char[testString.length()];
- br.read(buf, 0, 500);
- assertTrue("Failed to set mark properly", testString.substring(500,
- 1000).equals(new String(buf, 0, 500)));
-
- try {
- br = new BufferedReader(new Support_StringReader(testString), 800);
- br.skip(500);
- br.mark(250);
- br.read(buf, 0, 1000);
- br.reset();
- fail("Failed to invalidate mark properly");
- } catch (IOException x) {
- // Expected
- }
-
- char[] chars = new char[256];
- for (int i = 0; i < 256; i++)
- chars[i] = (char) i;
- Reader in = new BufferedReader(new Support_StringReader(new String(
- chars)), 12);
-
- in.skip(6);
- in.mark(14);
- in.read(new char[14], 0, 14);
- in.reset();
- assertTrue("Wrong chars", in.read() == (char) 6
- && in.read() == (char) 7);
-
- in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
- in.skip(6);
- in.mark(8);
- in.skip(7);
- in.reset();
- assertTrue("Wrong chars 2", in.read() == (char) 6
- && in.read() == (char) 7);
-
- BufferedReader br = new BufferedReader(new StringReader("01234"), 2);
- br.mark(3);
- char[] carray = new char[3];
- int result = br.read(carray);
- assertEquals(3, result);
- assertEquals("Assert 0:", '0', carray[0]);
- assertEquals("Assert 1:", '1', carray[1]);
- assertEquals("Assert 2:", '2', carray[2]);
- assertEquals("Assert 3:", '3', br.read());
-
- br = new BufferedReader(new StringReader("01234"), 2);
- br.mark(3);
- carray = new char[4];
- result = br.read(carray);
- assertEquals("Assert 4:", 4, result);
- assertEquals("Assert 5:", '0', carray[0]);
- assertEquals("Assert 6:", '1', carray[1]);
- assertEquals("Assert 7:", '2', carray[2]);
- assertEquals("Assert 8:", '3', carray[3]);
- assertEquals("Assert 9:", '4', br.read());
- assertEquals("Assert 10:", -1, br.read());
-
- BufferedReader reader = new BufferedReader(new StringReader("01234"));
- reader.mark(Integer.MAX_VALUE);
- reader.read();
- reader.close();
- }
-
- /**
- * @tests java.io.BufferedReader#markSupported()
- */
- public void test_markSupported() {
- // Test for method boolean java.io.BufferedReader.markSupported()
- br = new BufferedReader(new Support_StringReader(testString));
- assertTrue("markSupported returned false", br.markSupported());
- }
-
- /**
- * @tests java.io.BufferedReader#read()
- */
- public void test_read() throws IOException {
- // Test for method int java.io.BufferedReader.read()
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- int r = br.read();
- assertTrue("Char read improperly", testString.charAt(0) == r);
- br = new BufferedReader(new Support_StringReader(new String(
- new char[] { '\u8765' })));
- assertTrue("Wrong double byte character", br.read() == '\u8765');
- } catch (java.io.IOException e) {
- fail("Exception during read test");
- }
-
- char[] chars = new char[256];
- for (int i = 0; i < 256; i++)
- chars[i] = (char) i;
- Reader in = new BufferedReader(new Support_StringReader(new String(
- chars)), 12);
- try {
- assertEquals("Wrong initial char", 0, in.read()); // Fill the
- // buffer
- char[] buf = new char[14];
- in.read(buf, 0, 14); // Read greater than the buffer
- assertTrue("Wrong block read data", new String(buf)
- .equals(new String(chars, 1, 14)));
- assertEquals("Wrong chars", 15, in.read()); // Check next byte
- } catch (IOException e) {
- fail("Exception during read test 2:" + e);
- }
-
- // regression test for HARMONY-841
- assertTrue(new BufferedReader(new CharArrayReader(new char[5], 1, 0), 2).read() == -1);
- }
-
- /**
- * @tests java.io.BufferedReader#read(char[], int, int)
- */
- public void test_read$CII() throws Exception{
- char[] ca = new char[2];
- BufferedReader toRet = new BufferedReader(new InputStreamReader(
- new ByteArrayInputStream(new byte[0])));
-
- /* Null buffer should throw NPE even when len == 0 */
- try {
- toRet.read(null, 1, 0);
- fail("null buffer reading zero bytes should throw NPE");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- toRet.close();
- } catch (IOException e) {
- fail("unexpected 1: " + e);
- }
-
- try {
- toRet.read(null, 1, 0);
- fail("null buffer reading zero bytes on closed stream should throw IOException");
- } catch (IOException e) {
- //expected
- }
-
- /* Closed reader should throw IOException reading zero bytes */
- try {
- toRet.read(ca, 0, 0);
- fail("Reading zero bytes on a closed reader should not work");
- } catch (IOException e) {
- // expected
- }
-
- /*
- * Closed reader should throw IOException in preference to index out of
- * bounds
- */
- try {
- // Read should throw IOException before
- // ArrayIndexOutOfBoundException
- toRet.read(ca, 1, 5);
- fail("IOException should have been thrown");
- } catch (IOException e) {
- // expected
- }
-
- // Test to ensure that a drained stream returns 0 at EOF
- toRet = new BufferedReader(new InputStreamReader(
- new ByteArrayInputStream(new byte[2])));
- try {
- assertEquals("Emptying the reader should return two bytes", 2,
- toRet.read(ca, 0, 2));
- assertEquals("EOF on a reader should be -1", -1, toRet.read(ca, 0,
- 2));
- assertEquals("Reading zero bytes at EOF should work", 0, toRet
- .read(ca, 0, 0));
- } catch (IOException ex) {
- fail("Unexpected IOException : " + ex.getLocalizedMessage());
- }
-
- // Test for method int java.io.BufferedReader.read(char [], int, int)
- try {
- char[] buf = new char[testString.length()];
- br = new BufferedReader(new Support_StringReader(testString));
- br.read(buf, 50, 500);
- assertTrue("Chars read improperly", new String(buf, 50, 500)
- .equals(testString.substring(0, 500)));
- } catch (java.io.IOException e) {
- fail("Exception during read test");
- }
-
- BufferedReader bufin = new BufferedReader(new Reader() {
- int size = 2, pos = 0;
-
- char[] contents = new char[size];
-
- public int read() throws IOException {
- if (pos >= size)
- throw new IOException("Read past end of data");
- return contents[pos++];
- }
-
- public int read(char[] buf, int off, int len) throws IOException {
- if (pos >= size)
- throw new IOException("Read past end of data");
- int toRead = len;
- if (toRead > (size - pos))
- toRead = size - pos;
- System.arraycopy(contents, pos, buf, off, toRead);
- pos += toRead;
- return toRead;
- }
-
- public boolean ready() throws IOException {
- return size - pos > 0;
- }
-
- public void close() throws IOException {
- }
- });
- try {
- bufin.read();
- int result = bufin.read(new char[2], 0, 2);
- assertTrue("Incorrect result: " + result, result == 1);
- } catch (IOException e) {
- fail("Unexpected: " + e);
- }
-
- //regression for HARMONY-831
- try{
- new BufferedReader(new PipedReader(), 9).read(new char[] {}, 7, 0);
- fail("should throw IndexOutOfBoundsException");
- }catch(IndexOutOfBoundsException e){
- }
-
- // Regression for HARMONY-54
- char[] ch = {};
- BufferedReader reader = new BufferedReader(new CharArrayReader(ch));
- try {
- // Check exception thrown when the reader is open.
- reader.read(null, 1, 0);
- fail("Assert 0: NullPointerException expected");
- } catch (NullPointerException e) {
- // Expected
- }
-
- // Now check IOException is thrown in preference to
- // NullPointerexception when the reader is closed.
- reader.close();
- try {
- reader.read(null, 1, 0);
- fail("Assert 1: IOException expected");
- } catch (IOException e) {
- // Expected
- }
-
- try {
- // And check that the IOException is thrown before
- // ArrayIndexOutOfBoundException
- reader.read(ch, 0, 42);
- fail("Assert 2: IOException expected");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.BufferedReader#read(char[], int, int)
- */
- public void test_read_$CII_Exception() throws IOException {
- br = new BufferedReader(new Support_StringReader(testString));
- char[] nullCharArray = null;
- char[] charArray = testString.toCharArray();
-
- try {
- br.read(nullCharArray, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- br.read(nullCharArray, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- br.read(nullCharArray, 0, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- br.read(nullCharArray, 0, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- br.read(nullCharArray, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- br.read(charArray, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- br.read(charArray, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- br.read(charArray, 0, 0);
- br.read(charArray, 0, charArray.length);
- br.read(charArray, charArray.length, 0);
-
- try {
- br.read(charArray, charArray.length + 1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- br.read(charArray, charArray.length + 1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- br.close();
-
- try {
- br.read(nullCharArray, -1, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- br.read(charArray, -1, 0);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- try {
- br.read(charArray, 0, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
- /**
- * @tests java.io.BufferedReader#readLine()
- */
- public void test_readLine() {
- // Test for method java.lang.String java.io.BufferedReader.readLine()
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- String r = br.readLine();
- assertEquals("readLine returned incorrect string", "Test_All_Tests", r
- );
- } catch (java.io.IOException e) {
- fail("Exception during readLine test");
- }
- }
-
- /**
- * @tests java.io.BufferedReader#ready()
- */
- public void test_ready() {
- // Test for method boolean java.io.BufferedReader.ready()
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- assertTrue("ready returned false", br.ready());
- } catch (java.io.IOException e) {
- fail("Exception during ready test" + e.toString());
- }
- }
-
- /**
- * @tests java.io.BufferedReader#reset()
- */
- public void test_reset() {
- // Test for method void java.io.BufferedReader.reset()
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- br.mark(900);
- br.skip(500);
- br.reset();
- char[] buf = new char[testString.length()];
- br.read(buf, 0, 500);
- assertTrue("Failed to reset properly", testString.substring(500,
- 1000).equals(new String(buf, 0, 500)));
- } catch (java.io.IOException e) {
- fail("Exception during reset test");
- }
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- br.reset();
- fail("Reset succeeded on unmarked stream");
- } catch (IOException x) {
- return;
-
- }
- }
-
- public void test_reset_IOException() throws Exception {
- int[] expected = new int[] { '1', '2', '3', '4', '5', '6', '7', '8',
- '9', '0', -1 };
- br = new BufferedReader(new Support_StringReader("1234567890"), 9);
- br.mark(9);
- for (int i = 0; i < 11; i++) {
- assertEquals(expected[i], br.read());
- }
- try {
- br.reset();
- fail("should throw IOException");
- } catch (IOException e) {
- // Expected
- }
- for (int i = 0; i < 11; i++) {
- assertEquals(-1, br.read());
- }
-
- br = new BufferedReader(new Support_StringReader("1234567890"));
- br.mark(10);
- for (int i = 0; i < 10; i++) {
- assertEquals(expected[i], br.read());
- }
- br.reset();
- for (int i = 0; i < 11; i++) {
- assertEquals(expected[i], br.read());
- }
- }
-
- /**
- * @tests java.io.BufferedReader#skip(long)
- */
- public void test_skipJ() {
- // Test for method long java.io.BufferedReader.skip(long)
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- char[] buf = new char[testString.length()];
- br.read(buf, 0, 500);
- assertTrue("Failed to set skip properly", testString.substring(500,
- 1000).equals(new String(buf, 0, 500)));
- } catch (java.io.IOException e) {
- fail("Exception during skip test");
- }
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- br.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java
deleted file mode 100644
index 5b5a759..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java
+++ /dev/null
@@ -1,222 +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.luni.tests.java.io;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.security.PermissionCollection;
-
-import junit.framework.TestCase;
-
-public class FilePermissionTest extends TestCase {
-
- FilePermission readAllFiles = new FilePermission("<<ALL FILES>>", "read");
-
- FilePermission alsoReadAllFiles = new FilePermission("<<ALL FILES>>",
- "read");
-
- FilePermission allInCurrent = new FilePermission("*",
- "read, write, execute,delete");
-
- FilePermission readInCurrent = new FilePermission("*", "read");
-
- FilePermission readInFile = new FilePermission("aFile.file", "read");
-
- FilePermission readInSubdir = new FilePermission("-", "read");
-
- /**
- * @tests java.io.FilePermission#FilePermission(java.lang.String,
- * java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- assertTrue("Used to test", true);
- FilePermission constructFile = new FilePermission("test constructor",
- "write");
- assertEquals(
- "action given to the constructor did not correspond - constructor failed",
- "write", constructFile.getActions());
- assertTrue(
- "name given to the constructor did not correspond - constructor failed",
- constructFile.getName() == "test constructor");
-
- // Regression test for HARMONY-1050
- try {
- new FilePermission(null, "drink");
- fail("Expected IAE");
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- try {
- new FilePermission(null, "read");
- fail("Expected NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- new FilePermission(null, null);
- fail("Expected IAE");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.FilePermission#getActions()
- */
- public void test_getActions() {
- assertEquals("getActions should have returned only read", "read",
- readAllFiles.getActions());
- assertEquals("getActions should have returned all actions",
- "read,write,execute,delete", allInCurrent.getActions());
- }
-
- /**
- * @tests java.io.FilePermission#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- assertTrue(
- "Should not returned false when two instance of FilePermission is equal",
- readAllFiles.equals(alsoReadAllFiles));
- assertFalse(
- "Should not returned true when two instance of FilePermission is not equal",
- readInCurrent.equals(readInFile));
- }
-
- /**
- * @tests java.io.FilePermission#implies(java.security.Permission)
- */
- public void test_impliesLjava_security_Permission() {
- assertFalse("Should not return true for non-subset of actions", readAllFiles
- .implies(allInCurrent));
- assertFalse("Should not return true for non-subset of files", allInCurrent
- .implies(readAllFiles));
- assertTrue("Should not return false for subset of actions", allInCurrent
- .implies(readInCurrent));
- assertTrue("Should not return false for subset of files", readAllFiles
- .implies(readInCurrent));
- assertTrue("Should not return false for subset of files and actions",
- allInCurrent.implies(readInFile));
- assertTrue("Should not return false for equal FilePermissions", readAllFiles
- .implies(alsoReadAllFiles));
- assertTrue("Should not return false for subdir self", readInSubdir.implies(readInSubdir));
- assertTrue("Should not return false for current self", readInCurrent.implies(readInCurrent));
- assertTrue("Should not return false for subdir", readInSubdir.implies(readInCurrent));
-
- FilePermission fp13 = new FilePermission(File.separator, "read");
- FilePermission fp14 = new FilePermission(File.separator + "*", "read");
- assertFalse("/ should not imply /*", fp13.implies(fp14));
- fp14 = new FilePermission(File.separator + "-", "read");
- assertFalse("/ should not imply /-", fp13.implies(fp14));
-
- FilePermission fp3 = new FilePermission("/bob/*".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp4 = new FilePermission("/bob/".replace('/',
- File.separatorChar), "write");
- assertFalse("Should not return true for same dir using * and not *", fp3
- .implies(fp4));
- FilePermission fp5 = new FilePermission("/bob/file".replace('/',
- File.separatorChar), "write");
- assertTrue("Should not return false for same dir using * and file", fp3
- .implies(fp5));
-
- FilePermission fp6 = new FilePermission("/bob/".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp7 = new FilePermission("/bob/*".replace('/',
- File.separatorChar), "write");
- assertFalse("Should not return true for same dir using not * and *", fp6
- .implies(fp7));
- assertTrue("Should not return false for same subdir", fp6.implies(fp4));
-
- FilePermission fp8 = new FilePermission("/".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp9 = new FilePermission("/".replace('/',
- File.separatorChar), "write");
- assertTrue("Should not return false for same dir", fp8.implies(fp9));
-
- FilePermission fp10 = new FilePermission("/".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp11 = new FilePermission("/".replace('/',
- File.separatorChar), "write");
- assertTrue("Should not return false for same dir", fp10.implies(fp11));
-
- FilePermission fp12 = new FilePermission("/*".replace('/',
- File.separatorChar), "read,write");
- assertFalse("Should not return true for same dir using * and dir", fp12
- .implies(fp10));
-
- // Regression for HARMONY-47
- char separator = File.separatorChar;
- char nonSeparator = (separator == '/') ? '\\' : '/';
-
- FilePermission fp1 = new FilePermission(nonSeparator + "*", "read");
- FilePermission fp2 = new FilePermission(separator + "a", "read");
- assertFalse("Assert 0: non-separator worked", fp1.implies(fp2));
- fp1 = new FilePermission(nonSeparator + "-", "read");
- assertFalse("Assert 1: non-separator worked", fp1.implies(fp2));
- }
-
- /**
- * @tests java.io.FilePermission#newPermissionCollection()
- */
- public void test_newPermissionCollection() {
- char s = File.separatorChar;
- FilePermission perm[] = new FilePermission[4];
- perm[0] = readAllFiles;
- perm[1] = allInCurrent;
- perm[2] = new FilePermission(s + "tmp" + s + "test" + s + "*",
- "read,write");
- perm[3] = new FilePermission(s + "tmp" + s + "test" + s
- + "collection.file", "read");
-
- PermissionCollection collect = perm[0].newPermissionCollection();
- for (int i = 0; i < perm.length; i++) {
- collect.add(perm[i]);
- }
- assertTrue("Should not return false for subset of files", collect
- .implies(new FilePermission("*", "write")));
- assertTrue("Should not return false for subset of name and action", collect
- .implies(new FilePermission(s + "tmp", "read")));
- assertTrue("Should not return false for non subset of file and action", collect
- .implies(readInFile));
-
- FilePermission fp1 = new FilePermission("/tmp/-".replace('/',
- File.separatorChar), "read");
- PermissionCollection fpc = fp1.newPermissionCollection();
- fpc.add(fp1);
- fpc.add(new FilePermission("/tmp/scratch/foo/*".replace('/',
- File.separatorChar), "write"));
- FilePermission fp2 = new FilePermission("/tmp/scratch/foo/file"
- .replace('/', File.separatorChar), "read,write");
- assertTrue("collection does not collate", fpc.implies(fp2));
- }
-
- /**
- * @tests java.io.FilePermission#hashCode()
- */
- public void test_hashCode() {
- assertTrue(
- "two equal filePermission instances returned different hashCode",
- readAllFiles.hashCode() == alsoReadAllFiles.hashCode());
- assertTrue(
- "two filePermission instances with same permission name returned same hashCode",
- readInCurrent.hashCode() != allInCurrent.hashCode());
-
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java
deleted file mode 100644
index f828c3b..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java
+++ /dev/null
@@ -1,2262 +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.luni.tests.java.io;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamField;
-import java.io.RandomAccessFile;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import tests.support.Support_Exec;
-import tests.support.Support_PlatformFile;
-
-public class FileTest extends TestCase {
-
- private static String platformId = "JDK"
- + System.getProperty("java.vm.version").replace('.', '-');
-
- private static void deleteTempFolder(File dir) {
- String files[] = dir.list();
- if (files != null) {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- if (f.isDirectory()) {
- deleteTempFolder(f);
- } else {
- f.delete();
- }
- }
- }
- dir.delete();
- }
-
- private static String addTrailingSlash(String path) {
- if (File.separatorChar == path.charAt(path.length() - 1)) {
- return path;
- }
- return path + File.separator;
- }
-
- /** Location to store tests in */
- private File tempDirectory;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- protected void setUp() throws IOException {
- /** Setup the temporary directory */
- tempDirectory = new File(addTrailingSlash(System.getProperty("java.io.tmpdir")) + "harmony-test-" + getClass().getSimpleName() + File.separator);
- tempDirectory.mkdirs();
- }
-
- protected void tearDown() {
- if (tempDirectory != null) {
- deleteTempFolder(tempDirectory);
- tempDirectory = null;
- }
- }
-
- /**
- * @tests java.io.File#File(java.io.File, java.lang.String)
- */
- public void test_ConstructorLjava_io_FileLjava_lang_String0() {
- File f = new File(tempDirectory.getPath(), "input.tst");
- assertEquals("Created Incorrect File ", addTrailingSlash(tempDirectory.getPath()) + "input.tst", f.getPath());
- }
-
- public void test_ConstructorLjava_io_FileLjava_lang_String1() {
- try {
- new File(tempDirectory, null);
- fail("NullPointerException Not Thrown.");
- } catch (NullPointerException e) {
- }
- }
-
- public void test_ConstructorLjava_io_FileLjava_lang_String2() throws IOException {
- File f = new File((File)null, "input.tst");
- assertEquals("Created Incorrect File",
- new File("input.tst").getAbsolutePath(),
- f.getAbsolutePath());
- }
-
- public void test_ConstructorLjava_io_FileLjava_lang_String3() {
- // Regression test for HARMONY-382
- File f = new File("/abc");
- File d = new File((File)null, "/abc");
- assertEquals("Test3: Created Incorrect File",
- d.getAbsolutePath(), f.getAbsolutePath());
- }
-
- public void test_ConstructorLjava_io_FileLjava_lang_String4() {
- // Regression test for HARMONY-21
- File path = new File("/dir/file");
- File root = new File("/");
- File file = new File(root, "/dir/file");
- assertEquals("Assert 1: wrong path result ", path.getPath(), file
- .getPath());
- if (File.separatorChar == '\\') {
- assertTrue("Assert 1.1: path not absolute ", new File("\\\\\\a\b")
- .isAbsolute());
- } else {
- assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b")
- .isAbsolute());
- }
- }
-
- public void test_ConstructorLjava_io_FileLjava_lang_String5() {
- // Test data used in a few places below
- String dirName = tempDirectory.getPath();
- String fileName = "input.tst";
-
- // Check filename is preserved correctly
- File d = new File(dirName);
- File f = new File(d, fileName);
- dirName = addTrailingSlash(dirName);
- dirName += fileName;
- assertEquals("Assert 1: Created incorrect file ",
- dirName, f.getPath());
-
- // Check null argument is handled
- try {
- f = new File(d, null);
- fail("Assert 2: NullPointerException not thrown.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- public void test_ConstructorLjava_io_FileLjava_lang_String6() {
- // Regression for HARMONY-46
- File f1 = new File("a");
- File f2 = new File("a/");
- assertEquals("Trailing slash file name is incorrect", f1, f2);
- }
-
- /**
- * @tests java.io.File#File(java.lang.String)
- */
- public void test_ConstructorLjava_lang_String() {
- String fileName = null;
- try {
- new File(fileName);
- fail("NullPointerException Not Thrown.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- fileName = addTrailingSlash(tempDirectory.getPath());
- fileName += "input.tst";
-
- File f = new File(fileName);
- assertEquals("Created incorrect File", fileName, f.getPath());
- }
-
- /**
- * @tests java.io.File#File(java.lang.String, java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException {
- String dirName = null;
- String fileName = "input.tst";
- File f = new File(dirName, fileName);
- assertEquals("Test 1: Created Incorrect File",
- new File("input.tst").getAbsolutePath(),
- f.getAbsolutePath());
-
- dirName = tempDirectory.getPath();
- fileName = null;
- try {
- f = new File(dirName, fileName);
- fail("NullPointerException Not Thrown.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- fileName = "input.tst";
- f = new File(dirName, fileName);
- assertEquals("Test 2: Created Incorrect File",
- addTrailingSlash(tempDirectory.getPath()) + "input.tst",
- f.getPath());
-
- // Regression test for HARMONY-382
- String s = null;
- f = new File("/abc");
- File d = new File(s, "/abc");
- assertEquals("Test3: Created Incorrect File", d.getAbsolutePath(), f
- .getAbsolutePath());
- }
-
- /**
- * @tests java.io.File#File(java.lang.String, java.lang.String)
- */
- public void test_Constructor_String_String_112270() {
- File ref1 = new File("/dir1/file1");
-
- File file1 = new File("/", "/dir1/file1");
- assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
- File file2 = new File("/", "//dir1/file1");
- assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
-
- if (File.separatorChar == '\\') {
- File file3 = new File("\\", "\\dir1\\file1");
- assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
- File file4 = new File("\\", "\\\\dir1\\file1");
- assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
- }
-
- File ref2 = new File("/lib/content-types.properties");
- File file5 = new File("/", "lib/content-types.properties");
- assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
- }
-
- /**
- * @tests java.io.File#File(java.io.File, java.lang.String)
- */
- public void test_Constructor_File_String_112270() {
- File ref1 = new File("/dir1/file1");
-
- File root = new File("/");
- File file1 = new File(root, "/dir1/file1");
- assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
- File file2 = new File(root, "//dir1/file1");
- assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
-
- if (File.separatorChar == '\\') {
- File file3 = new File(root, "\\dir1\\file1");
- assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
- File file4 = new File(root, "\\\\dir1\\file1");
- assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
- }
-
- File ref2 = new File("/lib/content-types.properties");
- File file5 = new File(root, "lib/content-types.properties");
- assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
- }
-
- /**
- * @tests java.io.File#File(java.net.URI)
- */
- public void test_ConstructorLjava_net_URI() throws URISyntaxException {
- URI uri = null;
- try {
- new File(uri);
- fail("NullPointerException Not Thrown.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- // invalid file URIs
- String[] uris = new String[] { "mailto:user@domain.com", // not
- // hierarchical
- "ftp:///path", // not file scheme
- "//host/path/", // not absolute
- "file://host/path", // non empty authority
- "file:///path?query", // non empty query
- "file:///path#fragment", // non empty fragment
- "file:///path?", "file:///path#" };
-
- for (int i = 0; i < uris.length; i++) {
- uri = new URI(uris[i]);
- try {
- new File(uri);
- fail("Expected IllegalArgumentException for new File(" + uri
- + ")");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- // a valid File URI
- File f = new File(new URI("file:///pa%20th/another\u20ac/pa%25th"));
- assertTrue("Created incorrect File " + f.getPath(), f.getPath().equals(
- File.separator + "pa th" + File.separator + "another\u20ac" + File.separator + "pa%th"));
- }
-
- /**
- * @tests java.io.File#canRead()
- */
- public void test_canRead() throws IOException {
- // canRead only returns if the file exists so cannot be fully tested.
- File f = new File(tempDirectory, platformId + "canRead.tst");
- try {
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("canRead returned false", f.canRead());
- } finally {
- f.delete();
- }
- }
-
- /**
- * @tests java.io.File#canWrite()
- */
- public void test_canWrite() throws IOException {
- // canWrite only returns if the file exists so cannot be fully tested.
- File f = new File(tempDirectory, platformId + "canWrite.tst");
- try {
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("canWrite returned false", f.canWrite());
- } finally {
- f.delete();
- }
- }
-
- /**
- * @tests java.io.File#compareTo(java.io.File)
- */
- public void test_compareToLjava_io_File() {
- File f1 = new File("thisFile.file");
- File f2 = new File("thisFile.file");
- File f3 = new File("thatFile.file");
- assertEquals("Equal files did not answer zero for compareTo", 0, f1
- .compareTo(f2));
- assertTrue("f3.compareTo(f1) did not result in value < 0", f3
- .compareTo(f1) < 0);
- assertTrue("f1.compareTo(f3) did not result in value > 0", f1
- .compareTo(f3) > 0);
- }
-
- /**
- * @tests java.io.File#createNewFile()
- */
- public void test_createNewFile_EmptyString() {
- File f = new File("");
- try {
- f.createNewFile();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.File#createNewFile()
- */
- public void test_createNewFile() throws IOException {
- String base = tempDirectory.getPath();
- boolean dirExists = true;
- int numDir = 1;
- File dir = new File(base, String.valueOf(numDir));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number
- // (making it a new directory name.)
- if (dir.exists()) {
- numDir++;
- dir = new File(base, String.valueOf(numDir));
- } else {
- dirExists = false;
- }
- }
-
- // Test for trying to create a file in a directory that does not
- // exist.
- try {
- // Try to create a file in a directory that does not exist
- File f1 = new File(dir, "tempfile.tst");
- f1.createNewFile();
- fail("IOException not thrown");
- } catch (IOException e) {
- // Expected
- }
-
- dir.mkdir();
-
- File f1 = new File(dir, "tempfile.tst");
- File f2 = new File(dir, "tempfile.tst");
- f1.deleteOnExit();
- f2.deleteOnExit();
- dir.deleteOnExit();
- assertFalse("File Should Not Exist", f1.isFile());
- f1.createNewFile();
- assertTrue("File Should Exist.", f1.isFile());
- assertTrue("File Should Exist.", f2.isFile());
- String dirName = f1.getParent();
- if (!dirName.endsWith(File.separator)) {
- dirName += File.separator;
- }
- assertEquals("File Saved To Wrong Directory.",
- dir.getPath() + File.separator, dirName);
- assertEquals("File Saved With Incorrect Name.", "tempfile.tst",
- f1.getName());
-
- // Test for creating a file that already exists.
- assertFalse("File Already Exists, createNewFile Should Return False.",
- f2.createNewFile());
-
- // Test create an illegal file
- String sep = File.separator;
- f1 = new File(sep + "..");
- try {
- f1.createNewFile();
- fail("should throw IOE");
- } catch (IOException e) {
- // expected;
- }
- f1 = new File(sep + "a" + sep + ".." + sep + ".." + sep);
- try {
- f1.createNewFile();
- fail("should throw IOE");
- } catch (IOException e) {
- // expected;
- }
-
- // This test is invalid. createNewFile should return false
- // not IOE when the file exists (in this case it exists and is
- // a directory). TODO: We should probably replace this test
- // with some that cover this behaviour. It might even be
- // different on unix and windows since it directly reflects
- // the open syscall behaviour.
- //
- // // Test create an exist path
- // f1 = new File(base);
- // try {
- // assertFalse(f1.createNewFile());
- // fail("should throw IOE");
- // } catch (IOException e) {
- // // expected;
- // }
- }
-
- /**
- * @tests java.io.File#createTempFile(java.lang.String, java.lang.String)
- */
- public void test_createTempFileLjava_lang_StringLjava_lang_String()
- throws IOException {
- // Error protection against using a suffix without a "."?
- File f1 = null;
- File f2 = null;
- try {
- f1 = File.createTempFile("harmony-test-FileTest_tempFile_abc", ".tmp");
- f2 = File.createTempFile("harmony-test-FileTest_tempFile_tf", null);
-
- String fileLocation = addTrailingSlash(f1.getParent());
-
- String tempDir = addTrailingSlash(System.getProperty("java.io.tmpdir"));
-
- assertEquals(
- "File did not save to the default temporary-file location.",
- tempDir, fileLocation);
-
- // Test to see if correct suffix was used to create the tempfile.
- File currentFile;
- String fileName;
- // Testing two files, one with suffix ".tmp" and one with null
- for (int i = 0; i < 2; i++) {
- currentFile = i == 0 ? f1 : f2;
- fileName = currentFile.getPath();
- assertTrue("File Created With Incorrect Suffix.", fileName
- .endsWith(".tmp"));
- }
-
- // Tests to see if the correct prefix was used to create the
- // tempfiles.
- fileName = f1.getName();
- assertTrue("Test 1: File Created With Incorrect Prefix.", fileName
- .startsWith("harmony-test-FileTest_tempFile_abc"));
- fileName = f2.getName();
- assertTrue("Test 2: File Created With Incorrect Prefix.", fileName
- .startsWith("harmony-test-FileTest_tempFile_tf"));
-
- // Tests for creating a tempfile with a filename shorter than 3
- // characters.
- try {
- File f3 = File.createTempFile("ab", ".tst");
- f3.delete();
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- try {
- File f3 = File.createTempFile("a", ".tst");
- f3.delete();
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- try {
- File f3 = File.createTempFile("", ".tst");
- f3.delete();
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- } finally {
- if (f1 != null) {
- f1.delete();
- }
- if (f2 != null) {
- f2.delete();
- }
- }
- }
-
- /**
- * @tests java.io.File#createTempFile(java.lang.String, java.lang.String,
- * java.io.File)
- */
- public void test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File()
- throws IOException {
- File f1 = null;
- File f2 = null;
- String base = System.getProperty("java.io.tmpdir");
- try {
- // Test to make sure that the tempfile was saved in the correct
- // location and with the correct prefix/suffix.
- f1 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", null, null);
- File dir = new File(base);
- f2 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", ".tmp", dir);
- File currentFile;
- String fileLocation;
- String fileName;
- for (int i = 0; i < 2; i++) {
- currentFile = i == 0 ? f1 : f2;
- fileLocation = addTrailingSlash(currentFile.getParent());
- base = addTrailingSlash(base);
- assertEquals(
- "File not created in the default temporary-file location.",
- base, fileLocation);
- fileName = currentFile.getName();
- assertTrue("File created with incorrect suffix.", fileName
- .endsWith(".tmp"));
- assertTrue("File created with incorrect prefix.", fileName
- .startsWith("harmony-test-FileTest_tempFile2_tf"));
- currentFile.delete();
- }
-
- // Test for creating a tempfile in a directory that does not exist.
- int dirNumber = 1;
- boolean dirExists = true;
- // Set dir to a non-existent directory inside the temporary
- // directory
- dir = new File(base, String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number
- // (making it
- // a new directory name.)
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
- try {
- // Try to create a file in a directory that does not exist
- File f3 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", null, dir);
- f3.delete();
- fail("IOException not thrown");
- } catch (IOException e) {
- // Expected
- }
- dir.delete();
-
- // Tests for creating a tempfile with a filename shorter than 3
- // characters.
- try {
- File f4 = File.createTempFile("ab", null, null);
- f4.delete();
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- try {
- File f4 = File.createTempFile("a", null, null);
- f4.delete();
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- try {
- File f4 = File.createTempFile("", null, null);
- f4.delete();
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- } finally {
- if (f1 != null) {
- f1.delete();
- }
- if (f2 != null) {
- f1.delete();
- }
- }
- }
-
- /**
- * @tests java.io.File#delete()
- */
- public void test_delete() throws IOException {
- File dir = new File(tempDirectory, platformId
- + "filechk");
- dir.mkdir();
- assertTrue("Directory does not exist", dir.exists());
- assertTrue("Directory is not directory", dir.isDirectory());
- File f = new File(dir, "filechk.tst");
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("Error Creating File For Delete Test", f.exists());
- dir.delete();
- assertTrue("Directory Should Not Have Been Deleted.", dir.exists());
- f.delete();
- assertTrue("File Was Not Deleted", !f.exists());
- dir.delete();
- assertTrue("Directory Was Not Deleted", !dir.exists());
- }
-
- // GCH
- // TODO : This test passes on Windows but fails on Linux with a
- // java.lang.NoClassDefFoundError. Temporarily removing from the test
- // suite while I investigate the cause.
- // /**
- // * @tests java.io.File#deleteOnExit()
- // */
- // public void test_deleteOnExit() {
- // File f1 = new File(System.getProperty("java.io.tmpdir"), platformId
- // + "deleteOnExit.tst");
- // try {
- // FileOutputStream fos = new FileOutputStream(f1);
- // fos.close();
- // } catch (IOException e) {
- // fail("Unexpected IOException During Test : " + e.getMessage());
- // }
- // assertTrue("File Should Exist.", f1.exists());
- //
- // try {
- // Support_Exec.execJava(new String[] {
- // "tests.support.Support_DeleteOnExitTest", f1.getPath() },
- // null, true);
- // } catch (IOException e) {
- // fail("Unexpected IOException During Test + " + e.getMessage());
- // } catch (InterruptedException e) {
- // fail("Unexpected InterruptedException During Test: " + e);
- // }
- //
- // boolean gone = !f1.exists();
- // f1.delete();
- // assertTrue("File Should Already Be Deleted.", gone);
- // }
-
- /**
- * @tests java.io.File#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() throws IOException {
- File f1 = new File("filechk.tst");
- File f2 = new File("filechk.tst");
- File f3 = new File("xxxx");
-
- assertTrue("Equality test failed", f1.equals(f2));
- assertTrue("Files Should Not Return Equal.", !f1.equals(f3));
-
- f3 = new File("FiLeChK.tst");
- boolean onWindows = File.separatorChar == '\\';
- boolean onUnix = File.separatorChar == '/';
- if (onWindows) {
- assertTrue("Files Should Return Equal.", f1.equals(f3));
- } else if (onUnix) {
- assertTrue("Files Should NOT Return Equal.", !f1.equals(f3));
- }
-
- f1 = new File(tempDirectory, "casetest.tmp");
- f2 = new File(tempDirectory, "CaseTest.tmp");
- new FileOutputStream(f1).close(); // create the file
- if (f1.equals(f2)) {
- try {
- FileInputStream fis = new FileInputStream(f2);
- fis.close();
- } catch (IOException e) {
- fail("File system is case sensitive");
- }
- } else {
- boolean exception = false;
- try {
- FileInputStream fis = new FileInputStream(f2);
- fis.close();
- } catch (IOException e) {
- exception = true;
- }
- assertTrue("File system is case insensitive", exception);
- }
- f1.delete();
- }
-
- /**
- * @tests java.io.File#exists()
- */
- public void test_exists() throws IOException {
- File f = new File(tempDirectory, platformId
- + "exists.tst");
- assertTrue("Exists returned true for non-existent file", !f.exists());
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("Exists returned false file", f.exists());
- f.delete();
- }
-
- /**
- * @tests java.io.File#getAbsoluteFile()
- */
- public void test_getAbsoluteFile() {
- String base = addTrailingSlash(tempDirectory.getPath());
- File f = new File(base, "temp.tst");
- File f2 = f.getAbsoluteFile();
- assertEquals("Test 1: Incorrect File Returned.", 0, f2.compareTo(f
- .getAbsoluteFile()));
- f = new File(base + "Temp" + File.separator + File.separator + "temp.tst");
- f2 = f.getAbsoluteFile();
- assertEquals("Test 2: Incorrect File Returned.", 0, f2.compareTo(f
- .getAbsoluteFile()));
- f = new File(base + File.separator + ".." + File.separator + "temp.tst");
- f2 = f.getAbsoluteFile();
- assertEquals("Test 3: Incorrect File Returned.", 0, f2.compareTo(f
- .getAbsoluteFile()));
- f.delete();
- f2.delete();
- }
-
- /**
- * @tests java.io.File#getAbsolutePath()
- */
- public void test_getAbsolutePath() {
- String base = addTrailingSlash(tempDirectory.getPath());
- File f = new File(base, "temp.tst");
- assertEquals("Test 1: Incorrect Path Returned.",
- base + "temp.tst", f.getAbsolutePath());
-
- f = new File(base + "Temp" + File.separator + File.separator + File.separator + "Testing" + File.separator
- + "temp.tst");
- assertEquals("Test 2: Incorrect Path Returned.",
- base + "Temp" + File.separator + "Testing" + File.separator + "temp.tst",
- f.getAbsolutePath());
-
- f = new File(base + "a" + File.separator + File.separator + ".." + File.separator + "temp.tst");
- assertEquals("Test 3: Incorrect Path Returned.",
- base + "a" + File.separator + ".." + File.separator + "temp.tst",
- f.getAbsolutePath());
- f.delete();
- }
-
- /**
- * @tests java.io.File#getCanonicalFile()
- */
- public void test_getCanonicalFile() throws IOException {
- String base = addTrailingSlash(tempDirectory.getPath());
- File f = new File(base, "temp.tst");
- File f2 = f.getCanonicalFile();
- assertEquals("Test 1: Incorrect File Returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
- f = new File(base + "Temp" + File.separator + File.separator + "temp.tst");
- f2 = f.getCanonicalFile();
- assertEquals("Test 2: Incorrect File Returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
- f = new File(base + "Temp" + File.separator + File.separator + ".." + File.separator + "temp.tst");
- f2 = f.getCanonicalFile();
- assertEquals("Test 3: Incorrect File Returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
-
- // Test for when long directory/file names in Windows
- boolean onWindows = File.separatorChar == '\\';
- if (onWindows) {
- File testdir = new File(base, "long-" + platformId);
- testdir.mkdir();
- File dir = new File(testdir, "longdirectory" + platformId);
- try {
- dir.mkdir();
- f = new File(dir, "longfilename.tst");
- f2 = f.getCanonicalFile();
- assertEquals("Test 4: Incorrect File Returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- f2 = new File(testdir + File.separator + "longdi~1" + File.separator
- + "longfi~1.tst");
- File canonicalf2 = f2.getCanonicalFile();
- /*
- * If the "short file name" doesn't exist, then assume that the
- * 8.3 file name compatibility is disabled.
- */
- if (canonicalf2.exists()) {
- assertTrue("Test 5: Incorrect File Returned: "
- + canonicalf2, canonicalf2.compareTo(f
- .getCanonicalFile()) == 0);
- }
- } finally {
- f.delete();
- f2.delete();
- dir.delete();
- testdir.delete();
- }
- }
- }
-
- /**
- * @tests java.io.File#getCanonicalPath()
- */
- public void test_getCanonicalPath() throws IOException {
- // Should work for Unix/Windows.
- String dots = "..";
- String base = tempDirectory.getCanonicalPath();
- base = addTrailingSlash(base);
- File f = new File(base, "temp.tst");
- assertEquals("Test 1: Incorrect Path Returned.", base + "temp.tst", f
- .getCanonicalPath());
- f = new File(base + "Temp" + File.separator + dots + File.separator + "temp.tst");
- assertEquals("Test 2: Incorrect Path Returned.", base + "temp.tst", f
- .getCanonicalPath());
-
- // Finding a non-existent directory for tests 3 and 4
- // This is necessary because getCanonicalPath is case sensitive and
- // could cause a failure in the test if the directory exists but with
- // different case letters (e.g "Temp" and "temp")
- int dirNumber = 1;
- boolean dirExists = true;
- File dir1 = new File(base, String.valueOf(dirNumber));
- while (dirExists) {
- if (dir1.exists()) {
- dirNumber++;
- dir1 = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
- f = new File(base + dirNumber + File.separator + dots + File.separator + dirNumber
- + File.separator + "temp.tst");
- assertEquals("Test 3: Incorrect Path Returned.", base + dirNumber
- + File.separator + "temp.tst", f.getCanonicalPath());
- f = new File(base + dirNumber + File.separator + "Temp" + File.separator + dots + File.separator
- + "Test" + File.separator + "temp.tst");
- assertEquals("Test 4: Incorrect Path Returned.", base + dirNumber
- + File.separator + "Test" + File.separator + "temp.tst", f.getCanonicalPath());
-
- f = new File(base + "1234.567");
- assertEquals("Test 5: Incorrect Path Returned.", base + "1234.567", f
- .getCanonicalPath());
-
- // Test for long file names on Windows
- boolean onWindows = (File.separatorChar == '\\');
- if (onWindows) {
- File testdir = new File(base, "long-" + platformId);
- testdir.mkdir();
- File f1 = new File(testdir, "longfilename" + platformId + ".tst");
- FileOutputStream fos = new FileOutputStream(f1);
- File f2 = null, f3 = null, dir2 = null;
- try {
- fos.close();
- String dirName1 = f1.getCanonicalPath();
- File f4 = new File(testdir, "longfi~1.tst");
- /*
- * If the "short file name" doesn't exist, then assume that the
- * 8.3 file name compatibility is disabled.
- */
- if (f4.exists()) {
- String dirName2 = f4.getCanonicalPath();
- assertEquals("Test 6: Incorrect Path Returned.", dirName1,
- dirName2);
- dir2 = new File(testdir, "longdirectory" + platformId);
- if (!dir2.exists()) {
- assertTrue("Could not create dir: " + dir2, dir2
- .mkdir());
- }
- f2 = new File(testdir.getPath() + File.separator + "longdirectory"
- + platformId + File.separator + "Test" + File.separator + dots
- + File.separator + "longfilename.tst");
- FileOutputStream fos2 = new FileOutputStream(f2);
- fos2.close();
- dirName1 = f2.getCanonicalPath();
- f3 = new File(testdir.getPath() + File.separator + "longdi~1"
- + File.separator + "Test" + File.separator + dots + File.separator
- + "longfi~1.tst");
- dirName2 = f3.getCanonicalPath();
- assertEquals("Test 7: Incorrect Path Returned.", dirName1,
- dirName2);
- }
- } finally {
- f1.delete();
- if (f2 != null) {
- f2.delete();
- }
- if (dir2 != null) {
- dir2.delete();
- }
- testdir.delete();
- }
- }
- }
-
- /**
- * @tests java.io.File#getName()
- */
- public void test_getName() {
- File f = new File("name.tst");
- assertEquals("Test 1: Returned incorrect name", "name.tst", f.getName());
-
- f = new File("");
- assertEquals("Test 2: Returned incorrect name", "", f.getName());
-
- f.delete();
- }
-
- /**
- * @tests java.io.File#getParent()
- */
- public void test_getParent() {
- File f = new File("p.tst");
- assertNull("Incorrect path returned", f.getParent());
- f = new File(System.getProperty("user.home"), "p.tst");
- assertEquals("Incorrect path returned",
- System.getProperty("user.home"), f.getParent());
- f.delete();
-
- File f1 = new File("/directory");
- assertEquals("Wrong parent test 1", File.separator, f1.getParent());
- f1 = new File("/directory/file");
- assertEquals("Wrong parent test 2",
- File.separator + "directory", f1.getParent());
- f1 = new File("directory/file");
- assertEquals("Wrong parent test 3", "directory", f1.getParent());
- f1 = new File("/");
- assertNull("Wrong parent test 4", f1.getParent());
- f1 = new File("directory");
- assertNull("Wrong parent test 5", f1.getParent());
-
- if (File.separatorChar == '\\' && new File("d:/").isAbsolute()) {
- f1 = new File("d:/directory");
- assertEquals("Wrong parent test 1a", "d:" + File.separator, f1.getParent());
- f1 = new File("d:/directory/file");
- assertEquals("Wrong parent test 2a",
- "d:" + File.separator + "directory", f1.getParent());
- f1 = new File("d:directory/file");
- assertEquals("Wrong parent test 3a", "d:directory", f1.getParent());
- f1 = new File("d:/");
- assertNull("Wrong parent test 4a", f1.getParent());
- f1 = new File("d:directory");
- assertEquals("Wrong parent test 5a", "d:", f1.getParent());
- }
- }
-
- /**
- * @tests java.io.File#getParentFile()
- */
- public void test_getParentFile() {
- File f = new File("tempfile.tst");
- assertNull("Incorrect path returned", f.getParentFile());
- f = new File(tempDirectory, "tempfile1.tmp");
- File f2 = new File(tempDirectory, "tempfile2.tmp");
- File f3 = new File(tempDirectory, "/a/tempfile.tmp");
- assertEquals("Incorrect File Returned", 0, f.getParentFile().compareTo(
- f2.getParentFile()));
- assertTrue("Incorrect File Returned", f.getParentFile().compareTo(
- f3.getParentFile()) != 0);
- f.delete();
- f2.delete();
- f3.delete();
- }
-
- /**
- * @tests java.io.File#getPath()
- */
- public void test_getPath() {
- String base = System.getProperty("user.home");
- String fname;
- File f1;
- if (!base.regionMatches((base.length() - 1), File.separator, 0, 1)) {
- base += File.separator;
- }
- fname = base + "filechk.tst";
- f1 = new File(base, "filechk.tst");
- File f2 = new File("filechk.tst");
- File f3 = new File("c:");
- File f4 = new File(base + "a" + File.separator + File.separator + ".." + File.separator
- + "filechk.tst");
- assertEquals("getPath returned incorrect path(f1)",
- fname, f1.getPath());
- assertEquals("getPath returned incorrect path(f2)",
- "filechk.tst", f2.getPath());
- assertEquals("getPath returned incorrect path(f3)","c:", f3.getPath());
- assertEquals("getPath returned incorrect path(f4)",
- base + "a" + File.separator + ".." + File.separator + "filechk.tst",
- f4.getPath());
- f1.delete();
- f2.delete();
- f3.delete();
- f4.delete();
-
- // Regression for HARMONY-444
- File file;
- String separator = File.separator;
-
- file = new File((File) null, "x/y/z");
- assertEquals("x" + separator + "y" + separator + "z", file.getPath());
-
- file = new File((String) null, "x/y/z");
- assertEquals("x" + separator + "y" + separator + "z", file.getPath());
-
- // Regression for HARMONY-829
- String f1ParentName = "01";
- f1 = new File(f1ParentName, "");
- assertEquals(f1ParentName, f1.getPath());
-
- String f2ParentName = "0";
- f2 = new File(f2ParentName, "");
-
- assertEquals(-1, f2.compareTo(f1));
- assertEquals(1, f1.compareTo(f2));
-
- File parent = tempDirectory;
- f3 = new File(parent, "");
-
- assertEquals(parent.getPath(), f3.getPath());
-
- // Regression for HARMONY-3869
- File file1 = new File("", "");
- assertEquals(File.separator, file1.getPath());
-
- File file2 = new File(new File(""), "");
- assertEquals(File.separator, file2.getPath());
- }
-
- /**
- * @tests java.io.File#hashCode()
- */
- public void test_hashCode() {
- // Regression for HARMONY-53
- String mixedFname = "SoMe FiLeNaMe";
- File mfile = new File(mixedFname);
- File lfile = new File(mixedFname.toLowerCase());
-
- if (mfile.equals(lfile)) {
- assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile
- .hashCode());
- } else {
- assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile
- .hashCode());
- }
- }
-
- /**
- * @tests java.io.File#isAbsolute()
- */
- public void test_isAbsolute() {
- if (File.separatorChar == '\\') {
- File f = new File("c:\\test");
- File f1 = new File("\\test");
- // One or the other should be absolute on Windows or CE
- assertTrue("Absolute returned false", (f.isAbsolute() && !f1
- .isAbsolute())
- || (!f.isAbsolute() && f1.isAbsolute()));
-
- assertTrue(new File("C:/").isAbsolute());
- assertTrue(new File("f:/").isAbsolute());
- assertTrue(new File("f:\\").isAbsolute());
- assertFalse(new File("f:").isAbsolute());
- assertFalse(new File("K:").isAbsolute());
- assertTrue(new File("\\\\").isAbsolute());
- assertTrue(new File("\\\\\\").isAbsolute());
- assertTrue(new File("\\\\hello").isAbsolute());
- assertFalse(new File("\\").isAbsolute());
- assertFalse(new File("/").isAbsolute());
- } else {
- File f = new File("/test");
- File f1 = new File("\\test");
- assertTrue("Absolute returned false", f.isAbsolute());
- assertFalse("Absolute returned true", f1.isAbsolute());
- assertTrue(new File("//test").isAbsolute());
- assertFalse(new File("test").isAbsolute());
- assertFalse(new File("c:/").isAbsolute());
- assertFalse(new File("c:\\").isAbsolute());
- assertFalse(new File("c:").isAbsolute());
- assertFalse(new File("\\").isAbsolute());
- assertFalse(new File("\\\\").isAbsolute());
- }
- assertTrue("Non-Absolute returned true", !new File("../test")
- .isAbsolute());
- }
-
- /**
- * @tests java.io.File#isDirectory()
- */
- public void test_isDirectory() {
- String base = addTrailingSlash(tempDirectory.getPath());
- File f = new File(base);
- assertTrue("Test 1: Directory Returned False", f.isDirectory());
- f = new File(base + "zxzxzxz" + platformId);
- assertTrue("Test 2: (Not Created) Directory Returned True.", !f
- .isDirectory());
- f.mkdir();
- try {
- assertTrue("Test 3: Directory Returned False.", f.isDirectory());
- } finally {
- f.delete();
- }
- }
-
- /**
- * @tests java.io.File#isFile()
- */
- public void test_isFile() throws IOException {
- String base = tempDirectory.getPath();
- File f = new File(base);
- assertFalse("Directory Returned True As Being A File.", f.isFile());
-
- base = addTrailingSlash(base);
- f = new File(base, platformId + "amiafile");
- assertTrue("Non-existent File Returned True", !f.isFile());
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("File returned false", f.isFile());
- f.delete();
- }
-
- /**
- * @tests java.io.File#isHidden()
- */
- public void test_isHidden() throws IOException, InterruptedException {
- boolean onUnix = File.separatorChar == '/';
- File f = File.createTempFile("harmony-test-FileTest_isHidden_", ".tmp");
- // On Unix hidden files are marked with a "." at the beginning
- // of the file name.
- if (onUnix) {
- File f2 = new File(".test.tst" + platformId);
- FileOutputStream fos2 = new FileOutputStream(f2);
- fos2.close();
- assertTrue("File returned hidden on Unix", !f.isHidden());
- assertTrue("File returned visible on Unix", f2.isHidden());
- assertTrue("File did not delete.", f2.delete());
- } else {
- // For windows, the file is being set hidden by the attrib
- // command.
- Runtime r = Runtime.getRuntime();
- assertTrue("File returned hidden", !f.isHidden());
- Process p = r.exec("attrib +h \"" + f.getAbsolutePath() + "\"");
- p.waitFor();
- assertTrue("File returned visible", f.isHidden());
- p = r.exec("attrib -h \"" + f.getAbsolutePath() + "\"");
- p.waitFor();
- assertTrue("File returned hidden", !f.isHidden());
- }
- f.delete();
- }
-
- /**
- * @tests java.io.File#lastModified()
- */
- public void test_lastModified() throws IOException {
- File f = new File(System.getProperty("java.io.tmpdir"), platformId
- + "lModTest.tst");
- f.delete();
- long lastModifiedTime = f.lastModified();
- assertEquals("LastModified Time Should Have Returned 0.", 0,
- lastModifiedTime);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- f.setLastModified(315550800000L);
- lastModifiedTime = f.lastModified();
- assertEquals("LastModified Time Incorrect",
- 315550800000L, lastModifiedTime);
- f.delete();
-
- // Regression for HARMONY-2146
- f = new File("/../");
- assertTrue(f.lastModified() > 0);
- }
-
- /**
- * @tests java.io.File#length()
- */
- public void test_length() throws IOException {
- File f = new File(tempDirectory, platformId
- + "input.tst");
- assertEquals("File Length Should Have Returned 0.", 0, f.length());
- FileOutputStream fos = new FileOutputStream(f);
- fos.write(fileString.getBytes());
- fos.close();
- assertEquals("Incorrect file length returned",
- fileString.length(), f.length());
- f.delete();
-
- // regression test for HARMONY-1497
- f = File.createTempFile("test", "tmp");
- f.deleteOnExit();
- RandomAccessFile raf = new RandomAccessFile(f, "rwd");
- raf.write(0x41);
- assertEquals(1, f.length());
- }
-
- /**
- * @tests java.io.File#list()
- */
- public void test_list() throws IOException {
- String base = tempDirectory.getPath();
- // Old test left behind "garbage files" so this time it creates a
- // directory that is guaranteed not to already exist (and deletes it
- // afterward.)
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = null;
- dir = new File(base, platformId + String.valueOf(dirNumber));
- while (dirExists) {
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- String[] flist = dir.list();
-
- assertNull("Method list() Should Have Returned null.", flist);
-
- assertTrue("Could not create parent directory for list test", dir
- .mkdir());
-
- String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
- try {
- assertEquals(
- "Method list() Should Have Returned An Array Of Length 0.",
- 0, dir.list().length);
-
- File file = new File(dir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.list());
- } finally {
- file.delete();
- }
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
-
- flist = dir.list();
- if (flist.length != files.length) {
- fail("Incorrect list returned");
- }
-
- // Checking to make sure the correct files were are listed in the
- // array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++) {
- check[i] = false;
- }
- for (int i = 0; i < files.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].equals(files[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false) {
- checkCount++;
- }
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
-
- assertTrue("Could not delete parent directory for list test.", dir
- .delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#listFiles()
- */
- public void test_listFiles() throws IOException, InterruptedException {
- String base = tempDirectory.getPath();
- // Finding a non-existent directory to create.
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, platformId + String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number
- // (making it a new directory name.)
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
- // Test for attempting to call listFiles on a non-existent directory.
- assertNull("listFiles Should Return Null.", dir.listFiles());
-
- assertTrue("Failed To Create Parent Directory.", dir.mkdir());
-
- String[] files = { "1.tst", "2.tst", "3.tst", "" };
- try {
- assertEquals("listFiles Should Return An Array Of Length 0.", 0,
- dir.listFiles().length);
-
- File file = new File(dir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.listFiles());
- } finally {
- file.delete();
- }
-
- for (int i = 0; i < (files.length - 1); i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
-
- new File(dir, "doesNotExist.tst");
- File[] flist = dir.listFiles();
-
- // Test to make sure that only the 3 files that were created are
- // listed.
- assertEquals("Incorrect Number Of Files Returned.", 3, flist.length);
-
- // Test to make sure that listFiles can read hidden files.
- boolean onUnix = File.separatorChar == '/';
- boolean onWindows = File.separatorChar == '\\';
- if (onWindows) {
- files[3] = "4.tst";
- File f = new File(dir, "4.tst");
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- Runtime r = Runtime.getRuntime();
- Process p = r.exec("attrib +h \"" + f.getPath() + "\"");
- p.waitFor();
- }
- if (onUnix) {
- files[3] = ".4.tst";
- File f = new File(dir, ".4.tst");
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- flist = dir.listFiles();
- assertEquals("Incorrect Number Of Files Returned.", 4, flist.length);
-
- // Checking to make sure the correct files were are listed in
- // the array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++) {
- check[i] = false;
- }
- for (int i = 0; i < files.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].getName().equals(files[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false) {
- checkCount++;
- }
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- if (onWindows) {
- Runtime r = Runtime.getRuntime();
- Process p = r.exec("attrib -h \""
- + new File(dir, files[3]).getPath() + "\"");
- p.waitFor();
- }
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- assertTrue("Parent Directory Not Deleted.", dir.delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#listFiles(java.io.FileFilter)
- */
- public void test_listFilesLjava_io_FileFilter() throws IOException {
- String base = System.getProperty("java.io.tmpdir");
- // Finding a non-existent directory to create.
- int dirNumber = 1;
- boolean dirExists = true;
- File baseDir = new File(base, platformId + String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number (making
- // it a new directory name.)
- if (baseDir.exists()) {
- dirNumber++;
- baseDir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- // Creating a filter that catches directories.
- FileFilter dirFilter = new FileFilter() {
- public boolean accept(File f) {
- return f.isDirectory();
- }
- };
-
- assertNull("listFiles Should Return Null.", baseDir
- .listFiles(dirFilter));
-
- assertTrue("Failed To Create Parent Directory.", baseDir.mkdir());
-
- File dir1 = null;
- String[] files = { "1.tst", "2.tst", "3.tst" };
- try {
- assertEquals("listFiles Should Return An Array Of Length 0.", 0,
- baseDir.listFiles(dirFilter).length);
-
- File file = new File(baseDir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.listFiles(dirFilter));
- } finally {
- file.delete();
- }
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- dir1 = new File(baseDir, "Temp1");
- dir1.mkdir();
-
- // Creating a filter that catches files.
- FileFilter fileFilter = new FileFilter() {
- public boolean accept(File f) {
- return f.isFile();
- }
- };
-
- // Test to see if the correct number of directories are returned.
- File[] directories = baseDir.listFiles(dirFilter);
- assertEquals("Incorrect Number Of Directories Returned.", 1,
- directories.length);
-
- // Test to see if the directory was saved with the correct name.
- assertEquals("Incorrect Directory Returned.", 0, directories[0]
- .compareTo(dir1));
-
- // Test to see if the correct number of files are returned.
- File[] flist = baseDir.listFiles(fileFilter);
- assertEquals("Incorrect Number Of Files Returned.",
- files.length, flist.length);
-
- // Checking to make sure the correct files were are listed in the
- // array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++) {
- check[i] = false;
- }
- for (int i = 0; i < files.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].getName().equals(files[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false) {
- checkCount++;
- }
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir, files[i]);
- f.delete();
- }
- dir1.delete();
- assertTrue("Parent Directory Not Deleted.", baseDir.delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir, files[i]);
- f.delete();
- }
- if (dir1 != null) {
- dir1.delete();
- }
- baseDir.delete();
- }
- }
-
- /**
- * @tests java.io.File#listFiles(java.io.FilenameFilter)
- */
- public void test_listFilesLjava_io_FilenameFilter() throws IOException {
- String base = System.getProperty("java.io.tmpdir");
- // Finding a non-existent directory to create.
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, platformId + String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number (making
- // it a new directory name.)
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, platformId + String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- // Creating a filter that catches "*.tst" files.
- FilenameFilter tstFilter = new FilenameFilter() {
- public boolean accept(File f, String fileName) {
- return fileName.endsWith(".tst");
- }
- };
-
- assertNull("listFiles Should Return Null.", dir.listFiles(tstFilter));
-
- assertTrue("Failed To Create Parent Directory.", dir.mkdir());
-
- String[] files = { "1.tst", "2.tst", "3.tmp" };
- try {
- assertEquals("listFiles Should Return An Array Of Length 0.", 0,
- dir.listFiles(tstFilter).length);
-
- File file = new File(dir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.listFiles(tstFilter));
- } finally {
- file.delete();
- }
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
-
- // Creating a filter that catches "*.tmp" files.
- FilenameFilter tmpFilter = new FilenameFilter() {
- public boolean accept(File f, String fileName) {
- // If the suffix is ".tmp" then send it to the array
- if (fileName.endsWith(".tmp")) {
- return true;
- } else {
- return false;
- }
- }
- };
-
- // Tests to see if the correct number of files were returned.
- File[] flist = dir.listFiles(tstFilter);
- assertEquals("Incorrect Number Of Files Passed Through tstFilter.",
- 2, flist.length);
- for (int i = 0; i < flist.length; i++) {
- assertTrue("File Should Not Have Passed The tstFilter.",
- flist[i].getPath().endsWith(".tst"));
- }
-
- flist = dir.listFiles(tmpFilter);
- assertEquals("Incorrect Number Of Files Passed Through tmpFilter.",
- 1, flist.length);
- assertTrue("File Should Not Have Passed The tmpFilter.", flist[0]
- .getPath().endsWith(".tmp"));
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- assertTrue("Parent Directory Not Deleted.", dir.delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#list(java.io.FilenameFilter)
- */
- public void test_listLjava_io_FilenameFilter() throws IOException {
- String base = tempDirectory.getPath();
- // Old test left behind "garbage files" so this time it creates a
- // directory that is guaranteed not to already exist (and deletes it
- // afterward.)
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, platformId + String.valueOf(dirNumber));
- while (dirExists) {
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- FilenameFilter filter = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return !name.equals("mtzz1.xx");
- }
- };
-
- String[] flist = dir.list(filter);
- assertNull("Method list(FilenameFilter) Should Have Returned Null.",
- flist);
-
- assertTrue("Could not create parent directory for test", dir.mkdir());
-
- String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
- try {
- /*
- * Do not return null when trying to use list(Filename Filter) on a
- * file rather than a directory. All other "list" methods return
- * null for this test case.
- */
- /*
- * File file = new File(dir, "notADir.tst"); try { FileOutputStream
- * fos = new FileOutputStream(file); fos.close(); } catch
- * (IOException e) { fail("Unexpected IOException During Test."); }
- * flist = dir.list(filter); assertNull("listFiles Should Have
- * Returned Null When Used On A File Instead Of A Directory.",
- * flist); file.delete();
- */
-
- flist = dir.list(filter);
- assertEquals("Array Of Length 0 Should Have Returned.", 0,
- flist.length);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
-
- flist = dir.list(filter);
-
- assertEquals("Incorrect list returned", flist.length,
- files.length - 1);
-
- // Checking to make sure the correct files were are listed in the
- // array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++) {
- check[i] = false;
- }
- String[] wantedFiles = { "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
- for (int i = 0; i < wantedFiles.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].equals(wantedFiles[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false) {
- checkCount++;
- }
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- assertTrue("Could not delete parent directory for test.", dir
- .delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#listRoots()
- */
- public void test_listRoots() {
- File[] roots = File.listRoots();
- boolean onUnix = File.separatorChar == '/';
- boolean onWindows = File.separatorChar == '\\';
- if (onUnix) {
- assertEquals("Incorrect Number Of Root Directories.", 1,
- roots.length);
- String fileLoc = roots[0].getPath();
- assertTrue("Incorrect Root Directory Returned.", fileLoc
- .startsWith(File.separator));
- } else if (onWindows) {
- // Need better test for Windows
- assertTrue("Incorrect Number Of Root Directories.",
- roots.length > 0);
- }
- }
-
- /**
- * @tests java.io.File#mkdir()
- */
- public void test_mkdir() throws IOException {
- String base = tempDirectory.getPath();
- // Old test left behind "garbage files" so this time it creates a
- // directory that is guaranteed not to already exist (and deletes it
- // afterward.)
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, String.valueOf(dirNumber));
- while (dirExists) {
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- assertTrue("mkdir failed", dir.mkdir());
- assertTrue("mkdir worked but exists check failed", dir.exists());
- dir.deleteOnExit();
-
- String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars
- String newbase = new String(dir + File.separator);
- StringBuilder sb = new StringBuilder(dir + File.separator);
- StringBuilder sb2 = new StringBuilder(dir + File.separator);
-
- // Test make a long path
- while (dir.getCanonicalPath().length() < 256 - longDirName.length()) {
- sb.append(longDirName + File.separator);
- dir = new File(sb.toString());
- assertTrue("mkdir failed", dir.mkdir());
- assertTrue("mkdir worked but exists check failed", dir.exists());
- dir.deleteOnExit();
- }
-
- while (dir.getCanonicalPath().length() < 256) {
- sb.append(0);
- dir = new File(sb.toString());
- assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
- dir.mkdir());
- assertTrue("mkdir " + dir.getCanonicalPath().length()
- + " worked but exists check failed", dir.exists());
- dir.deleteOnExit();
- }
- dir = new File(sb2.toString());
- // Test make many paths
- while (dir.getCanonicalPath().length() < 256) {
- sb2.append(0);
- dir = new File(sb2.toString());
- assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
- dir.mkdir());
- assertTrue("mkdir " + dir.getCanonicalPath().length()
- + " worked but exists check failed", dir.exists());
- dir.deleteOnExit();
- }
-
- // Regression test for HARMONY-3656
- String[] ss = { "dir\u3400", "abc", "abc@123", "!@#$%^&",
- "~\u4E00!\u4E8C@\u4E09$", "\u56DB\u4E94\u516D",
- "\u4E03\u516B\u4E5D" };
- for (int i = 0; i < ss.length; i++) {
- dir = new File(newbase, ss[i]);
- assertTrue("mkdir " + dir.getCanonicalPath() + " failed",
- dir.mkdir());
- assertTrue("mkdir " + dir.getCanonicalPath()
- + " worked but exists check failed",
- dir.exists());
- dir.deleteOnExit();
- }
- }
-
- /**
- * @tests java.io.File#mkdir()
- *
- * HARMONY-6041
- */
- public void test_mkdir_special_unicode() throws IOException {
- File specialDir = new File(this.tempDirectory,"\u5C73");
- int i = 0;
- while (specialDir.exists()) {
- specialDir = new File("\u5C73" + i);
- ++i;
- }
- assertFalse(specialDir.exists());
- assertTrue(specialDir.mkdir());
- assertTrue(specialDir.exists());
- }
-
- /**
- * @tests java.io.File#mkdirs()
- */
- public void test_mkdirs() {
- String userHome = addTrailingSlash(tempDirectory.getPath());
- File f = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2",
- "p.tst");
- File g = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2");
- File h = new File(userHome + "mdtest" + platformId);
- f.mkdirs();
- try {
- assertTrue("Base Directory not created", h.exists());
- assertTrue("Directories not created", g.exists());
- assertTrue("File not created", f.exists());
- } finally {
- f.delete();
- g.delete();
- h.delete();
- }
- }
-
- /**
- * @tests java.io.File#renameTo(java.io.File)
- */
- public void test_renameToLjava_io_File() throws IOException {
- String base = tempDirectory.getPath();
- File dir = new File(base, platformId);
- dir.mkdir();
- File f = new File(dir, "xxx.xxx");
- File rfile = new File(dir, "yyy.yyy");
- File f2 = new File(dir, "zzz.zzz");
- try {
- FileOutputStream fos = new FileOutputStream(f);
- fos.write(fileString.getBytes());
- fos.close();
- long lengthOfFile = f.length();
-
- rfile.delete(); // in case it already exists
-
- assertTrue("Test 1: File Rename Failed", f.renameTo(rfile));
- assertTrue("Test 2: File Rename Failed.", rfile.exists());
- assertEquals("Test 3: Size Of File Changed.",
- lengthOfFile, rfile.length());
-
- fos = new FileOutputStream(rfile);
- fos.close();
-
- f2.delete(); // in case it already exists
- assertTrue("Test 4: File Rename Failed", rfile.renameTo(f2));
- assertTrue("Test 5: File Rename Failed.", f2.exists());
- } finally {
- f.delete();
- rfile.delete();
- f2.delete();
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#setLastModified(long)
- */
- public void test_setLastModifiedJ() throws IOException {
- File f1 = null;
- try {
- f1 = new File(Support_PlatformFile.getNewPlatformFile(
- "harmony-test-FileTest_setLastModified", ".tmp"));
- f1.createNewFile();
- long orgTime = f1.lastModified();
- // Subtracting 100 000 milliseconds from the orgTime of File f1
- f1.setLastModified(orgTime - 100000);
- long lastModified = f1.lastModified();
- assertEquals("Test 1: LastModifed time incorrect",
- orgTime - 100000, lastModified);
- // Subtracting 10 000 000 milliseconds from the orgTime of File f1
- f1.setLastModified(orgTime - 10000000);
- lastModified = f1.lastModified();
- assertEquals("Test 2: LastModifed time incorrect",
- orgTime - 10000000, lastModified);
- // Adding 100 000 milliseconds to the orgTime of File f1
- f1.setLastModified(orgTime + 100000);
- lastModified = f1.lastModified();
- assertEquals("Test 3: LastModifed time incorrect",
- orgTime + 100000, lastModified);
- // Adding 10 000 000 milliseconds from the orgTime of File f1
- f1.setLastModified(orgTime + 10000000);
- lastModified = f1.lastModified();
- assertEquals("Test 4: LastModifed time incorrect",
- orgTime + 10000000, lastModified);
- // Trying to set time to an exact number
- f1.setLastModified(315550800000L);
- lastModified = f1.lastModified();
- assertEquals("Test 5: LastModified time incorrect",
- 315550800000L, lastModified);
- String osName = System.getProperty("os.name", "unknown");
- if (osName.equals("Windows 2000") || osName.equals("Windows NT")) {
- // Trying to set time to a large exact number
- boolean result = f1.setLastModified(4354837199000L);
- long next = f1.lastModified();
- // Dec 31 23:59:59 EST 2107 is overflow on FAT file systems, and
- // the call fails
- if (result) {
- assertEquals("Test 6: LastModified time incorrect",
- 4354837199000L, next);
- }
- }
- // Trying to set time to a negative number
- try {
- f1.setLastModified(-25);
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- }
- } finally {
- if (f1 != null) {
- f1.delete();
- }
- }
- }
-
- /**
- * @tests java.io.File#setReadOnly()
- */
- public void test_setReadOnly() throws IOException, InterruptedException {
- File f1 = null;
- File f2 = null;
- try {
- f1 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
- f2 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
- f1.setReadOnly();
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f1 Is Not Set To ReadOnly." , !f1.canWrite());
- try {
- // Attempt to write to a file that is setReadOnly.
- new FileOutputStream(f1);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // Expected
- }
- Runtime r = Runtime.getRuntime();
- Process p;
- boolean onUnix = File.separatorChar == '/';
- if (onUnix) {
- p = r.exec("chmod +w " + f1.getAbsolutePath());
- } else {
- p = r.exec("attrib -r \"" + f1.getAbsolutePath() + "\"");
- }
- p.waitFor();
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
- FileOutputStream fos = new FileOutputStream(f1);
- fos.write(fileString.getBytes());
- fos.close();
- assertTrue("File Was Not Able To Be Written To.",
- f1.length() == fileString.length());
- assertTrue("File f1 Did Not Delete", f1.delete());
-
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite());
- fos = new FileOutputStream(f2);
- // Write to a file.
- fos.write(fileString.getBytes());
- fos.close();
- f2.setReadOnly();
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f2 Is Not Set To ReadOnly." , !f2.canWrite());
- try {
- // Attempt to write to a file that has previously been written
- // to.
- // and is now set to read only.
- fos = new FileOutputStream(f2);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // Expected
- }
- r = Runtime.getRuntime();
- if (onUnix) {
- p = r.exec("chmod +w " + f2.getAbsolutePath());
- } else {
- p = r.exec("attrib -r \"" + f2.getAbsolutePath() + "\"");
- }
- p.waitFor();
- assertTrue("File f2 Is Set To ReadOnly.", f2.canWrite());
- fos = new FileOutputStream(f2);
- fos.write(fileString.getBytes());
- fos.close();
- f2.setReadOnly();
- assertTrue("File f2 Did Not Delete", f2.delete());
- // Similarly, trying to delete a read-only directory should succeed
- f2 = new File(tempDirectory, "deltestdir");
- f2.mkdir();
- f2.setReadOnly();
- assertTrue("Directory f2 Did Not Delete", f2.delete());
- assertTrue("Directory f2 Did Not Delete", !f2.exists());
- } finally {
- if (f1 != null) {
- f1.delete();
- }
- if (f2 != null) {
- f2.delete();
- }
- }
- }
-
- /**
- * @tests java.io.File#toString()
- */
- public void test_toString() {
- String fileName = System.getProperty("user.home") + File.separator + "input.tst";
- File f = new File(fileName);
- assertEquals("Incorrect string returned", fileName, f.toString());
-
- if (File.separatorChar == '\\') {
- String result = new File("c:\\").toString();
- assertEquals("Removed backslash", "c:\\", result);
- }
- }
-
- /**
- * @tests java.io.File#toURI()
- */
- public void test_toURI() throws URISyntaxException {
- // Need a directory that exists
- File dir = tempDirectory;
-
- // Test for toURI when the file is a directory.
- String newURIPath = dir.getAbsolutePath();
- newURIPath = newURIPath.replace(File.separatorChar, '/');
- if (!newURIPath.startsWith("/")) {
- newURIPath = "/" + newURIPath;
- }
- if (!newURIPath.endsWith("/")) {
- newURIPath += '/';
- }
-
- URI uri = dir.toURI();
- assertEquals("Test 1A: Incorrect URI Returned.", dir.getAbsoluteFile(), new File(uri));
- assertEquals("Test 1B: Incorrect URI Returned.",
- new URI("file", null, newURIPath, null, null), uri);
-
- // Test for toURI with a file name with illegal chars.
- File f = new File(dir, "te% \u20ac st.tst");
- newURIPath = f.getAbsolutePath();
- newURIPath = newURIPath.replace(File.separatorChar, '/');
- if (!newURIPath.startsWith("/")) {
- newURIPath = "/" + newURIPath;
- }
-
- uri = f.toURI();
- assertEquals("Test 2A: Incorrect URI Returned.",
- f.getAbsoluteFile(), new File(uri));
- assertEquals("Test 2B: Incorrect URI Returned.",
- new URI("file", null, newURIPath, null, null), uri);
-
- // Regression test for HARMONY-3207
- dir = new File(""); // current directory
- uri = dir.toURI();
- assertTrue("Test current dir: URI does not end with slash.", uri
- .toString().endsWith("/"));
- }
-
- /**
- * @tests java.io.File#toURL()
- */
- public void test_toURL() throws MalformedURLException {
- // Need a directory that exists
- File dir = tempDirectory;
-
- // Test for toURL when the file is a directory.
- String newDirURL = dir.getAbsolutePath();
- newDirURL = newDirURL.replace(File.separatorChar, '/');
- if (newDirURL.startsWith("/")) {
- newDirURL = "file:" + newDirURL;
- } else {
- newDirURL = "file:/" + newDirURL;
- }
- if (!newDirURL.endsWith("/")) {
- newDirURL += '/';
- }
- assertEquals("Test 1: Incorrect URL Returned.",
- dir.toURL().toString(), newDirURL);
-
- // Test for toURL with a file.
- File f = new File(dir, "test.tst");
- String newURL = f.getAbsolutePath();
- newURL = newURL.replace(File.separatorChar, '/');
- if (newURL.startsWith("/")) {
- newURL = "file:" + newURL;
- } else {
- newURL = "file:/" + newURL;
- }
- assertEquals("Test 2: Incorrect URL Returned.",
- f.toURL().toString(), newURL);
-
- // Regression test for HARMONY-3207
- dir = new File(""); // current directory
- newDirURL = dir.toURL().toString();
- assertTrue("Test current dir: URL does not end with slash.", newDirURL
- .endsWith("/"));
- }
-
- /**
- * @tests java.io.File#toURI()
- */
- public void test_toURI2() throws URISyntaxException {
- File f = new File(tempDirectory, "a/b/c/../d/e/./f");
-
- String path = f.getAbsolutePath();
- path = path.replace(File.separatorChar, '/');
- if (!path.startsWith("/")) {
- path = "/" + path;
- }
-
- URI uri1 = new URI("file", null, path, null);
- URI uri2 = f.toURI();
- assertEquals("uris not equal", uri1, uri2);
- }
-
- /**
- * @tests java.io.File#toURL()
- */
- public void test_toURL2() throws MalformedURLException {
- File f = new File(tempDirectory, "a/b/c/../d/e/./f");
-
- String path = f.getAbsolutePath();
- path = path.replace(File.separatorChar, '/');
- if (!path.startsWith("/")) {
- path = "/" + path;
- }
-
- URL url1 = new URL("file", "", path);
- URL url2 = f.toURL();
- assertEquals("urls not equal", url1, url2);
- }
-
- /**
- * @tests java.io.File#deleteOnExit()
- */
- /* BEGIN android-removed: we don't have Support_Exec.execJava.
- public void test_deleteOnExit() throws IOException, InterruptedException {
- File dir = new File("dir4filetest");
- dir.mkdir();
- assertTrue(dir.exists());
- File subDir = new File("dir4filetest/subdir");
- subDir.mkdir();
- assertTrue(subDir.exists());
-
- Support_Exec.execJava(new String[] {
- "tests.support.Support_DeleteOnExitTest",
- dir.getAbsolutePath(), subDir.getAbsolutePath() },
- new String[] {}, false);
- assertFalse(dir.exists());
- assertFalse(subDir.exists());
- }
- */
-
- /**
- * @tests serilization
- */
- public void test_objectStreamClass_getFields() throws Exception {
- // Regression for HARMONY-2674
- ObjectStreamClass objectStreamClass = ObjectStreamClass
- .lookup(File.class);
- ObjectStreamField[] objectStreamFields = objectStreamClass.getFields();
- assertEquals(1, objectStreamFields.length);
- ObjectStreamField objectStreamField = objectStreamFields[0];
- assertEquals("path", objectStreamField.getName());
- assertEquals(String.class, objectStreamField.getType());
- }
-
- // Regression test for HARMONY-4493
- public void test_list_withUnicodeFileName() throws Exception {
- File rootDir = new File("P");
- if (!rootDir.exists()) {
- rootDir.mkdir();
- rootDir.deleteOnExit();
- }
-
- String dirName = new String("src\u3400");
- File dir = new File(rootDir, dirName);
- if (!dir.exists()) {
- dir.mkdir();
- dir.deleteOnExit();
- }
- boolean exist = false;
- String[] fileNames = rootDir.list();
- for (String fileName : fileNames) {
- if (dirName.equals(fileName)) {
- exist = true;
- break;
- }
- }
- assertTrue(exist);
- }
-
- /**
- * @tests serialization/deserialization.
- */
- public void test_serialization_self() throws Exception {
- File testFile = new File("test.ser");
- SerializationTest.verifySelf(testFile);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- public void test_serialization_compatibility() throws Exception {
- File file = new File("FileTest.golden.ser");
- SerializationTest.verifyGolden(this, file);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java
deleted file mode 100644
index 642c8dd..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java
+++ /dev/null
@@ -1,537 +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.luni.tests.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CodingErrorAction;
-import java.nio.charset.MalformedInputException;
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-public class InputStreamReaderTest extends TestCase {
-
- static class LimitedByteArrayInputStream extends ByteArrayInputStream {
-
- // A ByteArrayInputStream that only returns a single byte per read
- byte[] bytes;
-
- int count;
-
- public LimitedByteArrayInputStream(int type) {
- super(new byte[0]);
- switch (type) {
- case 0:
- bytes = new byte[] { 0x61, 0x72 };
- break;
- case 1:
- bytes = new byte[] { (byte) 0xff, (byte) 0xfe, 0x61, 0x72 };
- break;
- case 2:
- bytes = new byte[] { '\u001b', '$', 'B', '6', 'e', 'B', 'h',
- '\u001b', '(', 'B' };
- break;
- }
- count = bytes.length;
- }
-
- @Override
- public int available() {
- return count;
- }
-
- @Override
- public int read() {
- if (count == 0) {
- return -1;
- }
- count--;
- return bytes[bytes.length - count];
- }
-
- @Override
- public int read(byte[] buffer, int offset, int length) {
- if (count == 0) {
- return -1;
- }
- if (length == 0) {
- return 0;
- }
- buffer[offset] = bytes[bytes.length - count];
- count--;
- return 1;
- }
- }
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
-
- private InputStream fis;
-
- private InputStream in;
-
- private InputStreamReader is;
-
- private InputStreamReader reader;
-
- private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
-
- /*
- * @see TestCase#setUp()
- */
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- in = new ByteArrayInputStream(source.getBytes("UTF-8"));
- reader = new InputStreamReader(in, "UTF-8");
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- OutputStreamWriter osw = new OutputStreamWriter(bos);
- char[] buf = new char[fileString.length()];
- fileString.getChars(0, fileString.length(), buf, 0);
- osw.write(buf);
- osw.close();
- fis = new ByteArrayInputStream(bos.toByteArray());
- is = new InputStreamReader(fis);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- @Override
- protected void tearDown() throws Exception {
- try {
- in.close();
- is.close();
- fis.close();
- } catch (IOException e) {
- // Ignored
- }
-
- super.tearDown();
- }
-
- /**
- * @tests java.io.InputStreamReader#close()
- */
- public void test_close() throws IOException {
- is.close();
- try {
- is.read();
- fail("Should throw IOException");
- } catch (IOException e) {
- // Expected
- }
-
- reader.close();
- try {
- reader.ready();
- fail("Should throw IOException");
- } catch (IOException e) {
- // Expected
- }
-
- // Should be a no-op
- reader.close();
-
- // Tests after reader closed
- in = new BufferedInputStream(
- this
- .getClass()
- .getClassLoader()
- .getResourceAsStream(
- "org/apache/harmony/luni/tests/java/io/testfile-utf8.txt"));
- reader = new InputStreamReader(in, "utf-8");
- in.close();
- try {
- int count = reader.read(new char[1]);
- fail("count:" + count);
- } catch (IOException e) {
- // Expected
- }
- try {
- reader.read();
- fail();
- } catch (IOException e) {
- // Expected
- }
-
- assertFalse(reader.ready());
- Charset cs = Charset.forName("utf-8");
- assertEquals(cs, Charset.forName(reader.getEncoding()));
- }
-
- /**
- * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
- */
- public void test_ConstructorLjava_io_InputStream() throws IOException {
- try {
- reader = new InputStreamReader(null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- InputStreamReader reader2 = new InputStreamReader(in);
- reader2.close();
- }
-
- /**
- * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream,
- * java.lang.String)
- */
- public void test_ConstructorLjava_io_InputStreamLjava_lang_String()
- throws IOException {
- is = new InputStreamReader(fis, "8859_1");
-
- try {
- is = new InputStreamReader(fis, "Bogus");
- fail("Failed to throw Unsupported Encoding exception");
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
-
- try {
- reader = new InputStreamReader(null, "utf-8");
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- reader = new InputStreamReader(in, (String) null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- reader = new InputStreamReader(in, "");
- fail();
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
- try {
- reader = new InputStreamReader(in, "badname");
- fail();
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
- InputStreamReader reader2 = new InputStreamReader(in, "utf-8");
- assertEquals(Charset.forName(reader2.getEncoding()), Charset
- .forName("utf-8"));
- reader2.close();
- reader2 = new InputStreamReader(in, "utf8");
- assertEquals(Charset.forName(reader2.getEncoding()), Charset
- .forName("utf-8"));
- reader2.close();
- }
-
- /**
- * @tests java.io.InputStreamReader(java.io.InputStream,
- * java.nio.charset.Charset)
- */
- public void test_ConstructorLjava_io_InputStreamLjava_nio_charset_Charset()
- throws IOException {
- Charset cs = Charset.forName("utf-8");
- try {
- reader = new InputStreamReader(null, cs);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- reader = new InputStreamReader(in, (Charset) null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- InputStreamReader reader2 = new InputStreamReader(in, cs);
- assertEquals(Charset.forName(reader2.getEncoding()), cs);
- reader2.close();
- }
-
- /**
- * @tests java.io.InputStreamReader(java.io.InputStream,
- * java.nio.charset.CharsetDecoder)
- */
- public void test_ConstructorLjava_io_InputStreamLjava_nio_charset_CharsetDecoder()
- throws IOException {
- CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();
- try {
- reader = new InputStreamReader(null, decoder);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- reader = new InputStreamReader(in, (CharsetDecoder) null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- InputStreamReader reader2 = new InputStreamReader(in, decoder);
- assertEquals(Charset.forName(reader2.getEncoding()), decoder.charset());
- reader2.close();
- }
-
- /**
- * @tests java.io.InputStreamReader#getEncoding()
- */
- public void test_getEncoding() throws IOException {
- InputStreamReader isr = new InputStreamReader(fis, "8859_1");
- assertEquals("Returned incorrect encoding when setting 8859_1",
- "ISO8859_1", isr.getEncoding());
-
- isr = new InputStreamReader(fis, "ISO-8859-1");
- assertEquals("Returned incorrect encoding when setting ISO-8859-1",
- "ISO8859_1", isr.getEncoding());
-
- byte b[] = new byte[5];
- isr = new InputStreamReader(new ByteArrayInputStream(b), "UTF-16BE");
- isr.close();
- assertNull(isr.getEncoding());
-
- try {
- isr = new InputStreamReader(System.in, "UTF-16BE");
- } catch (UnsupportedEncodingException e) {
- // Ignored
- }
- assertEquals("UnicodeBigUnmarked", isr.getEncoding());
- }
-
- /**
- * @tests java.io.InputStreamReader#read()
- */
- public void test_read() throws IOException {
- assertEquals('T', (char) reader.read());
- assertEquals('h', (char) reader.read());
- assertEquals('i', (char) reader.read());
- assertEquals('s', (char) reader.read());
- assertEquals(' ', (char) reader.read());
- reader.read(new char[source.length() - 5], 0, source.length() - 5);
- assertEquals(-1, reader.read());
-
- int c = is.read();
- assertTrue("returned incorrect char", (char) c == fileString.charAt(0));
- InputStreamReader reader = new InputStreamReader(
- new ByteArrayInputStream(new byte[] { (byte) 0xe8, (byte) 0x9d,
- (byte) 0xa5 }), "UTF8");
- assertTrue("wrong double byte char", reader.read() == '\u8765');
-
- // Regression for HARMONY-166
- InputStream in;
-
- in = new LimitedByteArrayInputStream(0);
- reader = new InputStreamReader(in, "UTF-16BE");
- assertEquals("Incorrect byte UTF-16BE", '\u6172', reader.read());
-
- in = new LimitedByteArrayInputStream(0);
- reader = new InputStreamReader(in, "UTF-16LE");
- assertEquals("Incorrect byte UTF-16BE", '\u7261', reader.read());
-
- in = new LimitedByteArrayInputStream(1);
- reader = new InputStreamReader(in, "UTF-16");
- assertEquals("Incorrect byte UTF-16BE", '\u7261', reader.read());
-
- /*
- * Temporarily commented out due to lack of ISO2022 support in ICU4J 3.8
- * in = new LimitedByteArrayInputStream(2); reader = new
- * InputStreamReader(in, "ISO2022JP"); assertEquals("Incorrect byte
- * ISO2022JP 1", '\u4e5d', reader.read()); assertEquals("Incorrect byte
- * ISO2022JP 2", '\u7b2c', reader.read());
- */
- }
-
- /*
- * Class under test for int read() Regression for Harmony-411
- */
- public void test_read_1() throws IOException {
- // if the decoder is constructed by InputStreamReader itself, the
- // decoder's default error action is REPLACE
- InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(
- new byte[] { -32, -96 }), "UTF-8");
- assertEquals("read() return incorrect value", 65533, isr.read());
-
- InputStreamReader isr2 = new InputStreamReader(
- new ByteArrayInputStream(new byte[] { -32, -96 }), Charset
- .forName("UTF-8"));
- assertEquals("read() return incorrect value", 65533, isr2.read());
-
- // if the decoder is passed in, keep its status intact
- CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- InputStreamReader isr3 = new InputStreamReader(
- new ByteArrayInputStream(new byte[] { -32, -96 }), decoder);
- try {
- isr3.read();
- fail("Should throw MalformedInputException");
- } catch (MalformedInputException e) {
- // expected
- }
-
- CharsetDecoder decoder2 = Charset.forName("UTF-8").newDecoder();
- decoder2.onMalformedInput(CodingErrorAction.IGNORE);
- InputStreamReader isr4 = new InputStreamReader(
- new ByteArrayInputStream(new byte[] { -32, -96 }), decoder2);
- assertEquals("read() return incorrect value", -1, isr4.read());
-
- CharsetDecoder decoder3 = Charset.forName("UTF-8").newDecoder();
- decoder3.onMalformedInput(CodingErrorAction.REPLACE);
- InputStreamReader isr5 = new InputStreamReader(
- new ByteArrayInputStream(new byte[] { -32, -96 }), decoder3);
- assertEquals("read() return incorrect value", 65533, isr5.read());
- }
-
- public void test_read_specialCharset() throws IOException {
- reader.close();
- in = this.getClass().getClassLoader().getResourceAsStream(
- "org/apache/harmony/luni/tests/java/io/testfile-utf8.txt");
- reader = new InputStreamReader(in, "utf-8");
- int c;
- StringBuffer sb = new StringBuffer();
- while ((c = reader.read()) != -1) {
- sb.append((char) c);
- }
- // delete BOM
- assertEquals(source, sb.deleteCharAt(0).toString());
-
- sb.setLength(0);
- reader.close();
- in = this.getClass().getClassLoader().getResourceAsStream(
- "org/apache/harmony/luni/tests/java/io/testfile.txt");
- try {
- reader = new InputStreamReader(in, "gb18030");
- } catch (UnsupportedEncodingException e) {
- System.out
- .println("GB18030 is not supported, abort test InputStreamReaderTest.testSpecialCharsetReading().");
- }
- while ((c = reader.read()) != -1) {
- sb.append((char) c);
- }
- assertEquals(source, sb.toString());
- }
-
- /**
- * @tests java.io.InputStreamReader#read(char[], int, int)
- */
- public void test_read$CII() throws IOException {
- char[] rbuf = new char[100];
- char[] sbuf = new char[100];
- fileString.getChars(0, 100, sbuf, 0);
- is.read(rbuf, 0, 100);
- for (int i = 0; i < rbuf.length; i++) {
- assertTrue("returned incorrect chars", rbuf[i] == sbuf[i]);
- }
-
- // Test successive reads
- byte[] data = new byte[8192 * 2];
- Arrays.fill(data, (byte) 116); // 116 = ISO-8859-1 value for 't'
- ByteArrayInputStream bis = new ByteArrayInputStream(data);
- InputStreamReader isr = new InputStreamReader(bis, "ISO-8859-1");
-
- // One less than the InputStreamReader.BUFFER_SIZE
- char[] buf = new char[8191];
- int bytesRead = isr.read(buf, 0, buf.length);
- assertFalse(-1 == bytesRead);
- bytesRead = isr.read(buf, 0, buf.length);
- assertFalse(-1 == bytesRead);
-
- bis = new ByteArrayInputStream(source.getBytes("UTF-8"));
- isr = new InputStreamReader(in, "UTF-8");
- char[] chars = new char[source.length()];
- assertEquals(source.length() - 3, isr.read(chars, 0, chars.length - 3));
- assertEquals(3, isr.read(chars, 0, 10));
- }
-
- /*
- * Class under test for int read(char[], int, int)
- */
- public void test_read$CII_1() throws IOException {
- try {
- // Throws IndexOutOfBoundsException before NullPointerException
- reader.read(null, -1, 1);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- // Throws NullPointerException before IndexOutOfBoundsException
- reader.read(null, 0, -1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- reader.read(null, 0, 1);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- reader.read(new char[3], -1, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- reader.read(new char[3], 0, -1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- reader.read(new char[3], 1, 3);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- assertEquals(0, reader.read(new char[3], 3, 0));
- char[] chars = new char[source.length()];
- assertEquals(0, reader.read(chars, 0, 0));
- assertEquals(0, chars[0]);
- assertEquals(3, reader.read(chars, 0, 3));
- assertEquals(5, reader.read(chars, 3, 5));
- assertEquals(source.length() - 8, reader.read(chars, 8,
- chars.length - 8));
- assertTrue(Arrays.equals(chars, source.toCharArray()));
- assertEquals(-1, reader.read(chars, 0, chars.length));
- assertTrue(Arrays.equals(chars, source.toCharArray()));
- }
-
- /**
- * @tests java.io.InputStreamReader#ready()
- */
- public void test_ready() throws IOException {
- assertTrue("Ready test failed", is.ready());
- is.read();
- assertTrue("More chars, but not ready", is.ready());
-
- assertTrue(reader.ready());
- reader.read(new char[source.length()]);
- assertFalse(reader.ready());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java
deleted file mode 100644
index 467075f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java
+++ /dev/null
@@ -1,45 +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.luni.tests.java.io;
-
-import java.io.ObjectStreamConstants;
-
-import junit.framework.TestCase;
-
-public class ObjectStreamConstantsTest extends TestCase {
-
- /**
- * @tests java.io.ObjectStreamConstants#TC_ENUM
- */
- public void test_TC_ENUM() {
- assertEquals(126, ObjectStreamConstants.TC_ENUM);
- }
-
- /**
- * @tests java.io.ObjectStreamConstants#SC_ENUM
- */
- public void test_SC_ENUM() {
- assertEquals(16, ObjectStreamConstants.SC_ENUM);
- }
-
- /**
- * @tests java.io.ObjectStreamConstants#TC_MAX
- */
- public void test_TC_MAX() {
- assertEquals(126, ObjectStreamConstants.TC_MAX);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java
deleted file mode 100644
index 5283e46..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java
+++ /dev/null
@@ -1,703 +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.luni.tests.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-
-import junit.framework.TestCase;
-
-public class OutputStreamWriterTest extends TestCase {
-
- private static final int UPPER = 0xd800;
-
- private static final int BUFFER_SIZE = 10000;
-
- private ByteArrayOutputStream out;
-
- private OutputStreamWriter writer;
-
- static private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
-
- static private final String[] MINIMAL_CHARSETS = new String[] { "US-ASCII",
- "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16", "UTF-8" };
-
- OutputStreamWriter osw;
-
- InputStreamReader isr;
-
- private ByteArrayOutputStream fos;
-
- String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
-
- /*
- * @see TestCase#setUp()
- */
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- out = new ByteArrayOutputStream();
- writer = new OutputStreamWriter(out, "utf-8");
-
- fos = new ByteArrayOutputStream();
- osw = new OutputStreamWriter(fos);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- @Override
- protected void tearDown() throws Exception {
- try {
- writer.close();
-
- if (isr != null) {
- isr.close();
- }
- osw.close();
- } catch (Exception e) {
- // Ignored
- }
-
- super.tearDown();
- }
-
- public void testClose() throws Exception {
- writer.flush();
- writer.close();
- try {
- writer.flush();
- fail();
- } catch (IOException e) {
- // Expected
- }
- }
-
- public void testFlush() throws Exception {
- writer.write(source);
- writer.flush();
- String result = out.toString("utf-8");
- assertEquals(source, result);
- }
-
- /*
- * Class under test for void write(char[], int, int)
- */
- public void testWritecharArrayintint() throws IOException {
- char[] chars = source.toCharArray();
-
- // Throws IndexOutOfBoundsException if offset is negative
- try {
- writer.write((char[]) null, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- // throws NullPointerException though count is negative
- try {
- writer.write((char[]) null, 1, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- writer.write((char[]) null, 1, 1);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- writer.write(new char[0], 0, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write(chars, -1, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write(chars, 0, -1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write(chars, 1, chars.length);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- writer.write(chars, 1, 2);
- writer.flush();
- assertEquals("hi", out.toString("utf-8"));
- writer.write(chars, 0, chars.length);
- writer.flush();
- assertEquals("hi" + source, out.toString("utf-8"));
-
- writer.close();
- // After the stream is closed, should throw IOException first
- try {
- writer.write((char[]) null, -1, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /*
- * Class under test for void write(int)
- */
- public void testWriteint() throws IOException {
- writer.write(1);
- writer.flush();
- String str = new String(out.toByteArray(), "utf-8");
- assertEquals("\u0001", str);
-
- writer.write(2);
- writer.flush();
- str = new String(out.toByteArray(), "utf-8");
- assertEquals("\u0001\u0002", str);
-
- writer.write(-1);
- writer.flush();
- str = new String(out.toByteArray(), "utf-8");
- assertEquals("\u0001\u0002\uffff", str);
-
- writer.write(0xfedcb);
- writer.flush();
- str = new String(out.toByteArray(), "utf-8");
- assertEquals("\u0001\u0002\uffff\uedcb", str);
-
- writer.close();
- // After the stream is closed, should throw IOException
- try {
- writer.write(1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /*
- * Class under test for void write(String, int, int)
- */
- public void testWriteStringintint() throws IOException {
- try {
- writer.write((String) null, 1, 1);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- writer.write("", 0, 1);
- fail();
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write("abc", -1, 1);
- fail();
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write("abc", 0, -1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write("abc", 1, 3);
- fail();
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- // Throws IndexOutOfBoundsException before NullPointerException if count
- // is negative
- try {
- writer.write((String) null, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- // Throws NullPointerException before StringIndexOutOfBoundsException
- try {
- writer.write((String) null, -1, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- writer.write("abc", 1, 2);
- writer.flush();
- assertEquals("bc", out.toString("utf-8"));
- writer.write(source, 0, source.length());
- writer.flush();
- assertEquals("bc" + source, out.toString("utf-8"));
-
- writer.close();
- // Throws IndexOutOfBoundsException first if count is negative
- try {
- writer.write((String) null, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write((String) null, -1, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- writer.write("abc", -1, 0);
- fail("should throw StringIndexOutOfBoundsException");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- // Throws IOException
- try {
- writer.write("abc", 0, 1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /*
- * Class under test for void OutputStreamWriter(OutputStream)
- */
- public void testOutputStreamWriterOutputStream() throws IOException {
- try {
- writer = new OutputStreamWriter(null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- OutputStreamWriter writer2 = new OutputStreamWriter(out);
- writer2.close();
- }
-
- /*
- * Class under test for void OutputStreamWriter(OutputStream, String)
- */
- public void testOutputStreamWriterOutputStreamString() throws IOException {
- try {
- writer = new OutputStreamWriter(null, "utf-8");
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- writer = new OutputStreamWriter(out, "");
- fail();
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
- try {
- writer = new OutputStreamWriter(out, "badname");
- fail();
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
- try {
- writer = new OutputStreamWriter(out, (String) null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- OutputStreamWriter writer2 = new OutputStreamWriter(out, "ascii");
- assertEquals(Charset.forName("ascii"), Charset.forName(writer2
- .getEncoding()));
- writer2.close();
- }
-
- /*
- * Class under test for void OutputStreamWriter(OutputStream)
- */
- public void testOutputStreamWriterOutputStreamCharset() throws IOException {
- Charset cs = Charset.forName("ascii");
- try {
- writer = new OutputStreamWriter(null, cs);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- writer = new OutputStreamWriter(out, (Charset) null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- OutputStreamWriter writer2 = new OutputStreamWriter(out, cs);
- assertEquals(cs, Charset.forName(writer2.getEncoding()));
- writer2.close();
- }
-
- /*
- * Class under test for void OutputStreamWriter(OutputStream, String)
- */
- public void testOutputStreamWriterOutputStreamCharsetEncoder()
- throws IOException {
- Charset cs = Charset.forName("ascii");
- CharsetEncoder enc = cs.newEncoder();
- try {
- writer = new OutputStreamWriter(null, enc);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- writer = new OutputStreamWriter(out, (CharsetEncoder) null);
- fail();
- } catch (NullPointerException e) {
- // Expected
- }
- OutputStreamWriter writer2 = new OutputStreamWriter(out, enc);
- assertEquals(cs, Charset.forName(writer2.getEncoding()));
- writer2.close();
- }
-
- public void testGetEncoding() {
- Charset cs = Charset.forName("utf-8");
- assertEquals(cs, Charset.forName(writer.getEncoding()));
- }
-
- public void testHandleEarlyEOFChar_1() throws IOException {
- String str = "All work and no play makes Jack a dull boy\n";
- int NUMBER = 2048;
- int j = 0;
- int len = str.length() * NUMBER;
- char[] strChars = new char[len];
- for (int i = 0; i < NUMBER; ++i) {
- for (int k = 0; k < str.length(); ++k) {
- strChars[j++] = str.charAt(k);
- }
- }
-
- File f = File.createTempFile("one", "by_one");
- f.deleteOnExit();
- FileWriter fw = new FileWriter(f);
- fw.write(strChars);
- fw.close();
- FileInputStream fis = new FileInputStream(f);
- InputStreamReader in = new InputStreamReader(fis);
- for (int offset = 0; offset < strChars.length; ++offset) {
- int b = in.read();
- assertFalse("Early EOF at offset", -1 == b);
- }
- }
-
- public void testHandleEarlyEOFChar_2() throws IOException {
- int capacity = 65536;
- byte[] bytes = new byte[capacity];
- byte[] bs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
- for (int i = 0; i < bytes.length; i++) {
- bytes[i] = bs[i / 8192];
- }
- String inputStr = new String(bytes);
- int len = inputStr.length();
- File f = File.createTempFile("FileWriterBugTest ", null);
- f.deleteOnExit();
- FileWriter writer = new FileWriter(f);
- writer.write(inputStr);
- writer.close();
- long flen = f.length();
-
- FileReader reader = new FileReader(f);
- char[] outChars = new char[capacity];
- int outCount = reader.read(outChars);
- String outStr = new String(outChars, 0, outCount);
-
- assertEquals(len, flen);
- assertEquals(inputStr, outStr);
- }
-
- public void testSingleCharIO() throws Exception {
- InputStreamReader isr = null;
- for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
- try {
- out = new ByteArrayOutputStream();
- writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
-
- int upper = UPPER;
- switch (i) {
- case 0:
- upper = 128;
- break;
- case 1:
- upper = 256;
- break;
- }
-
- for (int c = 0; c < upper; ++c) {
- writer.write(c);
- }
- writer.flush();
- byte[] result = out.toByteArray();
-
- isr = new InputStreamReader(new ByteArrayInputStream(result),
- MINIMAL_CHARSETS[i]);
- for (int expected = 0; expected < upper; ++expected) {
- assertEquals("Error when reading bytes in "
- + MINIMAL_CHARSETS[i], expected, isr.read());
- }
- } finally {
- try {
- isr.close();
- } catch (Exception e) {
- }
- try {
- writer.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
- public void testBlockIO() throws Exception {
- InputStreamReader isr = null;
- char[] largeBuffer = new char[BUFFER_SIZE];
- for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
- try {
- out = new ByteArrayOutputStream();
- writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
-
- int upper = UPPER;
- switch (i) {
- case 0:
- upper = 128;
- break;
- case 1:
- upper = 256;
- break;
- }
-
- int m = 0;
- for (int c = 0; c < upper; ++c) {
- largeBuffer[m++] = (char) c;
- if (m == BUFFER_SIZE) {
- writer.write(largeBuffer);
- m = 0;
- }
- }
- writer.write(largeBuffer, 0, m);
- writer.flush();
- byte[] result = out.toByteArray();
-
- isr = new InputStreamReader(new ByteArrayInputStream(result),
- MINIMAL_CHARSETS[i]);
- int expected = 0, read = 0, j = 0;
- while (expected < upper) {
- if (j == read) {
- read = isr.read(largeBuffer);
- j = 0;
- }
- assertEquals("Error when reading bytes in "
- + MINIMAL_CHARSETS[i], expected++, largeBuffer[j++]);
- }
- } finally {
- try {
- isr.close();
- } catch (Exception e) {
- }
- try {
- writer.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
- */
- public void test_ConstructorLjava_io_OutputStream() {
- assertTrue("Used in tests", true);
- }
-
- /**
- * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
- * java.lang.String)
- */
- public void test_ConstructorLjava_io_OutputStreamLjava_lang_String()
- throws UnsupportedEncodingException {
- osw = new OutputStreamWriter(fos, "8859_1");
- try {
- osw = new OutputStreamWriter(fos, "Bogus");
- fail("Failed to throw Unsupported Encoding exception");
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#close()
- */
- public void test_close() throws IOException {
- osw.close();
-
- try {
- osw.write(testString, 0, testString.length());
- fail("Chars written after close");
- } catch (IOException e) {
- // Expected
- }
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- try {
- OutputStreamWriter writer = new OutputStreamWriter(bout,
- "ISO2022JP");
- writer.write(new char[] { 'a' });
- writer.close();
- // the default is ASCII, there should not be any mode changes
- String converted = new String(bout.toByteArray(), "ISO8859_1");
- assertTrue("invalid conversion 1: " + converted, converted
- .equals("a"));
-
- bout.reset();
- writer = new OutputStreamWriter(bout, "ISO2022JP");
- writer.write(new char[] { '\u3048' });
- writer.flush();
- // the byte sequence should not switch to ASCII mode until the
- // stream is closed
- converted = new String(bout.toByteArray(), "ISO8859_1");
- assertTrue("invalid conversion 2: " + converted, converted
- .equals("\u001b$B$("));
- writer.close();
- converted = new String(bout.toByteArray(), "ISO8859_1");
- assertTrue("invalid conversion 3: " + converted, converted
- .equals("\u001b$B$(\u001b(B"));
-
- bout.reset();
- writer = new OutputStreamWriter(bout, "ISO2022JP");
- writer.write(new char[] { '\u3048' });
- writer.write(new char[] { '\u3048' });
- writer.close();
- // there should not be a mode switch between writes
- assertEquals("invalid conversion 4", "\u001b$B$($(\u001b(B",
- new String(bout.toByteArray(), "ISO8859_1"));
- } catch (UnsupportedEncodingException e) {
- // Can't test missing converter
- System.out.println(e);
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#flush()
- */
- public void test_flush() throws IOException {
- char[] buf = new char[testString.length()];
- osw.write(testString, 0, testString.length());
- osw.flush();
- openInputStream();
- isr.read(buf, 0, buf.length);
- assertTrue("Chars not flushed", new String(buf, 0, buf.length)
- .equals(testString));
- }
-
- /**
- * @tests java.io.OutputStreamWriter#getEncoding()
- */
- public void test_getEncoding() throws IOException {
- try {
- osw = new OutputStreamWriter(fos, "8859_1");
- } catch (UnsupportedEncodingException e) {
- assertEquals("Returned incorrect encoding", "8859_1", osw
- .getEncoding());
- }
-
- OutputStreamWriter out = new OutputStreamWriter(
- new ByteArrayOutputStream(), "UTF-16BE");
- out.close();
-
- String result = out.getEncoding();
- assertNull(result);
-
- out = null;
- try {
- out = new OutputStreamWriter(new ByteArrayOutputStream(),
- "UTF-16BE");
- } catch (UnsupportedEncodingException e) {
- // ok
- }
- result = out.getEncoding();
- assertEquals("UnicodeBigUnmarked", result);
- }
-
- /**
- * @tests java.io.OutputStreamWriter#write(char[], int, int)
- */
- public void test_write$CII() throws IOException {
- char[] buf = new char[testString.length()];
- osw.write(testString, 0, testString.length());
- osw.close();
- openInputStream();
- isr.read(buf, 0, buf.length);
- assertTrue("Incorrect chars returned", new String(buf, 0, buf.length)
- .equals(testString));
- }
-
- /**
- * @tests java.io.OutputStreamWriter#write(int)
- */
- public void test_writeI() throws IOException {
- osw.write('T');
- osw.close();
- openInputStream();
- int c = isr.read();
- assertEquals("Incorrect char returned", 'T', (char) c);
- }
-
- /**
- * @tests java.io.OutputStreamWriter#write(java.lang.String, int, int)
- */
- public void test_writeLjava_lang_StringII() throws IOException {
- char[] buf = new char[testString.length()];
- osw.write(testString, 0, testString.length());
- osw.close();
- openInputStream();
- isr.read(buf);
- assertTrue("Incorrect chars returned", new String(buf, 0, buf.length)
- .equals(testString));
- }
-
- private void openInputStream() {
- isr = new InputStreamReader(new ByteArrayInputStream(fos.toByteArray()));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java
deleted file mode 100644
index c5f19f4..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java
+++ /dev/null
@@ -1,108 +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.luni.tests.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.PushbackInputStream;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(PushbackInputStream.class)
-public class PushBackInputStreamTest extends TestCase {
-
- /*
- * @tests java.io.PushBackInputStream(InputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "read",
- args = {}
- )
- public void test_read() {
- PushbackInputStream str = new PushbackInputStream(null);
- try {
- str.read();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- str = new PushbackInputStream(null, 1);
- try {
- str.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#unread(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unread",
- args = {byte[].class, int.class, int.class}
- )
- public void test_unread$BII() {
- // Regression for HARMONY-49
- try {
- PushbackInputStream pb = new PushbackInputStream(
- new ByteArrayInputStream(new byte[] { 0 }), 2);
- pb.unread(new byte[1], 0, 5);
- fail("Assert 0: should throw IOE");
- } catch (IOException e) {
- // expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- PushbackInputStream pb = new PushbackInputStream(
- new ByteArrayInputStream(new byte[] { 0 }), 2);
- try {
- pb.reset();
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mark",
- args = {int.class}
- )
- public void test_mark() {
- PushbackInputStream pb = new PushbackInputStream(
- new ByteArrayInputStream(new byte[] { 0 }), 2);
- pb.mark(Integer.MAX_VALUE);
- pb.mark(0);
- pb.mark(-1);
- pb.mark(Integer.MIN_VALUE);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java
deleted file mode 100644
index 4cd1f56..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java
+++ /dev/null
@@ -1,984 +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.luni.tests.java.io;
-
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-
-import java.nio.channels.FileChannel;
-import java.nio.channels.NonWritableChannelException;
-
-public class RandomAccessFileTest extends junit.framework.TestCase {
-
- public String fileName;
-
- public boolean ufile = true;
-
- java.io.RandomAccessFile raf;
-
- java.io.File f;
-
- String unihw = "\u0048\u0065\u006C\u0801\u006C\u006F\u0020\u0057\u0081\u006F\u0072\u006C\u0064";
-
- //java.io.FileOutputStream fos;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File,
- * java.lang.String)
- */
- public void test_ConstructorLjava_io_FileLjava_lang_String()
- throws Exception {
- // Test for method java.io.RandomAccessFile(java.io.File,
- // java.lang.String)
- RandomAccessFile raf = new java.io.RandomAccessFile(f, "rw");
- raf.write(20);
- raf.seek(0);
- assertEquals("Incorrect int read/written", 20, raf.read());
- raf.close();
-
- raf = new java.io.RandomAccessFile(f, "rwd");
- raf.write(20);
- raf.seek(0);
- assertEquals("Incorrect int read/written", 20, raf.read());
- raf.close();
-
- raf = new java.io.RandomAccessFile(f, "rws");
- raf.write(20);
- raf.seek(0);
- assertEquals("Incorrect int read/written", 20, raf.read());
- raf.close();
-
- // Regression for HARMONY-50
- File f = File.createTempFile("xxx", "yyy");
- f.deleteOnExit();
- raf = new RandomAccessFile(f, "rws");
- raf.close();
-
- f = File.createTempFile("xxx", "yyy");
- f.deleteOnExit();
- raf = new RandomAccessFile(f, "rwd");
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#RandomAccessFile(java.lang.String,
- * java.lang.String)
- */
- public void test_ConstructorLjava_lang_StringLjava_lang_String()
- throws IOException {
- // Test for method java.io.RandomAccessFile(java.lang.String,
- // java.lang.String)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write("Test".getBytes(), 0, 4);
- raf.close();
-
- raf = new java.io.RandomAccessFile(fileName, "rwd");
- raf.write("Test".getBytes(), 0, 4);
- raf.close();
-
- raf = new java.io.RandomAccessFile(fileName, "rws");
- raf.write("Test".getBytes(), 0, 4);
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#close()
- */
- public void test_close() {
- // Test for method void java.io.RandomAccessFile.close()
- try {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.close();
- raf.write("Test".getBytes(), 0, 4);
- fail("Failed to close file properly");
- } catch (IOException e) {}
- }
-
- /**
- * @tests java.io.RandomAccessFile#getFD()
- */
- public void test_getFD() throws IOException {
- // Test for method java.io.FileDescriptor
- // java.io.RandomAccessFile.getFD()
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- assertTrue("Returned invalid fd", raf.getFD().valid());
-
- raf.close();
- assertFalse("Returned valid fd after close", raf.getFD().valid());
- }
-
- /**
- * @tests java.io.RandomAccessFile#getFilePointer()
- */
- public void test_getFilePointer() throws IOException {
- // Test for method long java.io.RandomAccessFile.getFilePointer()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write(fileString.getBytes(), 0, 1000);
- assertEquals("Incorrect filePointer returned", 1000, raf
- .getFilePointer());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#length()
- */
- public void test_length() throws IOException {
- // Test for method long java.io.RandomAccessFile.length()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write(fileString.getBytes());
- assertEquals("Incorrect length returned", fileString.length(), raf
- .length());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#read()
- */
- public void test_read() throws IOException {
- // Test for method int java.io.RandomAccessFile.read()
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(fileString.getBytes("UTF-8"), 0, fileString.length());
- fos.close();
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- assertEquals("Incorrect bytes returned from read",
- fileString.charAt(0), raf.read());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[])
- */
- public void test_read$B() throws IOException {
- // Test for method int java.io.RandomAccessFile.read(byte [])
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(fileString.getBytes(), 0, fileString.length());
- fos.close();
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- byte[] rbuf = new byte[4000];
- raf.read(rbuf);
- assertEquals("Incorrect bytes returned from read", fileString,
- new String(rbuf, 0, fileString.length()));
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[], int, int)
- */
- public void test_read$BII() throws IOException {
- // Test for method int java.io.RandomAccessFile.read(byte [], int, int)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- byte[] rbuf = new byte[4000];
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(fileString.getBytes(), 0, fileString.length());
- fos.close();
- raf.read(rbuf, 0, fileString.length());
- assertEquals("Incorrect bytes returned from read", fileString,
- new String(rbuf, 0, fileString.length()));
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readBoolean()
- */
- public void test_readBoolean() throws IOException {
- // Test for method boolean java.io.RandomAccessFile.readBoolean()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBoolean(true);
- raf.seek(0);
- assertTrue("Incorrect boolean read/written", raf.readBoolean());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readByte()
- */
- public void test_readByte() throws IOException {
- // Test for method byte java.io.RandomAccessFile.readByte()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeByte(127);
- raf.seek(0);
- assertEquals("Incorrect bytes read/written", 127, raf.readByte());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readChar()
- */
- public void test_readChar() throws IOException {
- // Test for method char java.io.RandomAccessFile.readChar()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeChar('T');
- raf.seek(0);
- assertEquals("Incorrect char read/written", 'T', raf.readChar());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readDouble()
- */
- public void test_readDouble() throws IOException {
- // Test for method double java.io.RandomAccessFile.readDouble()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeDouble(Double.MAX_VALUE);
- raf.seek(0);
- assertEquals("Incorrect double read/written", Double.MAX_VALUE, raf
- .readDouble(), 0);
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readFloat()
- */
- public void test_readFloat() throws IOException {
- // Test for method float java.io.RandomAccessFile.readFloat()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeFloat(Float.MAX_VALUE);
- raf.seek(0);
- assertEquals("Incorrect float read/written", Float.MAX_VALUE, raf
- .readFloat(), 0);
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readFully(byte[])
- */
- public void test_readFully$B() throws IOException {
- // Test for method void java.io.RandomAccessFile.readFully(byte [])
- byte[] buf = new byte[10];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes("HelloWorld");
- raf.seek(0);
- raf.readFully(buf);
- assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
- buf, 0, 10, "UTF-8"));
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readFully(byte[], int, int)
- */
- public void test_readFully$BII() throws IOException {
- // Test for method void java.io.RandomAccessFile.readFully(byte [], int,
- // int)
- byte[] buf = new byte[10];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes("HelloWorld");
- raf.seek(0);
- raf.readFully(buf, 0, buf.length);
- assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
- buf, 0, 10, "UTF-8"));
- try {
- raf.readFully(buf, 0, buf.length);
- fail("Reading past end of buffer did not throw EOFException");
- } catch (EOFException e) {}
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readInt()
- */
- public void test_readInt() throws IOException {
- // Test for method int java.io.RandomAccessFile.readInt()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeInt(Integer.MIN_VALUE);
- raf.seek(0);
- assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf
- .readInt());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readLine()
- */
- public void test_readLine() throws IOException {
- // Test for method java.lang.String java.io.RandomAccessFile.readLine()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- String s = "Goodbye\nCruel\nWorld\n";
- raf.write(s.getBytes("UTF-8"), 0, s.length());
- raf.seek(0);
-
- assertEquals("Goodbye", raf.readLine());
- assertEquals("Cruel", raf.readLine());
- assertEquals("World", raf.readLine());
-
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readLong()
- */
- public void test_readLong() throws IOException {
- // Test for method long java.io.RandomAccessFile.readLong()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeLong(Long.MAX_VALUE);
- raf.seek(0);
- assertEquals("Incorrect long read/written", Long.MAX_VALUE, raf
- .readLong());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readShort()
- */
- public void test_readShort() throws IOException {
- // Test for method short java.io.RandomAccessFile.readShort()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeShort(Short.MIN_VALUE);
- raf.seek(0);
- assertEquals("Incorrect long read/written", Short.MIN_VALUE, raf
- .readShort());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readUnsignedByte()
- */
- public void test_readUnsignedByte() throws IOException {
- // Test for method int java.io.RandomAccessFile.readUnsignedByte()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeByte(-1);
- raf.seek(0);
- assertEquals("Incorrect byte read/written", 255, raf.readUnsignedByte());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readUnsignedShort()
- */
- public void test_readUnsignedShort() throws IOException {
- // Test for method int java.io.RandomAccessFile.readUnsignedShort()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeShort(-1);
- raf.seek(0);
- assertEquals("Incorrect byte read/written", 65535, raf
- .readUnsignedShort());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#readUTF()
- */
- public void test_readUTF() throws IOException {
- // Test for method java.lang.String java.io.RandomAccessFile.readUTF()
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeUTF(unihw);
- raf.seek(0);
- assertEquals("Incorrect utf string read", unihw, raf.readUTF());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#seek(long)
- */
- public void test_seekJ() throws IOException {
- // Test for method void java.io.RandomAccessFile.seek(long)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write(fileString.getBytes(), 0, fileString.length());
- raf.seek(12);
- assertEquals("Seek failed to set filePointer", 12, raf.getFilePointer());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#skipBytes(int)
- */
- public void test_skipBytesI() throws IOException {
- // Test for method int java.io.RandomAccessFile.skipBytes(int)
- byte[] buf = new byte[5];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes("HelloWorld");
- raf.seek(0);
- raf.skipBytes(5);
- raf.readFully(buf);
- assertEquals("Failed to skip bytes", "World", new String(buf, 0, 5, "UTF-8"));
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#write(byte[])
- */
- public void test_write$B() throws IOException {
- // Test for method void java.io.RandomAccessFile.write(byte [])
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
-
- byte[] nullByteArray = null;
- try {
- raf.write(nullByteArray);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- //expected
- }
-
- byte[] rbuf = new byte[4000];
- raf.write(fileString.getBytes());
- raf.close();
-
- try {
- raf.write(nullByteArray);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- //expected
- }
-
- //will not throw IOException if array's length is 0
- raf.write(new byte[0]);
-
- try {
- raf.write(fileString.getBytes());
- fail("should throw IOException");
- } catch (IOException e) {
- //expected
- }
-
- FileInputStream fis = new java.io.FileInputStream(fileName);
- fis.read(rbuf, 0, fileString.length());
- assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0,
- fileString.length()));
- fis.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#write(byte[], int, int)
- */
- public void test_write$BII() throws IOException {
- // Test for method void java.io.RandomAccessFile.write(byte [], int,
- // int)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- byte[] rbuf = new byte[4000];
- raf.write(fileString.getBytes(), 0, fileString.length());
- raf.close();
- FileInputStream fis = new java.io.FileInputStream(fileName);
- fis.read(rbuf, 0, fileString.length());
- assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0,
- fileString.length()));
- fis.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#write(byte[], int, int)
- */
- public void test_write_$BII_Exception() throws IOException {
- raf = new java.io.RandomAccessFile(f, "rw");
- byte[] nullByteArray = null;
- byte[] byteArray = new byte[10];
-
- try {
- raf.write(nullByteArray, -1, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- raf.write(nullByteArray, 0, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- raf.write(nullByteArray, 1, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- raf.write(nullByteArray, 1, 0);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- raf.write(nullByteArray, 1, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- raf.write(byteArray, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- raf.write(byteArray, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- raf.write(byteArray, -1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- raf.write(byteArray, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- raf.write(byteArray, 0, 0);
- raf.write(byteArray, 0, byteArray.length);
- raf.write(byteArray, 1, 0);
- raf.write(byteArray, byteArray.length, 0);
-
- try {
- raf.write(byteArray, byteArray.length + 1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- raf.write(byteArray, byteArray.length + 1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- raf.close();
-
- try {
- raf.write(nullByteArray, -1, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- raf.write(byteArray, -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- raf.write(byteArray, 0, 1);
- fail("should throw IOException");
- } catch (IOException e) {
- //expected
- }
-
- try {
- raf.write(byteArray, 0, byteArray.length);
- fail("should throw IOException");
- } catch (IOException e) {
- //expected
- }
-
- try {
- raf.write(byteArray, 1, 1);
- fail("should throw IOException");
- } catch (IOException e) {
- //expected
- }
-
- try {
- raf.write(byteArray, byteArray.length + 1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- // will not throw IOException if count = 0
- raf.write(byteArray, 0, 0);
- raf.write(byteArray, byteArray.length, 0);
- }
-
-
- /**
- * @tests java.io.RandomAccessFile#write(int)
- */
- public void test_writeI() throws IOException {
- // Test for method void java.io.RandomAccessFile.write(int)
- byte[] rbuf = new byte[4000];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write('t');
- raf.close();
- FileInputStream fis = new java.io.FileInputStream(fileName);
- fis.read(rbuf, 0, 1);
- assertEquals("Incorrect byte written", 't', rbuf[0]);
- fis.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeBoolean(boolean)
- */
- public void test_writeBooleanZ() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeBoolean(boolean)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBoolean(true);
- raf.seek(0);
- assertTrue("Incorrect boolean read/written", raf.readBoolean());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeByte(int)
- */
- public void test_writeByteI() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeByte(int)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeByte(127);
- raf.seek(0);
- assertEquals("Incorrect byte read/written", 127, raf.readByte());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeBytes(java.lang.String)
- */
- public void test_writeBytesLjava_lang_String() throws IOException {
- // Test for method void
- // java.io.RandomAccessFile.writeBytes(java.lang.String)
- byte[] buf = new byte[10];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes("HelloWorld");
- raf.seek(0);
- raf.readFully(buf);
- assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
- buf, 0, 10, "UTF-8"));
- raf.close();
-
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeChar(int)
- */
- public void test_writeCharI() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeChar(int)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeChar('T');
- raf.seek(0);
- assertEquals("Incorrect char read/written", 'T', raf.readChar());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeChars(java.lang.String)
- */
- public void test_writeCharsLjava_lang_String() throws IOException {
- // Test for method void
- // java.io.RandomAccessFile.writeChars(java.lang.String)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeChars("HelloWorld");
- char[] hchars = new char[10];
- "HelloWorld".getChars(0, 10, hchars, 0);
- raf.seek(0);
- for (int i = 0; i < hchars.length; i++)
- assertEquals("Incorrect string written", hchars[i], raf.readChar());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeDouble(double)
- */
- public void test_writeDoubleD() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeDouble(double)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeDouble(Double.MAX_VALUE);
- raf.seek(0);
- assertEquals("Incorrect double read/written", Double.MAX_VALUE, raf
- .readDouble(), 0);
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeFloat(float)
- */
- public void test_writeFloatF() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeFloat(float)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeFloat(Float.MAX_VALUE);
- raf.seek(0);
- assertEquals("Incorrect float read/written", Float.MAX_VALUE, raf
- .readFloat(), 0);
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeInt(int)
- */
- public void test_writeIntI() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeInt(int)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeInt(Integer.MIN_VALUE);
- raf.seek(0);
- assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf
- .readInt());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeLong(long)
- */
- public void test_writeLongJ() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeLong(long)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeLong(Long.MAX_VALUE);
- raf.seek(0);
- assertEquals("Incorrect long read/written", Long.MAX_VALUE, raf
- .readLong());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeShort(int)
- */
- public void test_writeShortI() throws IOException {
- // Test for method void java.io.RandomAccessFile.writeShort(int)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeShort(Short.MIN_VALUE);
- raf.seek(0);
- assertEquals("Incorrect long read/written", Short.MIN_VALUE, raf
- .readShort());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeUTF(java.lang.String)
- */
- public void test_writeUTFLjava_lang_String() throws IOException {
- // Test for method void
- // java.io.RandomAccessFile.writeUTF(java.lang.String)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeUTF(unihw);
- raf.seek(0);
- assertEquals("Incorrect utf string", unihw, raf.readUTF());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#seek(long)
- *
- * Regression for HARMONY-374
- */
- public void test_seekI() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- try {
- raf.seek(-1);
- fail("IOException must be thrown if pos < 0");
- } catch (IOException e) {
- }
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[], int, int)
- *
- * Regression for HARMONY-377
- */
- public void test_readBII() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- try {
- raf.read(new byte[1], -1, 1);
- fail("IndexOutOfBoundsException must be thrown if off <0");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.read(new byte[1], 0, -1);
- fail("IndexOutOfBoundsException must be thrown if len <0");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.read(new byte[1], 0, 5);
- fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.read(new byte[10], Integer.MAX_VALUE, 5);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.read(new byte[10], 5, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
-
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[],int,int)
- */
- public void test_read_$BII_IndexOutOfBoundsException() throws IOException {
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(fileString.getBytes(), 0, fileString.length());
- fos.close();
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- byte[] rbuf = new byte[100];
- raf.close();
- try {
- raf.read(rbuf,-1,0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[],int,int)
- */
- public void test_read_$BII_IOException() throws IOException {
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(fileString.getBytes(), 0, fileString.length());
- fos.close();
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- byte[] rbuf = new byte[100];
- raf.close();
- int read = raf.read(rbuf,0,0);
- assertEquals(0,read);
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[])
- */
- public void test_read_$B_IOException() throws IOException {
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(fileString.getBytes(), 0, fileString.length());
- fos.close();
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- byte[] rbuf = new byte[0];
- raf.close();
- int read = raf.read(rbuf);
- assertEquals(0,read);
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[],int,int)
- */
- public void test_read_$BII_NullPointerException() throws IOException {
- File f = File.createTempFile("tmp", "tmp");
- f.deleteOnExit();
- RandomAccessFile raf = new RandomAccessFile(f, "r");
- byte[] rbuf = null;
- try {
- raf.read(rbuf, 0, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#write(byte[], int, int)
- *
- * Regression for HARMONY-377
- */
- public void test_writeBII() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- try {
- raf.write(new byte[1], -1, 1);
- fail("IndexOutOfBoundsException must be thrown if off <0");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.write(new byte[1], 0, -1);
- fail("IndexOutOfBoundsException must be thrown if len <0");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.write(new byte[1], 0, 5);
- fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.write(new byte[10], Integer.MAX_VALUE, 5);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- raf.write(new byte[10], 5, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
- raf.close();
- }
-
- /**
- * Regression for HARMONY-69
- */
- public void testRandomAccessFile_String_String() throws IOException {
- f.createNewFile();
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- FileChannel fcr = raf.getChannel();
-
- try {
- fcr.lock(0L, Long.MAX_VALUE, false);
- fail("NonWritableChannelException expected!");
- } catch (NonWritableChannelException e) {}
- raf.close();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
- f = File.createTempFile("raf", "tst");
- if (!f.delete()) {
- fail("Unable to delete test file : " + f);
- }
- fileName = f.getAbsolutePath();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- * @throws Exception
- */
- protected void tearDown() throws Exception {
- if (f.exists()) {
- f.delete();
- }
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java
deleted file mode 100644
index f818917..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java
+++ /dev/null
@@ -1,379 +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.luni.tests.java.io;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.nio.CharBuffer;
-
-import junit.framework.TestCase;
-import tests.support.Support_ASimpleReader;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(Reader.class)
-public class ReaderTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "Reader",
- args = {}
- )
- public void test_Reader() {
- MockReader r = new MockReader();
- assertTrue("Test 1: Lock has not been set correctly.", r.lockSet(r));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "Reader",
- args = {java.lang.Object.class}
- )
- public void test_Reader_CharBuffer_null() throws IOException {
- String s = "MY TEST STRING";
- MockReader mockReader = new MockReader(s.toCharArray());
- CharBuffer charBuffer = null;
- try {
- mockReader.read(charBuffer);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- //expected;
- }
- }
-
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "Reader",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- })
- public void test_Reader_CharBuffer_ZeroChar() throws IOException {
- // If the charBuffer has a capacity of 0, then the number of char read
- // to the CharBuffer is 0. Furthermore, the MockReader is intact in
- // its content.
- String s = "MY TEST STRING";
- char[] srcBuffer = s.toCharArray();
- MockReader mockReader = new MockReader(srcBuffer);
- CharBuffer charBuffer = CharBuffer.allocate(0);
- int result = mockReader.read(charBuffer);
- assertEquals(0, result);
- char[] destBuffer = new char[srcBuffer.length];
- mockReader.read(destBuffer);
- assertEquals(s, String.valueOf(destBuffer));
- }
-
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "Reader",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- })
- public void test_Reader_CharBufferChar() throws IOException {
- String s = "MY TEST STRING";
- char[] srcBuffer = s.toCharArray();
- final int CHARBUFFER_SIZE = 10;
- MockReader mockReader = new MockReader(srcBuffer);
- CharBuffer charBuffer = CharBuffer.allocate(CHARBUFFER_SIZE);
- charBuffer.append('A');
- final int CHARBUFFER_REMAINING = charBuffer.remaining();
- int result = mockReader.read(charBuffer);
- assertEquals(CHARBUFFER_REMAINING, result);
- charBuffer.rewind();
- assertEquals(s.substring(0, CHARBUFFER_REMAINING), charBuffer
- .subSequence(CHARBUFFER_SIZE - CHARBUFFER_REMAINING,
- CHARBUFFER_SIZE).toString());
- char[] destBuffer = new char[srcBuffer.length - CHARBUFFER_REMAINING];
- mockReader.read(destBuffer);
- assertEquals(s.substring(CHARBUFFER_REMAINING), String
- .valueOf(destBuffer));
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- CharBuffer buf = CharBuffer.allocate(4);
- assertEquals("Wrong return value!", 4, simple.read(buf));
- buf.rewind();
- assertEquals("Wrong stuff read!", "Bla ", String.valueOf(buf));
- simple.read(buf);
- buf.rewind();
- assertEquals("Wrong stuff read!", "bla,", String.valueOf(buf));
- simple.throwExceptionOnNextUse = true;
- try {
- simple.read(buf);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {char[].class}
- )
- public void test_Read_$C() throws IOException {
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- char[] buf = new char[4];
- assertEquals("Wrong return value!", 4, simple.read(buf));
- assertEquals("Wrong stuff read!", "Bla ", new String(buf));
- simple.read(buf);
- assertEquals("Wrong stuff read!", "bla,", new String(buf));
- simple.throwExceptionOnNextUse = true;
- try {
- simple.read(buf);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.io.Reader#mark(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mark",
- args = {int.class}
- )
- public void test_mark() {
- MockReader mockReader = new MockReader();
- try {
- mockReader.mark(0);
- fail("Should throw IOException for Reader do not support mark");
- } catch (IOException e) {
- // Excepted
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- assertFalse("markSupported must return false", new MockReader().markSupported());
- }
-
- /**
- * @tests {@link java.io.Reader#read()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- MockReader reader = new MockReader();
-
- // return -1 when the stream is null;
- assertEquals("Should be equal to -1", -1, reader.read());
-
- String string = "MY TEST STRING";
- char[] srcBuffer = string.toCharArray();
- MockReader mockReader = new MockReader(srcBuffer);
-
- // normal read
- for (char c : srcBuffer) {
- assertEquals("Should be equal to \'" + c + "\'", c, mockReader
- .read());
- }
-
- // return -1 when read Out of Index
- mockReader.read();
- assertEquals("Should be equal to -1", -1, reader.read());
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- int res;
- res = simple.read();
- assertEquals("Wrong stuff read!", 'B', res);
- res = simple.read();
- assertEquals("Wrong stuff read!", 'l', res);
- simple.throwExceptionOnNextUse = true;
- try {
- simple.read();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.io.Reader#ready()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ready",
- args = {}
- )
- public void test_ready() throws IOException {
- MockReader mockReader = new MockReader();
- assertFalse("Should always return false", mockReader.ready());
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- simple.throwExceptionOnNextUse = true;
- try {
- simple.ready();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.io.Reader#reset()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() throws IOException {
- MockReader mockReader = new MockReader();
- try {
- mockReader.reset();
- fail("Should throw IOException");
- } catch (IOException e) {
- // Excepted
- }
- }
-
- /**
- * @tests {@link java.io.Reader#skip(long)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {long.class}
- )
- public void test_skip() throws IOException {
- String string = "MY TEST STRING";
- char[] srcBuffer = string.toCharArray();
- int length = srcBuffer.length;
- MockReader mockReader = new MockReader(srcBuffer);
- assertEquals("Should be equal to \'M\'", 'M', mockReader.read());
-
- // normal skip
- mockReader.skip(length / 2);
- assertEquals("Should be equal to \'S\'", 'S', mockReader.read());
-
- // try to skip a bigger number of characters than the total
- // Should do nothing
- mockReader.skip(length);
-
- // try to skip a negative number of characters throw IllegalArgumentException
- try {
- mockReader.skip(-1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Excepted
- }
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- char[] buf = new char[4];
- simple.read(buf);
- assertEquals("Wrong stuff read!", "Bla ", new String(buf));
- simple.skip(5);
- simple.read(buf);
- assertEquals("Wrong stuff read!", "what", new String(buf));
- simple.throwExceptionOnNextUse = true;
- try {
- simple.skip(1);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- class MockReader extends Reader {
-
- private char[] contents;
-
- private int current_offset = 0;
-
- private int length = 0;
-
- public MockReader() {
- super();
- }
-
- public MockReader(char[] data) {
- contents = data;
- length = contents.length;
- }
-
- @Override
- public void close() throws IOException {
-
- contents = null;
- }
-
- @Override
- public int read(char[] buf, int offset, int count) throws IOException {
-
- if (null == contents) {
- return -1;
- }
- if (length <= current_offset) {
- return -1;
- }
- if (buf.length < offset + count) {
- throw new IndexOutOfBoundsException();
- }
-
- count = Math.min(count, length - current_offset);
- for (int i = 0; i < count; i++) {
- buf[offset + i] = contents[current_offset + i];
- }
- current_offset += count;
- return count;
- }
-
- public boolean lockSet(Object o) {
- return (lock == o);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java
deleted file mode 100644
index e08b868..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java
+++ /dev/null
@@ -1,148 +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.luni.tests.java.io;
-
-import java.io.IOException;
-import java.io.Writer;
-
-import junit.framework.TestCase;
-
-public class WriterTest extends TestCase {
-
- /**
- * @tests java.io.Writer#append(char)
- */
- public void test_appendChar() throws IOException {
- char testChar = ' ';
- MockWriter writer = new MockWriter(20);
- writer.append(testChar);
- assertEquals(String.valueOf(testChar), String.valueOf(writer
- .getContents()));
- writer.close();
- }
-
- /**
- * @tests java.io.Writer#append(CharSequence)
- */
- public void test_appendCharSequence() throws IOException {
- String testString = "My Test String";
- MockWriter writer = new MockWriter(20);
- writer.append(testString);
- assertEquals(testString, String.valueOf(writer.getContents()));
- writer.close();
-
- }
-
- /**
- * @tests java.io.Writer#append(CharSequence, int, int)
- */
- public void test_appendCharSequenceIntInt() throws IOException {
- String testString = "My Test String";
- MockWriter writer = new MockWriter(20);
- writer.append(testString, 1, 3);
- assertEquals(testString.substring(1, 3), String.valueOf(writer
- .getContents()));
- writer.close();
-
- }
-
-
-
- /**
- * @tests java.io.Writer#write(String)
- */
- public void test_writeLjava_lang_String() throws IOException {
- // Regression for HARMONY-51
- Object lock = new Object();
- Writer wr = new MockLockWriter(lock);
- wr.write("Some string");
- wr.close();
- }
-
- class MockLockWriter extends Writer {
- final Object myLock;
-
- MockLockWriter(Object lock) {
- super(lock);
- myLock = lock;
- }
-
- @Override
- public synchronized void close() throws IOException {
- // do nothing
- }
-
- @Override
- public synchronized void flush() throws IOException {
- // do nothing
- }
-
- @Override
- public void write(char[] arg0, int arg1, int arg2) throws IOException {
- assertTrue(Thread.holdsLock(myLock));
- }
- }
-
-
- class MockWriter extends Writer {
- private char[] contents;
-
- private int length;
-
- private int offset;
-
- MockWriter(int capacity) {
- contents = new char[capacity];
- length = capacity;
- offset = 0;
- }
-
- public synchronized void close() throws IOException {
- flush();
- contents = null;
- }
-
- public synchronized void flush() throws IOException {
- // do nothing
- }
-
- public void write(char[] buffer, int offset, int count)
- throws IOException {
- if (null == contents) {
- throw new IOException();
- }
- if (offset < 0 || count < 0 || offset >= buffer.length) {
- throw new IndexOutOfBoundsException();
- }
- count = Math.min(count, buffer.length - offset);
- count = Math.min(count, this.length - this.offset);
- for (int i = 0; i < count; i++) {
- contents[this.offset + i] = buffer[offset + i];
- }
- this.offset += count;
-
- }
-
- public char[] getContents() {
- char[] result = new char[offset];
- for (int i = 0; i < offset; i++) {
- result[i] = contents[i];
- }
- return result;
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java
index 339d76c..f276ec7 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java
@@ -711,30 +711,20 @@
method = "getLocalizedInputStream",
args = {java.io.InputStream.class}
)
- public void test_getLocalizedInputStream() {
+ public void test_getLocalizedInputStream() throws Exception {
String simpleString = "Heart \u2f3c";
- byte[] expected = {72, 0, 101, 0, 97, 0, 114, 0, 116, 0, 32, 0, 60, 47};
+ byte[] expected = simpleString.getBytes("UTF-8");
byte[] returned = new byte[expected.length];
- System.setProperty("file.encoding", "UTF-16LE");
+ ByteArrayInputStream bais = new ByteArrayInputStream(
+ simpleString.getBytes("UTF-8"));
- try {
- ByteArrayInputStream bais = new ByteArrayInputStream(
- simpleString.getBytes("UTF-8"));
+ InputStream lcIn =
+ Runtime.getRuntime().getLocalizedInputStream(bais);
+ lcIn.read(returned);
- InputStream lcIn =
- Runtime.getRuntime().getLocalizedInputStream(bais);
- try {
- lcIn.read(returned);
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
-
- assertTrue("wrong result for String: " + simpleString,
- Arrays.equals(expected, returned));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException was thrown.");
- }
+ assertTrue("wrong result for String: " + simpleString,
+ Arrays.equals(expected, returned));
}
@SuppressWarnings("deprecation")
@@ -744,35 +734,23 @@
method = "getLocalizedOutputStream",
args = {java.io.OutputStream.class}
)
- public void test_getLocalizedOutputStream() {
+ public void test_getLocalizedOutputStream() throws IOException {
String simpleString = "Heart \u2f3c";
- byte[] expected = {72, 0, 101, 0, 97, 0, 114, 0, 116, 0, 32, 0, 60, 47};
- byte[] returned;
+ byte[] expected = simpleString.getBytes("UTF-8");
- String oldEncoding = System.getProperty("file.encoding");
- System.setProperty("file.encoding", "UTF-16LE");
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ OutputStream lcOut =
+ Runtime.getRuntime().getLocalizedOutputStream(out);
+ lcOut.write(simpleString.getBytes("UTF-8"));
+ lcOut.flush();
+ lcOut.close();
- OutputStream lcOut =
- Runtime.getRuntime().getLocalizedOutputStream(out);
- try {
- lcOut.write(simpleString.getBytes("UTF-8"));
- lcOut.flush();
- lcOut.close();
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
+ byte[] returned = out.toByteArray();
- returned = out.toByteArray();
-
- assertTrue("wrong result for String: " + returned.toString() +
- " expected string: " + expected.toString(),
- Arrays.equals(expected, returned));
- } finally {
- System.setProperty("file.encoding", oldEncoding);
- }
+ assertTrue("wrong result for String: " + returned.toString() +
+ " expected string: " + expected.toString(),
+ Arrays.equals(expected, returned));
}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java
deleted file mode 100644
index 572f681..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java
+++ /dev/null
@@ -1,392 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.Buffer;
-import java.nio.ByteBuffer;
-import java.nio.InvalidMarkException;
-
-import junit.framework.TestCase;
-
-/**
- * Tests a java.nio.Buffer instance.
- */
-@TestTargetClass(java.nio.Buffer.class)
-public abstract class AbstractBufferTest extends TestCase {
-
- protected Buffer baseBuf;
- protected int capacity;
-
- protected void setUp() throws Exception{
- super.setUp();
- capacity = 10;
- baseBuf = ByteBuffer.allocate(10);
- }
-
- protected void tearDown() throws Exception{
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "capacity",
- args = {}
- )
- public void testCapacity() {
- assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit()
- && baseBuf.limit() <= baseBuf.capacity());
- assertEquals(capacity, baseBuf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void testClear() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- Buffer ret = baseBuf.clear();
- assertSame(ret, baseBuf);
- assertEquals(0, baseBuf.position());
- assertEquals(baseBuf.limit(), baseBuf.capacity());
- try {
- baseBuf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "flip",
- args = {}
- )
- public void testFlip() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- baseBuf.mark();
-
- Buffer ret = baseBuf.flip();
- assertSame(ret, baseBuf);
- assertEquals(0, baseBuf.position());
- assertEquals(oldPosition, baseBuf.limit());
- try {
- baseBuf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hasRemaining",
- args = {}
- )
- public void testHasRemaining() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- assertEquals(baseBuf.hasRemaining(), baseBuf.position() < baseBuf.limit());
- baseBuf.position(baseBuf.limit());
- assertFalse(baseBuf.hasRemaining());
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public abstract void testIsReadOnly();
-
- /*
- * Class under test for int limit()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "limit",
- args = {}
- )
- public void testLimit() {
- assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit()
- && baseBuf.limit() <= baseBuf.capacity());
- assertEquals(capacity, baseBuf.limit());
- }
-
- /*
- * Class under test for Buffer limit(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "limit",
- args = {int.class}
- )
- public void testLimitint() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- Buffer ret = baseBuf.limit(baseBuf.limit());
- assertSame(ret, baseBuf);
-
- baseBuf.mark();
- baseBuf.limit(baseBuf.capacity());
- assertEquals(baseBuf.limit(), baseBuf.capacity());
- // position should not change
- assertEquals(oldPosition, baseBuf.position());
- // mark should be valid
- baseBuf.reset();
-
- assertTrue("The buffer capacity was 0", baseBuf.capacity() > 0);
- baseBuf.limit(baseBuf.capacity());
- baseBuf.position(baseBuf.capacity());
- baseBuf.mark();
- baseBuf.limit(baseBuf.capacity() - 1);
- // position should be the new limit
- assertEquals(baseBuf.limit(), baseBuf.position());
- // mark should be invalid
- try {
- baseBuf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- try {
- baseBuf.limit(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- baseBuf.limit(baseBuf.capacity() + 1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "mark",
- args = {}
- )
- public void testMark() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- Buffer ret = baseBuf.mark();
- assertSame(ret, baseBuf);
-
- baseBuf.mark();
- baseBuf.position(baseBuf.limit());
- baseBuf.reset();
- assertEquals(oldPosition, baseBuf.position());
-
- baseBuf.mark();
- baseBuf.position(baseBuf.limit());
- baseBuf.reset();
- assertEquals(oldPosition, baseBuf.position());
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- /*
- * Class under test for int position()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "position",
- args = {}
- )
- public void testPosition() {
- assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit()
- && baseBuf.limit() <= baseBuf.capacity());
- assertEquals(0, baseBuf.position());
- }
-
- /*
- * Class under test for Buffer position(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "position",
- args = {int.class}
- )
- public void testPositionint() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- try {
- baseBuf.position(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- baseBuf.position(baseBuf.limit() + 1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- baseBuf.mark();
- baseBuf.position(baseBuf.position());
- baseBuf.reset();
- assertEquals(oldPosition, baseBuf.position());
-
- baseBuf.position(0);
- assertEquals(0, baseBuf.position());
- baseBuf.position(baseBuf.limit());
- assertEquals(baseBuf.limit(), baseBuf.position());
-
- assertTrue("The buffer capacity was 0.", baseBuf.capacity() > 0);
- baseBuf.limit(baseBuf.capacity());
- baseBuf.position(baseBuf.limit());
- baseBuf.mark();
- baseBuf.position(baseBuf.limit() - 1);
- assertEquals(baseBuf.limit() - 1, baseBuf.position());
- // mark should be invalid
- try {
- baseBuf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- Buffer ret = baseBuf.position(0);
- assertSame(ret, baseBuf);
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "remaining",
- args = {}
- )
- public void testRemaining() {
- assertEquals(baseBuf.remaining(), baseBuf.limit() - baseBuf.position());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void testReset() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- baseBuf.mark();
- baseBuf.position(baseBuf.limit());
- baseBuf.reset();
- assertEquals(oldPosition, baseBuf.position());
-
- baseBuf.mark();
- baseBuf.position(baseBuf.limit());
- baseBuf.reset();
- assertEquals(oldPosition, baseBuf.position());
-
- Buffer ret = baseBuf.reset();
- assertSame(ret, baseBuf);
-
- baseBuf.clear();
- try {
- baseBuf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "rewind",
- args = {}
- )
- public void testRewind() {
- // save state
- int oldPosition = baseBuf.position();
- int oldLimit = baseBuf.limit();
-
- Buffer ret = baseBuf.rewind();
- assertEquals(0, baseBuf.position());
- assertSame(ret, baseBuf);
- try {
- baseBuf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // restore state
- baseBuf.limit(oldLimit);
- baseBuf.position(oldPosition);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java
deleted file mode 100644
index d1dcd3b..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java
+++ /dev/null
@@ -1,89 +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.nio.tests.java.nio;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Test suite for java.nio package
- *
- */
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("Tests for java.nio");
- //$JUnit-BEGIN$
- suite.addTestSuite(BufferOverflowExceptionTest.class);
- suite.addTestSuite(BufferUnderflowExceptionTest.class);
- suite.addTestSuite(ByteOrderTest.class);
- suite.addTestSuite(DirectByteBufferTest.class);
- suite.addTestSuite(DirectCharBufferTest.class);
- suite.addTestSuite(DirectDoubleBufferTest.class);
- suite.addTestSuite(DirectFloatBufferTest.class);
- suite.addTestSuite(DirectIntBufferTest.class);
- suite.addTestSuite(DirectLongBufferTest.class);
- suite.addTestSuite(DirectShortBufferTest.class);
- suite.addTestSuite(DuplicateDirectByteBufferTest.class);
- suite.addTestSuite(DuplicateHeapByteBufferTest.class);
- suite.addTestSuite(DuplicateWrappedByteBufferTest.class);
- suite.addTestSuite(HeapByteBufferTest.class);
- suite.addTestSuite(HeapCharBufferTest.class);
- suite.addTestSuite(HeapDoubleBufferTest.class);
- suite.addTestSuite(HeapFloatBufferTest.class);
- suite.addTestSuite(HeapIntBufferTest.class);
- suite.addTestSuite(HeapLongBufferTest.class);
- suite.addTestSuite(HeapShortBufferTest.class);
- suite.addTestSuite(InvalidMarkExceptionTest.class);
- suite.addTestSuite(MappedByteBufferTest.class);
- suite.addTestSuite(ReadOnlyBufferExceptionTest.class);
- suite.addTestSuite(ReadOnlyCharBufferTest.class);
- suite.addTestSuite(ReadOnlyDirectByteBufferTest.class);
- suite.addTestSuite(ReadOnlyDoubleBufferTest.class);
- suite.addTestSuite(ReadOnlyFloatBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapByteBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapCharBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapDoubleBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapFloatBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapIntBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapLongBufferTest.class);
- suite.addTestSuite(ReadOnlyHeapShortBufferTest.class);
- suite.addTestSuite(ReadOnlyIntBufferTest.class);
- suite.addTestSuite(ReadOnlyLongBufferTest.class);
- suite.addTestSuite(ReadOnlyShortBufferTest.class);
- suite.addTestSuite(ReadOnlyWrappedByteBufferTest.class);
- suite.addTestSuite(ReadOnlyWrappedCharBufferTest1.class);
- suite.addTestSuite(ReadOnlyWrappedDoubleBufferTest.class);
- suite.addTestSuite(ReadOnlyWrappedFloatBufferTest.class);
- suite.addTestSuite(ReadOnlyWrappedIntBufferTest.class);
- suite.addTestSuite(ReadOnlyWrappedLongBufferTest.class);
- suite.addTestSuite(ReadOnlyWrappedShortBufferTest.class);
- suite.addTestSuite(SliceDirectByteBufferTest.class);
- suite.addTestSuite(SliceHeapByteBufferTest.class);
- suite.addTestSuite(SliceWrappedByteBufferTest.class);
- suite.addTestSuite(WrappedByteBufferTest.class);
- suite.addTestSuite(WrappedCharBufferTest1.class);
- suite.addTestSuite(WrappedCharBufferTest2.class);
- suite.addTestSuite(WrappedDoubleBufferTest.class);
- suite.addTestSuite(WrappedFloatBufferTest.class);
- suite.addTestSuite(WrappedIntBufferTest.class);
- suite.addTestSuite(WrappedLongBufferTest.class);
- suite.addTestSuite(WrappedShortBufferTest.class);
- //$JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java
deleted file mode 100644
index 4951d1d..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java
+++ /dev/null
@@ -1,92 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.BufferOverflowException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(BufferOverflowException.class)
-public class BufferOverflowExceptionTest extends TestCase {
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility. And tests default constructor",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "BufferOverflowException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new BufferOverflowException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "BufferOverflowException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new BufferOverflowException());
- }
-
- /**
- *@tests {@link java.nio.BufferOverflowException#BufferOverflowException()}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "BufferOverflowException",
- args = {}
- )
- public void test_Constructor() {
- BufferOverflowException exception = new BufferOverflowException();
- assertNull(exception.getMessage());
- assertNull(exception.getLocalizedMessage());
- assertNull(exception.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java
deleted file mode 100644
index 72525a4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java
+++ /dev/null
@@ -1,95 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.BufferUnderflowException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for BufferUnderflowException
- */
-@TestTargetClass(BufferUnderflowException.class)
-public class BufferUnderflowExceptionTest extends TestCase {
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "BufferUnderflowException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new BufferUnderflowException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "BufferUnderflowException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new BufferUnderflowException());
- }
-
- /**
- *@tests {@link java.nio.BufferUnderflowException#BufferUnderflowException()}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "BufferUnderflowException",
- args = {}
- )
- public void test_Constructor() {
- BufferUnderflowException exception = new BufferUnderflowException();
- assertNull(exception.getMessage());
- assertNull(exception.getLocalizedMessage());
- assertNull(exception.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java
deleted file mode 100644
index 82bf938..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java
+++ /dev/null
@@ -1,2822 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.CharBuffer;
-import java.nio.DoubleBuffer;
-import java.nio.FloatBuffer;
-import java.nio.IntBuffer;
-import java.nio.InvalidMarkException;
-import java.nio.LongBuffer;
-import java.nio.ReadOnlyBufferException;
-import java.nio.ShortBuffer;
-import java.util.Arrays;
-
-/**
- * Tests java.nio.ByteBuffer
- *
- */
-@TestTargetClass(ByteBuffer.class)
-public abstract class ByteBufferTest extends AbstractBufferTest {
- protected static final int SMALL_TEST_LENGTH = 5;
- protected static final int BUFFER_LENGTH = 250;
-
- protected ByteBuffer buf;
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocate(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static ByteBuffer allocate(int capacity)
- * test covers following usecases:
- * 1. case for check ByteBuffer testBuf properties
- * 2. case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: ByteBuffer testBuf properties is satisfy the conditions
- // specification
- ByteBuffer testBuf = ByteBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = ByteBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = ByteBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /*
- * test for method static ByteBuffer allocateDirect(int capacity)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocateDirect",
- args = {int.class}
- )
- public void test_AllocateDirectI() {
- // case: ByteBuffer testBuf properties is satisfy the conditions
- // specification
- ByteBuffer testBuf = ByteBuffer.allocateDirect(20);
- assertEquals(0, testBuf.position());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = ByteBuffer.allocateDirect(0);
- assertEquals(0, testBuf.position());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- try {
- testBuf.array();
- fail("Didn't throw expected UnsupportedOperationException.");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- try {
- testBuf.arrayOffset();
- fail("Didn't throw expected UnsupportedOperationException.");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- // case: expected IllegalArgumentException
- try {
- testBuf = ByteBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- byte array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- byte array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = (byte) i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- ByteBuffer wrapped = ByteBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- loadTestData1(buf);
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- ByteBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(0, readonly.position());
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(0, buf.position());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("Fails on RI. See comment below")
- public void testCompact() {
- if (buf.isReadOnly()) {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- ByteBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.capacity(), buf.position());
- assertEquals(buf.capacity(), buf.limit());
- assertContentLikeTestData1(buf, 0, (byte) 0, buf.capacity());
- try {
- // Fails on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact(). So RI doesn't reset
- // mark position
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(0, buf.position());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (byte) 0, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
- buf.position(1);
- buf.limit(SMALL_TEST_LENGTH);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(4, buf.position());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (byte) 1, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.ByteBuffer.class}
- )
- public void testCompareTo() {
- // compare to self
- assertEquals(0, buf.compareTo(buf));
-
- // normal cases
- if (!buf.isReadOnly()) {
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
- buf.clear();
- ByteBuffer other = ByteBuffer.allocate(buf.capacity());
- loadTestData1(buf);
- loadTestData1(other);
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- other.limit(SMALL_TEST_LENGTH);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- }
-
- assertTrue(ByteBuffer.wrap(new byte[21]).compareTo(ByteBuffer.allocateDirect(21)) == 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- ByteBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to buf
- duplicate.reset();
- assertEquals(0, duplicate.position());
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(0, buf.position());
-
- // duplicate share the same content with buf
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- loadTestData1(buf);
-
- // equal to self
- assertTrue(buf.equals(buf));
- ByteBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- ByteBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(1);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for byte get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- loadTestData1(buf);
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(i, buf.position());
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ByteBuffer get(byte[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {byte[].class}
- )
- public void testGetbyteArray() {
- byte array[] = new byte[1];
- loadTestData1(buf);
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(i, buf.position());
- ByteBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i));
- assertSame(ret, buf);
- }
-
- buf.get(new byte[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((byte[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ByteBuffer get(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {byte[].class, int.class, int.class}
- )
- public void testGetbyteArrayintint() {
- loadTestData1(buf);
- buf.clear();
- byte array[] = new byte[buf.capacity()];
-
- try {
- buf.get(new byte[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(0, buf.position());
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(0, buf.position());
- try {
- buf.get(array, 2, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get((byte[])null, -1, 0);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(0, buf.position());
-
- buf.clear();
- ByteBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for byte get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- loadTestData1(buf);
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(i, buf.position());
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for wrapped ByteBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertTrue(buf.hasArray());
- assertNotNull(buf.array());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- loadTestData1(buf);
- ByteBuffer readonly = buf.asReadOnlyBuffer();
- ByteBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
- duplicate.position(buf.capacity()/2);
- assertTrue(buf.hashCode()!= duplicate.hashCode());
- }
-
- //for the testHashCode() method of readonly subclasses
- protected void readOnlyHashCode(boolean direct) {
- //create a new buffer initiated with some data
- ByteBuffer buf;
- if (direct) {
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH);
- } else {
- buf = ByteBuffer.allocate(BUFFER_LENGTH);
- }
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- buf.clear();
- ByteBuffer readonly = buf.asReadOnlyBuffer();
- ByteBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(),readonly.hashCode());
- duplicate.position(buf.capacity()/2);
- assertTrue(buf.hashCode()!= duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method with not direct buffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- // BIG_ENDIAN is the default byte order
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
-
- buf.order(ByteOrder.LITTLE_ENDIAN);
- assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
-
- buf.order(ByteOrder.BIG_ENDIAN);
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
-
- // Regression test for HARMONY-798
- buf.order((ByteOrder)null);
- assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- /*
- * test for method public final ByteBuffer order(ByteOrder bo)
- * test covers following usecases:
- * 1. case for check
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {java.nio.ByteOrder.class}
- )
- public void test_OrderLjava_lang_ByteOrder() {
- // BIG_ENDIAN is the default byte order
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
-
- buf.order(ByteOrder.LITTLE_ENDIAN);
- assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
-
- buf.order(ByteOrder.BIG_ENDIAN);
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
-
- // Regression test for HARMONY-798
- buf.order((ByteOrder)null);
- assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- /*
- * Class under test for java.nio.ByteBuffer put(byte)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {byte.class}
- )
- public void testPutbyte() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.put((byte) 0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(i, buf.position());
- ByteBuffer ret = buf.put((byte) i);
- assertEquals((byte) i, buf.get(i));
- assertSame(ret, buf);
- }
- try {
- buf.put((byte) 0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.rewind();
- buf.put(Byte.MAX_VALUE);
- assertEquals(Byte.MAX_VALUE, buf.get(0));
- buf.rewind();
- buf.put(Byte.MIN_VALUE);
- assertEquals(Byte.MIN_VALUE, buf.get(0));
- }
-
- /*
- * Class under test for java.nio.ByteBuffer put(byte[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {byte[].class}
- )
- public void testPutbyteArray() {
- byte array[] = new byte[1];
- if (buf.isReadOnly()) {
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(i, buf.position());
- array[0] = (byte) i;
- ByteBuffer ret = buf.put(array);
- assertEquals((byte) i, buf.get(i));
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.put((byte[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ByteBuffer put(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {byte[].class, int.class, int.class}
- )
- public void testPutbyteArrayintint() {
- buf.clear();
- byte array[] = new byte[buf.capacity()];
- if (buf.isReadOnly()) {
- try {
- buf.put(array, 0, array.length);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- try {
- buf.put(new byte[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(0, buf.position());
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(0, buf.position());
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- buf.put(array, 2, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((byte[])null, 2, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
-
- assertEquals(0, buf.position());
-
- loadTestData2(array, 0, array.length);
- ByteBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.ByteBuffer put(java.nio.ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {java.nio.ByteBuffer.class}
- )
- public void testPutByteBuffer() {
- ByteBuffer other = ByteBuffer.allocate(buf.capacity());
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.put(other);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.clear();
- buf.put((ByteBuffer)null);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(ByteBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- try {
- buf.put((ByteBuffer)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- loadTestData2(other);
- other.clear();
- buf.clear();
- ByteBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.ByteBuffer put(int, byte)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {int.class, byte.class}
- )
- public void testPutintbyte() {
- if (buf.isReadOnly()) {
- try {
- buf.put(0, (byte) 0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(0, buf.position());
- ByteBuffer ret = buf.put(i, (byte) i);
- assertEquals((byte) i, buf.get(i));
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, (byte) 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), (byte) 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.put(0, Byte.MAX_VALUE);
- assertEquals(Byte.MAX_VALUE, buf.get(0));
- buf.put(0, Byte.MIN_VALUE);
- assertEquals(Byte.MIN_VALUE, buf.get(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- loadTestData1(buf);
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- ByteBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(0, slice.position());
- assertEquals(buf.remaining(), slice.limit());
- assertEquals(buf.remaining(), slice.capacity());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, (byte) 0, slice.capacity());
- buf.put(2, (byte) 100);
- assertEquals(100, slice.get(1));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String str = buf.toString();
- assertTrue(str.indexOf("Byte") >= 0 || str.indexOf("byte") >= 0);
- assertTrue(str.indexOf("" + buf.position()) >= 0);
- assertTrue(str.indexOf("" + buf.limit()) >= 0);
- assertTrue(str.indexOf("" + buf.capacity()) >= 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asCharBuffer",
- args = {}
- )
- public void testAsCharBuffer() {
- CharBuffer charBuffer;
- byte bytes[] = new byte[2];
- char value;
- loadTestData1(buf);
-
- // test BIG_ENDIAN char buffer, read
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- charBuffer = buf.asCharBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, charBuffer.order());
- while (charBuffer.remaining() > 0) {
- buf.get(bytes);
- value = charBuffer.get();
- assertEquals(bytes2char(bytes, buf.order()), value);
- }
-
- // test LITTLE_ENDIAN char buffer, read
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- charBuffer = buf.asCharBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, charBuffer.order());
- while (charBuffer.remaining() > 0) {
- buf.get(bytes);
- value = charBuffer.get();
- assertEquals(bytes2char(bytes, buf.order()), value);
- }
-
- if (!buf.isReadOnly()) {
- // test BIG_ENDIAN char buffer, write
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- charBuffer = buf.asCharBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, charBuffer.order());
- while (charBuffer.remaining() > 0) {
- value = (char) charBuffer.remaining();
- charBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, char2bytes(value, buf.order())));
- }
-
- // test LITTLE_ENDIAN char buffer, write
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- charBuffer = buf.asCharBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, charBuffer.order());
- while (charBuffer.remaining() > 0) {
- value = (char) charBuffer.remaining();
- charBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, char2bytes(value, buf.order())));
- }
- }
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asDoubleBuffer",
- args = {}
- )
- public void testAsDoubleBuffer() {
- DoubleBuffer doubleBuffer;
- byte bytes[] = new byte[8];
- double value;
- loadTestData1(buf);
-
- // test BIG_ENDIAN double buffer, read
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- doubleBuffer = buf.asDoubleBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, doubleBuffer.order());
- while (doubleBuffer.remaining() > 0) {
- buf.get(bytes);
- value = doubleBuffer.get();
- if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
- .isNaN(value))) {
- assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
- }
- }
-
- // test LITTLE_ENDIAN double buffer, read
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- doubleBuffer = buf.asDoubleBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, doubleBuffer.order());
- while (doubleBuffer.remaining() > 0) {
- buf.get(bytes);
- value = doubleBuffer.get();
- if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
- .isNaN(value))) {
- assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
- }
- }
-
- if (!buf.isReadOnly()) {
- // test BIG_ENDIAN double buffer, write
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- doubleBuffer = buf.asDoubleBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, doubleBuffer.order());
- while (doubleBuffer.remaining() > 0) {
- value = doubleBuffer.remaining();
- doubleBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, double2bytes(value, buf.order())));
- }
-
- // test LITTLE_ENDIAN double buffer, write
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- doubleBuffer = buf.asDoubleBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, doubleBuffer.order());
- while (doubleBuffer.remaining() > 0) {
- value = doubleBuffer.remaining();
- doubleBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, double2bytes(value, buf.order())));
- }
- }
-
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asFloatBuffer",
- args = {}
- )
- public void testAsFloatBuffer() {
- FloatBuffer floatBuffer;
- byte bytes[] = new byte[4];
- float value;
- loadTestData1(buf);
-
- // test BIG_ENDIAN float buffer, read
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- floatBuffer = buf.asFloatBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, floatBuffer.order());
- while (floatBuffer.remaining() > 0) {
- buf.get(bytes);
- value = floatBuffer.get();
- if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
- .isNaN(value))) {
- assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
- }
- }
-
- // test LITTLE_ENDIAN float buffer, read
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- floatBuffer = buf.asFloatBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, floatBuffer.order());
- while (floatBuffer.remaining() > 0) {
- buf.get(bytes);
- value = floatBuffer.get();
- if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
- .isNaN(value))) {
- assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
- }
- }
-
- if (!buf.isReadOnly()) {
- // test BIG_ENDIAN float buffer, write
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- floatBuffer = buf.asFloatBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, floatBuffer.order());
- while (floatBuffer.remaining() > 0) {
- value = floatBuffer.remaining();
- floatBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, float2bytes(value, buf.order())));
- }
-
- // test LITTLE_ENDIAN float buffer, write
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- floatBuffer = buf.asFloatBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, floatBuffer.order());
- while (floatBuffer.remaining() > 0) {
- value = floatBuffer.remaining();
- floatBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, float2bytes(value, buf.order())));
- }
- }
-
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asIntBuffer",
- args = {}
- )
- public void testAsIntBuffer() {
- IntBuffer intBuffer;
- byte bytes[] = new byte[4];
- int value;
- loadTestData1(buf);
-
- // test BIG_ENDIAN int buffer, read
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- intBuffer = buf.asIntBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, intBuffer.order());
- while (intBuffer.remaining() > 0) {
- buf.get(bytes);
- value = intBuffer.get();
- assertEquals(bytes2int(bytes, buf.order()), value);
- }
-
- // test LITTLE_ENDIAN int buffer, read
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- intBuffer = buf.asIntBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, intBuffer.order());
- while (intBuffer.remaining() > 0) {
- buf.get(bytes);
- value = intBuffer.get();
- assertEquals(bytes2int(bytes, buf.order()), value);
- }
-
- if (!buf.isReadOnly()) {
- // test BIG_ENDIAN int buffer, write
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- intBuffer = buf.asIntBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, intBuffer.order());
- while (intBuffer.remaining() > 0) {
- value = intBuffer.remaining();
- intBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, int2bytes(value, buf.order())));
- }
-
- // test LITTLE_ENDIAN int buffer, write
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- intBuffer = buf.asIntBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, intBuffer.order());
- while (intBuffer.remaining() > 0) {
- value = intBuffer.remaining();
- intBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, int2bytes(value, buf.order())));
- }
- }
-
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asLongBuffer",
- args = {}
- )
- public void testAsLongBuffer() {
- LongBuffer longBuffer;
- byte bytes[] = new byte[8];
- long value;
- loadTestData1(buf);
-
- // test BIG_ENDIAN long buffer, read
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- longBuffer = buf.asLongBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, longBuffer.order());
- while (longBuffer.remaining() > 0) {
- buf.get(bytes);
- value = longBuffer.get();
- assertEquals(bytes2long(bytes, buf.order()), value);
- }
-
- // test LITTLE_ENDIAN long buffer, read
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- longBuffer = buf.asLongBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, longBuffer.order());
- while (longBuffer.remaining() > 0) {
- buf.get(bytes);
- value = longBuffer.get();
- assertEquals(bytes2long(bytes, buf.order()), value);
- }
-
- if (!buf.isReadOnly()) {
- // test BIG_ENDIAN long buffer, write
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- longBuffer = buf.asLongBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, longBuffer.order());
- while (longBuffer.remaining() > 0) {
- value = longBuffer.remaining();
- longBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, long2bytes(value, buf.order())));
- }
-
- // test LITTLE_ENDIAN long buffer, write
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- longBuffer = buf.asLongBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, longBuffer.order());
- while (longBuffer.remaining() > 0) {
- value = longBuffer.remaining();
- longBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, long2bytes(value, buf.order())));
- }
- }
-
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asShortBuffer",
- args = {}
- )
- public void testAsShortBuffer() {
- ShortBuffer shortBuffer;
- byte bytes[] = new byte[2];
- short value;
- loadTestData1(buf);
-
- // test BIG_ENDIAN short buffer, read
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- shortBuffer = buf.asShortBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, shortBuffer.order());
- while (shortBuffer.remaining() > 0) {
- buf.get(bytes);
- value = shortBuffer.get();
- assertEquals(bytes2short(bytes, buf.order()), value);
- }
-
- // test LITTLE_ENDIAN short buffer, read
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- shortBuffer = buf.asShortBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, shortBuffer.order());
- while (shortBuffer.remaining() > 0) {
- buf.get(bytes);
- value = shortBuffer.get();
- assertEquals(bytes2short(bytes, buf.order()), value);
- }
-
- if (!buf.isReadOnly()) {
- // test BIG_ENDIAN short buffer, write
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- shortBuffer = buf.asShortBuffer();
- assertSame(ByteOrder.BIG_ENDIAN, shortBuffer.order());
- while (shortBuffer.remaining() > 0) {
- value = (short) shortBuffer.remaining();
- shortBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, short2bytes(value, buf.order())));
- }
-
- // test LITTLE_ENDIAN short buffer, write
- buf.clear();
- buf.order(ByteOrder.LITTLE_ENDIAN);
- shortBuffer = buf.asShortBuffer();
- assertSame(ByteOrder.LITTLE_ENDIAN, shortBuffer.order());
- while (shortBuffer.remaining() > 0) {
- value = (short) shortBuffer.remaining();
- shortBuffer.put(value);
- buf.get(bytes);
- assertTrue(Arrays.equals(bytes, short2bytes(value, buf.order())));
- }
- }
-
- buf.clear();
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getChar",
- args = {}
- )
- public void testGetChar() {
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- char value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- assertEquals(i * nbytes, buf.position());
- buf.mark();
- buf.get(bytes);
- buf.reset();
- value = buf.getChar();
- assertEquals(bytes2char(bytes, buf.order()), value);
- }
-
- try {
- buf.getChar();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getChar",
- args = {int.class}
- )
- public void testGetCharint() {
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- char value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- buf.position(i);
- value = buf.getChar(i);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertEquals(bytes2char(bytes, buf.order()), value);
- }
-
- try {
- buf.getChar(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.getChar(buf.limit() - nbytes + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putChar",
- args = {char.class}
- )
- public void testPutChar() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.putChar((char) 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- char value = 0;
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = (char) i;
- buf.mark();
- buf.putChar(value);
- assertEquals((i + 1) * nbytes, buf.position());
- buf.reset();
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(char2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putChar(value);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.rewind();
- buf.putChar(0, Character.MAX_VALUE);
- assertEquals(Character.MAX_VALUE, buf.getChar(0));
- buf.rewind();
- buf.putChar(0, Character.MIN_VALUE);
- assertEquals(Character.MIN_VALUE, buf.getChar(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putChar",
- args = {int.class, char.class}
- )
- public void testPutCharint() {
- if (buf.isReadOnly()) {
- try {
- buf.putChar(0, (char) 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- char value = 0;
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = (char) i;
- buf.position(i);
- buf.putChar(i, value);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(char2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putChar(-1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.putChar(buf.limit() - nbytes + 1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- try {
- ByteBuffer.allocateDirect(16).putChar(Integer.MAX_VALUE, 'h');
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- buf.putChar(0, Character.MAX_VALUE);
- assertEquals(Character.MAX_VALUE, buf.getChar(0));
- buf.putChar(0, Character.MIN_VALUE);
- assertEquals(Character.MIN_VALUE, buf.getChar(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getDouble",
- args = {}
- )
- public void testGetDouble() {
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- double value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- assertEquals(i * nbytes, buf.position());
- buf.mark();
- buf.get(bytes);
- buf.reset();
- value = buf.getDouble();
- if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
- .isNaN(value))) {
- assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
- }
- }
-
- try {
- buf.getDouble();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getDouble",
- args = {int.class}
- )
- public void testGetDoubleint() {
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- double value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- buf.position(i);
- value = buf.getDouble(i);
- assertEquals(i, buf.position());
- buf.get(bytes);
- if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
- .isNaN(value))) {
- assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
- }
- }
-
- try {
- buf.getDouble(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.getDouble(buf.limit() - nbytes + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- try {
- ByteBuffer.allocateDirect(16).getDouble(Integer.MAX_VALUE);
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putDouble",
- args = {double.class}
- )
- public void testPutDouble() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.putDouble(1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- double value = 0;
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.mark();
- buf.putDouble(value);
- assertEquals((i + 1) * nbytes, buf.position());
- buf.reset();
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(double2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putDouble(value);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.rewind();
- buf.putDouble(Double.MAX_VALUE);
- assertEquals(Double.MAX_VALUE, buf.getDouble(0));
- buf.rewind();
- buf.putDouble(Double.MIN_VALUE);
- assertEquals(Double.MIN_VALUE, buf.getDouble(0));
- buf.rewind();
- buf.putDouble(Double.NaN);
- assertEquals(Double.NaN, buf.getDouble(0));
- buf.rewind();
- buf.putDouble(Double.NEGATIVE_INFINITY);
- assertEquals(Double.NEGATIVE_INFINITY, buf.getDouble(0));
- buf.rewind();
- buf.putDouble(Double.POSITIVE_INFINITY);
- assertEquals(Double.POSITIVE_INFINITY, buf.getDouble(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putDouble",
- args = {int.class, double.class}
- )
- public void testPutDoubleint() {
- if (buf.isReadOnly()) {
- try {
- buf.putDouble(0, 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- double value = 0;
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.position(i);
- buf.putDouble(i, value);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(double2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putDouble(-1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.putDouble(buf.limit() - nbytes + 1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.putDouble(0, Double.MAX_VALUE);
- assertEquals(Double.MAX_VALUE, buf.getDouble(0));
- buf.putDouble(0, Double.MIN_VALUE);
- assertEquals(Double.MIN_VALUE, buf.getDouble(0));
- buf.putDouble(0, Double.NaN);
- assertEquals(Double.NaN, buf.getDouble(0));
- buf.putDouble(0, Double.NEGATIVE_INFINITY);
- assertEquals(Double.NEGATIVE_INFINITY, buf.getDouble(0));
- buf.putDouble(0, Double.POSITIVE_INFINITY);
- assertEquals(Double.POSITIVE_INFINITY, buf.getDouble(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getFloat",
- args = {}
- )
- public void testGetFloat() {
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- float value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- assertEquals(i * nbytes, buf.position());
- buf.mark();
- buf.get(bytes);
- buf.reset();
- value = buf.getFloat();
- if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
- .isNaN(value))) {
- assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
- }
- }
-
- try {
- buf.getFloat();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getFloat",
- args = {int.class}
- )
- public void testGetFloatint() {
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- float value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- buf.position(i);
- value = buf.getFloat(i);
- assertEquals(i, buf.position());
- buf.get(bytes);
- if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
- .isNaN(value))) {
- assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
- }
- }
-
- try {
- buf.getFloat(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.getFloat(buf.limit() - nbytes + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putFloat",
- args = {float.class}
- )
- public void testPutFloat() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.putFloat(1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- float value = 0;
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.mark();
- buf.putFloat(value);
- assertEquals((i + 1) * nbytes, buf.position());
- buf.reset();
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(float2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putFloat(value);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.rewind();
- buf.putFloat(Float.MAX_VALUE);
- assertEquals(Float.MAX_VALUE, buf.getFloat(0));
- buf.rewind();
- buf.putFloat(Float.MIN_VALUE);
- assertEquals(Float.MIN_VALUE, buf.getFloat(0));
- buf.rewind();
- buf.putFloat(Float.NaN);
- assertEquals(Float.NaN, buf.getFloat(0));
- buf.rewind();
- buf.putFloat(Float.NEGATIVE_INFINITY);
- assertEquals(Float.NEGATIVE_INFINITY, buf.getFloat(0));
- buf.rewind();
- buf.putFloat(Float.POSITIVE_INFINITY);
- assertEquals(Float.POSITIVE_INFINITY, buf.getFloat(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putFloat",
- args = {int.class, float.class}
- )
- public void testPutFloatint() {
- if (buf.isReadOnly()) {
- try {
- buf.putFloat(0, 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- float value = 0;
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.position(i);
- buf.putFloat(i, value);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(float2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putFloat(-1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.putFloat(buf.limit() - nbytes + 1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.putFloat(0, Float.MAX_VALUE);
- assertEquals(Float.MAX_VALUE, buf.getFloat(0));
- buf.putFloat(0, Float.MIN_VALUE);
- assertEquals(Float.MIN_VALUE, buf.getFloat(0));
- buf.putFloat(0, Float.NaN);
- assertEquals(Float.NaN, buf.getFloat(0));
- buf.putFloat(0, Float.NEGATIVE_INFINITY);
- assertEquals(Float.NEGATIVE_INFINITY, buf.getFloat(0));
- buf.putFloat(0, Float.POSITIVE_INFINITY);
- assertEquals(Float.POSITIVE_INFINITY, buf.getFloat(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInt",
- args = {}
- )
- public void testGetInt() {
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- int value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- assertEquals(i * nbytes, buf.position());
- buf.mark();
- buf.get(bytes);
- buf.reset();
- value = buf.getInt();
- assertEquals(bytes2int(bytes, buf.order()), value);
- }
-
- try {
- buf.getInt();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInt",
- args = {int.class}
- )
- public void testGetIntint() {
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- int value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- buf.position(i);
- value = buf.getInt(i);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertEquals(bytes2int(bytes, buf.order()), value);
- }
-
- try {
- buf.getInt(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.getInt(buf.limit() - nbytes + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- try {
- ByteBuffer.allocateDirect(16).getInt(Integer.MAX_VALUE);
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putInt",
- args = {int.class}
- )
- public void testPutInt() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.putInt(1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- int value = 0;
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.mark();
- buf.putInt(value);
- assertEquals((i + 1) * nbytes, buf.position());
- buf.reset();
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(int2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putInt(value);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.rewind();
- buf.putInt(Integer.MAX_VALUE);
- assertEquals(Integer.MAX_VALUE, buf.getInt(0));
- buf.rewind();
- buf.putInt(Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, buf.getInt(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putInt",
- args = {int.class, int.class}
- )
- public void testPutIntint() {
- if (buf.isReadOnly()) {
- try {
- buf.putInt(0, 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 4;
- byte bytes[] = new byte[nbytes];
- int value = 0;
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.position(i);
- buf.putInt(i, value);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(int2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putInt(-1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.putInt(buf.limit() - nbytes + 1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.putInt(0, Integer.MAX_VALUE);
- assertEquals(Integer.MAX_VALUE, buf.getInt(0));
- buf.putInt(0, Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, buf.getInt(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getLong",
- args = {}
- )
- public void testGetLong() {
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- long value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- assertEquals(i * nbytes, buf.position());
- buf.mark();
- buf.get(bytes);
- buf.reset();
- value = buf.getLong();
- assertEquals(bytes2long(bytes, buf.order()), value);
- }
-
- try {
- buf.getLong();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getLong",
- args = {int.class}
- )
- public void testGetLongint() {
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- long value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- buf.position(i);
- value = buf.getLong(i);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertEquals(bytes2long(bytes, buf.order()), value);
- }
-
- try {
- buf.getLong(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.getLong(buf.limit() - nbytes + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putLong",
- args = {long.class}
- )
- public void testPutLong() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.putLong(1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- long value = 0;
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.mark();
- buf.putLong(value);
- assertEquals((i + 1) * nbytes, buf.position());
- buf.reset();
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(long2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putLong(value);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.rewind();
- buf.putLong(Long.MAX_VALUE);
- assertEquals(Long.MAX_VALUE, buf.getLong(0));
- buf.rewind();
- buf.putLong(Long.MIN_VALUE);
- assertEquals(Long.MIN_VALUE, buf.getLong(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putLong",
- args = {int.class, long.class}
- )
- public void testPutLongint() {
- if (buf.isReadOnly()) {
- try {
- buf.putLong(0, 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 8;
- byte bytes[] = new byte[nbytes];
- long value = 0;
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = i;
- buf.position(i);
- buf.putLong(i, value);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(long2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putLong(-1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.putLong(buf.limit() - nbytes + 1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.putLong(0, Long.MAX_VALUE);
- assertEquals(Long.MAX_VALUE, buf.getLong(0));
- buf.putLong(0, Long.MIN_VALUE);
- assertEquals(Long.MIN_VALUE, buf.getLong(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getShort",
- args = {}
- )
- public void testGetShort() {
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- short value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- assertEquals(i * nbytes, buf.position());
- buf.mark();
- buf.get(bytes);
- buf.reset();
- value = buf.getShort();
- assertEquals(bytes2short(bytes, buf.order()), value);
- }
-
- try {
- buf.getShort();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getShort",
- args = {int.class}
- )
- public void testGetShortint() {
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- short value;
- loadTestData1(buf);
-
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- buf.position(i);
- value = buf.getShort(i);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertEquals(bytes2short(bytes, buf.order()), value);
- }
-
- try {
- buf.getShort(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.getShort(buf.limit() - nbytes + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putShort",
- args = {short.class}
- )
- public void testPutShort() {
- if (buf.isReadOnly()) {
- try {
- buf.clear();
- buf.putShort((short) 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- short value = 0;
- buf.clear();
- for (int i = 0; buf.remaining() >= nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = (short) i;
- buf.mark();
- buf.putShort(value);
- assertEquals((i + 1) * nbytes, buf.position());
- buf.reset();
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(short2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putShort(value);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.rewind();
- buf.putShort(Short.MAX_VALUE);
- assertEquals(Short.MAX_VALUE, buf.getShort(0));
- buf.rewind();
- buf.putShort(Short.MIN_VALUE);
- assertEquals(Short.MIN_VALUE, buf.getShort(0));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putShort",
- args = {int.class, short.class}
- )
- public void testPutShortint() {
- if (buf.isReadOnly()) {
- try {
- buf.putShort(0, (short) 1);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- return;
- }
-
- int nbytes = 2;
- byte bytes[] = new byte[nbytes];
- short value = 0;
- buf.clear();
- for (int i = 0; i <= buf.limit() - nbytes; i++) {
- buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
- : ByteOrder.LITTLE_ENDIAN);
- value = (short) i;
- buf.position(i);
- buf.putShort(i, value);
- assertEquals(i, buf.position());
- buf.get(bytes);
- assertTrue("Wrong value at " + i,
- Arrays.equals(short2bytes(value, buf.order()), bytes));
- }
-
- try {
- buf.putShort(-1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.putShort(buf.limit() - nbytes + 1, value);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- buf.order(ByteOrder.BIG_ENDIAN);
-
- buf.putShort(0, Short.MAX_VALUE);
- assertEquals(Short.MAX_VALUE, buf.getShort(0));
- buf.putShort(0, Short.MIN_VALUE);
- assertEquals(Short.MIN_VALUE, buf.getShort(0));
- }
-
- /**
- * @tests java.nio.ByteBuffer.wrap(byte[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test. Verifies NullPointerException, IndexOutOfBoundsException.",
- method = "wrap",
- args = {byte[].class, int.class, int.class}
- )
- public void testWrappedByteBuffer_null_array() {
- // Regression for HARMONY-264
- byte array[] = null;
- try {
- ByteBuffer.wrap(array, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
- try {
- ByteBuffer.wrap(new byte[10], Integer.MAX_VALUE, 2);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /*
- * test for method static ByteBuffer wrap(byte[] array)
- * test covers following usecases:
- * 1. case for check ByteBuffer buf2 properties
- * 2. case for check equal between buf2 and byte array[]
- * 3. case for check a buf2 dependens to array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {byte[].class}
- )
- public void test_Wrap$B() {
- byte array[] = new byte[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- ByteBuffer buf2 = ByteBuffer.wrap(array);
-
- // case: ByteBuffer buf2 properties is satisfy the conditions specification
- assertEquals(array.length, buf2.capacity());
- assertEquals(array.length, buf2.limit());
- assertEquals(0, buf2.position());
-
- // case: ByteBuffer buf2 is equal to byte array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: ByteBuffer buf2 is depended to byte array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method static ByteBuffer wrap(byte[] array, int offset, int length)
- * test covers following usecases:
- * 1. case for check ByteBuffer buf2 properties
- * 2. case for check equal between buf2 and byte array[]
- * 3. case for check a buf2 dependens to array[]
- * 4. case expected IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {byte[].class, int.class, int.class}
- )
- public void test_Wrap$BII() {
- byte array[] = new byte[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- ByteBuffer buf2 = ByteBuffer.wrap(array, offset, length);
-
- // case: ByteBuffer buf2 properties is satisfy the conditions specification
- assertEquals(array.length, buf2.capacity());
- assertEquals(offset, buf2.position());
- assertEquals(offset + length, buf2.limit());
- assertEquals(0, buf2.arrayOffset());
-
- // case: ByteBuffer buf2 is equal to byte array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: ByteBuffer buf2 is depended to byte array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = ByteBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- protected void loadTestData1(byte array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (byte) i;
- }
- }
-
- protected void loadTestData2(byte array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (byte) (length - i);
- }
- }
-
- protected void loadTestData1(ByteBuffer buf) {
- if (buf.isReadOnly()) {
- return;
- }
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (byte) i);
- }
- }
-
- protected void loadTestData2(ByteBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (byte) (buf.capacity() - i));
- }
- }
-
- private void assertContentEquals(ByteBuffer buf, byte array[],
- int offset, int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(array[offset + i], buf.get(i));
- }
- }
-
- private void assertContentEquals(ByteBuffer buf, ByteBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i));
- }
- }
-
- private void assertContentLikeTestData1(ByteBuffer buf,
- int startIndex, byte startValue, int length) {
- byte value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value);
- value = (byte) (value + 1);
- }
- }
-
- private int bytes2int(byte bytes[], ByteOrder order) {
- int nbytes = 4, bigHead, step;
- if (order == ByteOrder.BIG_ENDIAN) {
- bigHead = 0;
- step = 1;
- } else {
- bigHead = nbytes - 1;
- step = -1;
- }
- int result = 0;
- int p = bigHead;
- for (int i = 0; i < nbytes; i++) {
- result = result << 8;
- result = result | (bytes[p] & 0xff);
- p += step;
- }
- return result;
- }
-
- private long bytes2long(byte bytes[], ByteOrder order) {
- int nbytes = 8, bigHead, step;
- if (order == ByteOrder.BIG_ENDIAN) {
- bigHead = 0;
- step = 1;
- } else {
- bigHead = nbytes - 1;
- step = -1;
- }
- long result = 0;
- int p = bigHead;
- for (int i = 0; i < nbytes; i++) {
- result = result << 8;
- result = result | (bytes[p] & 0xff);
- p += step;
- }
- return result;
- }
-
- private short bytes2short(byte bytes[], ByteOrder order) {
- int nbytes = 2, bigHead, step;
- if (order == ByteOrder.BIG_ENDIAN) {
- bigHead = 0;
- step = 1;
- } else {
- bigHead = nbytes - 1;
- step = -1;
- }
- short result = 0;
- int p = bigHead;
- for (int i = 0; i < nbytes; i++) {
- result = (short) (result << 8);
- result = (short) (result | (bytes[p] & 0xff));
- p += step;
- }
- return result;
- }
-
- private char bytes2char(byte bytes[], ByteOrder order) {
- return (char) bytes2short(bytes, order);
- }
-
- private float bytes2float(byte bytes[], ByteOrder order) {
- return Float.intBitsToFloat(bytes2int(bytes, order));
- }
-
- private double bytes2double(byte bytes[], ByteOrder order) {
- return Double.longBitsToDouble(bytes2long(bytes, order));
- }
-
- private byte[] int2bytes(int value, ByteOrder order) {
- int nbytes = 4, smallHead, step;
- if (order == ByteOrder.BIG_ENDIAN) {
- smallHead = nbytes - 1;
- step = -1;
- } else {
- smallHead = 0;
- step = 1;
- }
- byte bytes[] = new byte[nbytes];
- int p = smallHead;
- for (int i = 0; i < nbytes; i++) {
- bytes[p] = (byte) (value & 0xff);
- value = value >> 8;
- p += step;
- }
- return bytes;
- }
-
- private byte[] long2bytes(long value, ByteOrder order) {
- int nbytes = 8, smallHead, step;
- if (order == ByteOrder.BIG_ENDIAN) {
- smallHead = nbytes - 1;
- step = -1;
- } else {
- smallHead = 0;
- step = 1;
- }
- byte bytes[] = new byte[nbytes];
- int p = smallHead;
- for (int i = 0; i < nbytes; i++) {
- bytes[p] = (byte) (value & 0xff);
- value = value >> 8;
- p += step;
- }
- return bytes;
- }
-
- private byte[] short2bytes(short value, ByteOrder order) {
- int nbytes = 2, smallHead, step;
- if (order == ByteOrder.BIG_ENDIAN) {
- smallHead = nbytes - 1;
- step = -1;
- } else {
- smallHead = 0;
- step = 1;
- }
- byte bytes[] = new byte[nbytes];
- int p = smallHead;
- for (int i = 0; i < nbytes; i++) {
- bytes[p] = (byte) (value & 0xff);
- value = (short) (value >> 8);
- p += step;
- }
- return bytes;
- }
-
- private byte[] char2bytes(char value, ByteOrder order) {
- return short2bytes((short) value, order);
- }
-
- private byte[] float2bytes(float value, ByteOrder order) {
- return int2bytes(Float.floatToRawIntBits(value), order);
- }
-
- private byte[] double2bytes(double value, ByteOrder order) {
- return long2bytes(Double.doubleToRawLongBits(value), order);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
deleted file mode 100644
index 8ec62ca..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
+++ /dev/null
@@ -1,57 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteOrder;
-
-import junit.framework.TestCase;
-
-/**
- * Test java.nio.ByteOrder
- *
- */
-@TestTargetClass(ByteOrder.class)
-public class ByteOrderTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- assertEquals(ByteOrder.BIG_ENDIAN.toString(), "BIG_ENDIAN");
- assertEquals(ByteOrder.LITTLE_ENDIAN.toString(), "LITTLE_ENDIAN");
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nativeOrder",
- args = {}
- )
- public void testNativeOrder() {
- ByteOrder o = ByteOrder.nativeOrder();
- assertTrue(o == ByteOrder.BIG_ENDIAN || o == ByteOrder.LITTLE_ENDIAN);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java
deleted file mode 100644
index 94b49d1..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java
+++ /dev/null
@@ -1,1601 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.io.IOException;
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteOrder;
-import java.nio.CharBuffer;
-import java.nio.InvalidMarkException;
-import java.nio.ReadOnlyBufferException;
-
-/**
- * Tests java.nio.CharBuffer
- *
- */
-@TestTargetClass(CharBuffer.class)
-public abstract class CharBufferTest extends AbstractBufferTest {
- protected static final int SMALL_TEST_LENGTH = 5;
-
- protected static final int BUFFER_LENGTH = 20;
-
- protected CharBuffer buf;
-
- private static char[] chars = "123456789a".toCharArray();
-
- protected void setUp() throws Exception{
- capacity = chars.length;
- char[] charscopy = new char[chars.length];
- System.arraycopy(chars, 0, charscopy, 0, chars.length);
- buf = CharBuffer.wrap(charscopy);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception{
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static CharBuffer allocate(int capacity) test covers
- * following usecases: 1. case for check CharBuffer testBuf properties 2.
- * case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: CharBuffer testBuf properties is satisfy the conditions
- // specification
- CharBuffer testBuf = CharBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = CharBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = CharBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- char array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- char array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = (char) i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- CharBuffer wrapped = CharBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- CharBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertEquals(buf.capacity(), readonly.capacity());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), 0);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- buf.clear();
- int originalPosition = (buf.position() + buf.limit()) / 2;
- buf.position(originalPosition);
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertEquals(buf.capacity(), readonly.capacity());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), originalPosition);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), originalPosition);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("fails on RI. See comment below")
- public void testCompact() {
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- CharBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), buf.capacity());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (char) 0, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 0);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (char) 0, buf.capacity());
- try {
- // failed on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact()
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(5);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 4);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (char) 1, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.CharBuffer.class}
- )
- public void testCompareTo() {
- // compare to self
- assertEquals(0, buf.compareTo(buf));
-
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
- buf.clear();
- CharBuffer other = CharBuffer.allocate(buf.capacity());
- other.put(buf);
- other.clear();
- buf.clear();
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- assertTrue(buf.compareTo(other) == 0);
- assertTrue(other.compareTo(buf) == 0);
- other.limit(SMALL_TEST_LENGTH);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- // mark the position 0
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- CharBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertEquals(buf.capacity(), duplicate.capacity());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to
- // buf
- duplicate.reset();
- assertEquals(duplicate.position(), 0);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // mark another position
- buf.clear();
- int originalPosition = (buf.position() + buf.limit()) / 2;
- buf.position(originalPosition);
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertEquals(buf.capacity(), duplicate.capacity());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to
- // buf
- duplicate.reset();
- assertEquals(duplicate.position(), originalPosition);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), originalPosition);
-
- // duplicate share the same content with buf
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- // equal to self
- assertTrue(buf.equals(buf));
- CharBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- CharBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > 5);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for char get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.CharBuffer get(char[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {char[].class}
- )
- public void testGetcharArray() {
- char array[] = new char[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- CharBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i));
- assertSame(ret, buf);
- }
-
- buf.get(new char[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((char[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.CharBuffer get(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {char[].class, int.class, int.class}
- )
- public void testGetcharArrayintint() {
- buf.clear();
- char array[] = new char[buf.capacity()];
-
- try {
- buf.get(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, 2, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get((char[])null, 2, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- buf.clear();
- CharBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for char get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- loadTestData1(buf);
- CharBuffer readonly = buf.asReadOnlyBuffer();
- CharBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
- assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
- duplicate.position(buf.capacity() / 2);
- assertTrue(buf.hashCode() != duplicate.hashCode());
- }
-
- /*
- * Class under test for java.nio.CharBuffer put(char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {char.class}
- )
- public void testPutchar() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- CharBuffer ret = buf.put((char) i);
- assertEquals(buf.get(i), (char) i);
- assertSame(ret, buf);
- }
- try {
- buf.put((char) 0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.CharBuffer put(char[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {char[].class}
- )
- public void testPutcharArray() {
- char array[] = new char[1];
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- array[0] = (char) i;
- CharBuffer ret = buf.put(array);
- assertEquals(buf.get(i), (char) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.put((char[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.CharBuffer put(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {char[].class, int.class, int.class}
- )
- public void testPutcharArrayintint() {
- buf.clear();
- char array[] = new char[buf.capacity()];
- try {
- buf.put((char[]) null, 0, 1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((char[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- loadTestData2(array, 0, array.length);
- CharBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.CharBuffer put(java.nio.CharBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.CharBuffer.class}
- )
- public void testPutCharBuffer() {
- CharBuffer other = CharBuffer.allocate(buf.capacity());
-
- try {
- buf.put((CharBuffer) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(CharBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.flip();
- buf.put((CharBuffer)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
-
- loadTestData2(other);
- other.clear();
- buf.clear();
- CharBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.CharBuffer put(int, char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class, char.class}
- )
- public void testPutintchar() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), 0);
- CharBuffer ret = buf.put(i, (char) i);
- assertEquals(buf.get(i), (char) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, (char) 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), (char) 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- CharBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(0, slice.position());
- assertEquals(buf.remaining(), slice.limit());
- assertEquals(buf.remaining(), slice.capacity());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, (char) 0, slice.capacity());
- buf.put(2, (char) 500);
- assertEquals(slice.get(1), 500);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String expected = "";
- for (int i = buf.position(); i < buf.limit(); i++) {
- expected += buf.get(i);
- }
- String str = buf.toString();
- assertEquals(expected, str);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "charAt",
- args = {int.class}
- )
- public void testCharAt() {
- for (int i = 0; i < buf.remaining(); i++) {
- assertEquals(buf.get(buf.position() + i), buf.charAt(i));
- }
- try {
- buf.charAt(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.charAt(buf.remaining());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "length",
- args = {}
- )
- public void testLength() {
- assertEquals(buf.length(), buf.remaining());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "subSequence",
- args = {int.class, int.class}
- )
- public void testSubSequence() {
- try {
- buf.subSequence(-1, buf.length());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.subSequence(buf.length() + 1, buf.length() + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.subSequence(buf.length(), buf.length()).length(), 0);
- try {
- buf.subSequence(1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.subSequence(1, buf.length() + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- assertEquals(buf.subSequence(0, buf.length()).toString(), buf
- .toString());
-
- if (buf.length() >= 2) {
- assertEquals(buf.subSequence(1, buf.length() - 1).toString(), buf
- .toString().substring(1, buf.length() - 1));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.lang.String.class}
- )
- public void testPutString() {
- String str = " ";
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- str = "" + (char) i;
- CharBuffer ret = buf.put(str);
- assertEquals(buf.get(i), (char) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(str);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.put((String) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.lang.String.class, int.class, int.class}
- )
- @AndroidOnly("Fails on RI. See commend below")
- public void testPutStringintint() {
- buf.clear();
- String str = String.valueOf(new char[buf.capacity()]);
-
- // Throw a BufferOverflowException and no character is transfered to
- // CharBuffer
- try {
- buf.put(String.valueOf(new char[buf.capacity() + 1]), 0, buf
- .capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- // Fails on RI. On RI put() starts transferring characters even if
- // there's no free space for whole string
- assertEquals(0, buf.position());
-
- try {
- buf.put((String) null, 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- assertEquals(0, buf.position());
-
- buf.clear();
- try {
- buf.put(str, -1, str.length());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(str, str.length() + 1, str.length() + 2);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((String) null, -1, 0);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- buf.put(str, str.length(), str.length());
- assertEquals(buf.position(), 0);
- try {
- buf.put(str, 2, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(str, 2, str.length() + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- char array[] = new char[buf.capacity()];
- loadTestData2(array, 0, array.length);
- str = String.valueOf(array);
-
- CharBuffer ret = buf.put(str, 0, str.length());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, str.toCharArray(), 0, str.length());
- assertSame(ret, buf);
- }
-
- protected void loadTestData1(char array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (char) i;
- }
- }
-
- protected void loadTestData2(char array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (char) (length - i);
- }
- }
-
- protected void loadTestData1(CharBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (char) i);
- }
- }
-
- protected void loadTestData2(CharBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (char) (buf.capacity() - i));
- }
- }
-
- private void assertContentEquals(CharBuffer buf, char array[], int offset,
- int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(i), array[offset + i]);
- }
- }
-
- private void assertContentEquals(CharBuffer buf, CharBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i));
- }
- }
-
- private void assertContentLikeTestData1(CharBuffer buf, int startIndex,
- char startValue, int length) {
- char value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value);
- value = (char) (value + 1);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies append method with the same CharSequence object for which it's called.",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void testAppendSelf() throws Exception {
- CharBuffer cb = CharBuffer.allocate(10);
- CharBuffer cb2 = cb.duplicate();
- cb.append(cb);
- assertEquals(10, cb.position());
- cb.clear();
- assertEquals(cb2, cb);
-
- cb.put("abc");
- cb2 = cb.duplicate();
- cb.append(cb);
- assertEquals(10, cb.position());
- cb.clear();
- cb2.clear();
- assertEquals(cb2, cb);
-
- cb.put("edfg");
- cb.clear();
- cb2 = cb.duplicate();
- cb.append(cb);
- assertEquals(10, cb.position());
- cb.clear();
- cb2.clear();
- assertEquals(cb, cb2);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies BufferOverflowException.",
- method = "append",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies BufferOverflowException.",
- method = "append",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies BufferOverflowException.",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- })
- public void testAppendOverFlow() throws IOException {
- CharBuffer cb = CharBuffer.allocate(1);
- CharSequence cs = "String";
- cb.put('A');
- try {
- cb.append('C');
- fail("should throw BufferOverflowException.");
- } catch (BufferOverflowException ex) {
- // expected;
- }
- try {
- cb.append(cs);
- fail("should throw BufferOverflowException.");
- } catch (BufferOverflowException ex) {
- // expected;
- }
- try {
- cb.append(cs, 1, 2);
- fail("should throw BufferOverflowException.");
- } catch (BufferOverflowException ex) {
- // expected;
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "append",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "append",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- })
- public void testReadOnlyMap() throws IOException {
- CharBuffer cb = CharBuffer.wrap("ABCDE").asReadOnlyBuffer();
- CharSequence cs = "String";
- try {
- cb.append('A');
- fail("should throw ReadOnlyBufferException.");
- } catch (ReadOnlyBufferException ex) {
- // expected;
- }
- try {
- cb.append(cs);
- fail("should throw ReadOnlyBufferException.");
- } catch (ReadOnlyBufferException ex) {
- // expected;
- }
- try {
- cb.append(cs, 1, 2);
- fail("should throw ReadOnlyBufferException.");
- } catch (ReadOnlyBufferException ex) {
- // expected;
- }
- cb.append(cs, 1, 1);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "append",
- args = {char.class}
- )
- public void testAppendCNormal() throws IOException {
- CharBuffer cb = CharBuffer.allocate(2);
- cb.put('A');
- assertSame(cb, cb.append('B'));
- assertEquals('B', cb.get(1));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void testAppendCharSequenceNormal() throws IOException {
- CharBuffer cb = CharBuffer.allocate(10);
- cb.put('A');
- assertSame(cb, cb.append("String"));
- assertEquals("AString", cb.flip().toString());
- cb.append(null);
- assertEquals("null", cb.flip().toString());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive case, and null as CharSequence parameter.",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void testAppendCharSequenceIINormal() throws IOException {
- CharBuffer cb = CharBuffer.allocate(10);
- cb.put('A');
- assertSame(cb, cb.append("String", 1, 3));
- assertEquals("Atr", cb.flip().toString());
-
- cb.append(null, 0, 1);
- assertEquals("n", cb.flip().toString());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void testAppendCharSequenceII_IllegalArgument() throws IOException {
- CharBuffer cb = CharBuffer.allocate(10);
- cb.append("String", 0, 0);
- cb.append("String", 2, 2);
- try {
- cb.append("String", -1, 1);
- fail("should throw IndexOutOfBoundsException.");
- } catch (IndexOutOfBoundsException ex) {
- // expected;
- }
- try {
- cb.append("String", -1, -1);
- fail("should throw IndexOutOfBoundsException.");
- } catch (IndexOutOfBoundsException ex) {
- // expected;
- }
- try {
- cb.append("String", 3, 2);
- fail("should throw IndexOutOfBoundsException.");
- } catch (IndexOutOfBoundsException ex) {
- // expected;
- }
- try {
- cb.append("String", 3, 0);
- fail("should throw IndexOutOfBoundsException.");
- } catch (IndexOutOfBoundsException ex) {
- // expected;
- }
- try {
- cb.append("String", 3, 110);
- fail("should throw IndexOutOfBoundsException.");
- } catch (IndexOutOfBoundsException ex) {
- // expected;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- public void testReadCharBuffer() throws IOException {
- CharBuffer source = CharBuffer.wrap("String");
- CharBuffer target = CharBuffer.allocate(10);
- assertEquals(6, source.read(target));
- assertEquals("String", target.flip().toString());
- // return -1 when nothing to read
- assertEquals(-1, source.read(target));
- // NullPointerException
- try {
- assertEquals(-1, source.read(null));
- fail("should throw NullPointerException.");
- } catch (NullPointerException ex) {
- // expected;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- public void testReadReadOnly() throws IOException {
- CharBuffer source = CharBuffer.wrap("String");
- CharBuffer target = CharBuffer.allocate(10).asReadOnlyBuffer();
- try {
- source.read(target);
- fail("should throw ReadOnlyBufferException.");
- } catch (ReadOnlyBufferException ex) {
- // expected;
- }
- // if target has no remaining, needn't to check the isReadOnly
- target.flip();
- assertEquals(0, source.read(target));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies read method with CharBuffer parameter which length is less than read CharBuffer.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- public void testReadOverflow() throws IOException {
- CharBuffer source = CharBuffer.wrap("String");
- CharBuffer target = CharBuffer.allocate(1);
- assertEquals(1, source.read(target));
- assertEquals("S", target.flip().toString());
- assertEquals(1, source.position());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- public void testReadSelf() throws Exception {
- CharBuffer source = CharBuffer.wrap("abuffer");
- try {
- source.read(source);
- fail("should throw IAE.");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- public void testRead_scenario1() throws Exception {
- char[] charArray = new char[] { 'a', 'b' };
- CharBuffer charBuffer = CharBuffer.wrap(charArray);
- try {
- charBuffer.read(charBuffer);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- charBuffer.put(charArray);
- assertEquals(-1, charBuffer.read(charBuffer));
- }
-
- public void testRead_scenario2() throws Exception {
- CharBuffer charBufferA = CharBuffer.allocate(0);
- CharBuffer allocateBuffer = CharBuffer.allocate(1);
- CharBuffer charBufferB = CharBuffer.wrap(allocateBuffer);
- assertEquals(-1, charBufferA.read(charBufferB));
-
- allocateBuffer.append(allocateBuffer);
- charBufferB = CharBuffer.wrap(allocateBuffer);
- assertEquals(-1, charBufferA.read(charBufferB));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that hasArray returns true value.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertTrue(buf.hasArray());
- assertNotNull(buf.array());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.nativeOrder(), buf.order());
- }
-
- /*
- * test for method static CharBuffer wrap(char[] array) test covers
- * following usecases: 1. case for check CharBuffer buf2 properties 2. case
- * for check equal between buf2 and char array[] 3. case for check a buf2
- * dependens to array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {char[].class}
- )
- public void test_Wrap$C() {
- char array[] = new char[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- CharBuffer buf2 = CharBuffer.wrap(array);
-
- // case: CharBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.limit(), array.length);
- assertEquals(buf2.position(), 0);
-
- // case: CharBuffer buf2 is equal to char array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: CharBuffer buf2 is depended to char array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method static CharBuffer wrap(char[] array, int offset, int length)
- * test covers following usecases:
- * 1. case for check CharBuffer buf2 properties
- * 2. case for check equal between buf2 and char array[]
- * 3. case for check a buf2 dependens to array[]
- * 4. case expected IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {char[].class, int.class, int.class}
- )
- public void test_Wrap$CII() {
- char array[] = new char[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- CharBuffer buf2 = CharBuffer.wrap(array, offset, length);
-
- // case: CharBuffer buf2 properties is satisfy the conditions specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.position(), offset);
- assertEquals(buf2.limit(), offset + length);
- assertEquals(buf2.arrayOffset(), 0);
-
- // case: CharBuffer buf2 is equal to char array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: CharBuffer buf2 is depended to char array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = CharBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /*
- * test for method static CharBuffer wrap(CharSequence csq)
- * test covers following usecases:
- * 1. case for check StringBuffer
- * 2. case for check StringBuilder
- * 3. case for check String
- * 4. case for check CharBuffer
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {java.lang.CharSequence.class}
- )
- public void test_WrapLjava_lang_CharSequence() {
- // added this if clause to prevent Tests failing under special conditions.
- // If the test extending this test is made for a read only buffer it fails
- // when it tries to call loadTestData1.
- if(buf.isReadOnly()) {
- char[] charscopy = new char[chars.length];
- System.arraycopy(chars, 0, charscopy, 0, chars.length);
- buf = CharBuffer.wrap(charscopy);
- }
- loadTestData1(buf);
- buf.rewind();
- StringBuffer testStrBuffer = new StringBuffer(buf);
- StringBuilder testStrBuilder = new StringBuilder(buf);
- String testStr = buf.toString();
-
- //case: StringBuffer
- CharBuffer bufStrBf = CharBuffer.wrap(testStrBuffer);
- assertTrue(bufStrBf.isReadOnly());
- assertEquals(bufStrBf.capacity(), testStrBuffer.length());
- assertEquals(bufStrBf.limit(), testStrBuffer.length());
- assertEquals(bufStrBf.position(), 0);
- assertContentEquals(bufStrBf, buf);
-
- // case: StringBuilder
- CharBuffer bufStrBl = CharBuffer.wrap(testStrBuilder);
- assertTrue(bufStrBl.isReadOnly());
- assertEquals(bufStrBl.capacity(), testStrBuilder.length());
- assertEquals(bufStrBl.limit(), testStrBuilder.length());
- assertEquals(bufStrBl.position(), 0);
- assertContentEquals(bufStrBl, buf);
-
- // case: String
- CharBuffer bufStr = CharBuffer.wrap(testStr);
- assertTrue(bufStr.isReadOnly());
- assertEquals(bufStr.capacity(), testStr.length());
- assertEquals(bufStr.limit(), testStr.length());
- assertEquals(bufStr.position(), 0);
- assertContentEquals(bufStr, buf);
-
- // case: CharBuffer
- CharBuffer bufChBf = CharBuffer.wrap(buf);
- assertTrue(bufChBf.isReadOnly());
- assertEquals(bufChBf.capacity(), buf.length());
- assertEquals(bufChBf.limit(), buf.length());
- assertEquals(bufChBf.position(), 0);
- assertContentEquals(bufChBf, buf);
- }
-
- /*
- * test for method public static CharBuffer wrap(CharSequence csq, int start, int end)
- * test covers following usecases:
- * 1. case for check StringBuffer
- * 2. case for check StringBuilder
- * 3. case for check String
- * 4. case for check CharBuffer
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exception.",
- method = "wrap",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_WrapLjava_lang_CharSequenceII() {
- int start = buf.position();
- int end = buf.limit();
- CharBuffer buf2 = CharBuffer.wrap(buf.toString() + buf.toString()); //buf.toString() + buf.toString() //"123456789a123456789a"
-
- // case: StringBuffer
- StringBuffer testStrBuffer = new StringBuffer(buf2);
- CharBuffer bufStrBf = CharBuffer.wrap(testStrBuffer, start, end);
- assertTrue(bufStrBf.isReadOnly());
- assertEquals(bufStrBf.capacity(), testStrBuffer.length());
- assertEquals(bufStrBf.limit(), end);
- assertEquals(bufStrBf.position(), start);
- assertEquals(bufStrBf.toString(), buf.toString());
-
- // case: StringBuilder
- StringBuilder testStrBuilder = new StringBuilder(buf2);
- CharBuffer bufStrBl = CharBuffer.wrap(testStrBuilder, start, end);
- assertTrue(bufStrBl.isReadOnly());
- assertEquals(bufStrBl.capacity(), testStrBuilder.length());
- assertEquals(bufStrBl.limit(), end);
- assertEquals(bufStrBl.position(), start);
- assertEquals(bufStrBl.toString(), buf.toString());
-
- // case: String
- String testStr = new String(buf2.toString());
- CharBuffer bufStr = CharBuffer.wrap(testStr, start, end);
- assertTrue(bufStr.isReadOnly());
- assertEquals(bufStr.capacity(), testStr.length());
- assertEquals(bufStr.limit(), end);
- assertEquals(bufStr.position(), start);
- assertEquals(bufStr.toString(), buf.toString());
-
- // case: CharBuffer
- CharBuffer bufChBf = CharBuffer.wrap(buf2, start, end);
- assertTrue(bufChBf.isReadOnly());
- assertEquals(bufChBf.capacity(), buf2.length());
- assertEquals(bufChBf.limit(), end);
- assertEquals(bufChBf.position(), start);
- assertEquals(bufChBf.toString(), buf.toString());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java
deleted file mode 100644
index 824d716..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java
+++ /dev/null
@@ -1,113 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-
-@TestTargetClass(ByteBuffer.class)
-public class DirectByteBufferTest extends ByteBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /**
- * @tests java.nio.ByteBuffer#allocateDirect(int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocateDirect",
- args = {int.class}
- )
- public void testAllocatedByteBuffer_IllegalArg() {
- try {
- ByteBuffer.allocateDirect(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct ByteBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct ByteBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java
deleted file mode 100644
index 397e9f6..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class DirectCharBufferTest extends CharBufferTest {
-
- protected void setUp(){
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH * 2).asCharBuffer();
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown(){
- buf = null;
- baseBuf = null;
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct CharBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies array method for direct CharBuffer.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies arrayOffset method for direct CharBuffer.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct CharBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java
deleted file mode 100644
index 5b2e5d2..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java
+++ /dev/null
@@ -1,96 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public class DirectDoubleBufferTest extends DoubleBufferTest {
- public void setUp(){
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*8).asDoubleBuffer();
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- public void tearDown(){
- buf = null;
- baseBuf = null;
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct DoubleBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies array method for direct DoubleBuffer.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies arrayOffset method for direct DoubleBuffer.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct DoubleBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies order method for direct DoubleBuffer.",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java
deleted file mode 100644
index 184e926..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@TestTargetClass(java.nio.FloatBuffer.class)
-public class DirectFloatBufferTest extends FloatBufferTest {
- public void setUp(){
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*4).asFloatBuffer();
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- public void tearDown(){
- buf = null;
- baseBuf = null;
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct FloatBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies array method for direct FloatBuffer.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies arrayOffset method for direct FloatBuffer.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct FloatBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies order method for direct FloatBuffer.",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java
deleted file mode 100644
index a92ddbe..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java
+++ /dev/null
@@ -1,166 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.BufferOverflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.IntBuffer;
-
-@TestTargetClass(java.nio.IntBuffer.class)
-public class DirectIntBufferTest extends IntBufferTest {
- public void setUp(){
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*4).asIntBuffer();
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- public void tearDown(){
- buf = null;
- baseBuf = null;
- }
-
- /**
- * Regression for http://code.google.com/p/android/issues/detail?id=3279
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {int[].class, int.class, int.class}
- )
- public void testPutWhenOffsetIsNonZero() {
- ByteBuffer byteBuffer = ByteBuffer.allocateDirect(40);
- byteBuffer.order(ByteOrder.nativeOrder());
- IntBuffer intBuffer = byteBuffer.asIntBuffer();
-
- int[] source = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
-
- intBuffer.put(source, 2, 2);
- intBuffer.put(source, 4, 2);
- assertEquals(4, intBuffer.get(0));
- assertEquals(5, intBuffer.get(1));
- assertEquals(6, intBuffer.get(2));
- assertEquals(7, intBuffer.get(3));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct IntBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies array method for direct IntBuffer.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies arrayOffset method for direct IntBuffer.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct IntBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies order method for direct IntBuffer.",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test for IntToByteBufferAdapter",
- clazz = ByteBuffer.class,
- method = "asIntBuffer",
- args = {}
- )
- public void testRangeChecks() {
- int[] myInts = new int[BUFFER_LENGTH];
-
- for (int i = 0; i < BUFFER_LENGTH; i++) {
- myInts[i] = 1000 + i;
- }
-
- buf.position(0);
- buf.put(myInts, 0, BUFFER_LENGTH);
- buf.position(0);
- buf.put(myInts, 0, BUFFER_LENGTH);
-
- try {
- buf.put(myInts, 0, 1); // should fail
- fail("BufferOverflowException expected but not thrown");
- } catch (BufferOverflowException boe) {
- // expected
- }
-
- try {
- buf.position(0);
- buf.put(myInts, 0, BUFFER_LENGTH + 1); // should fail
- fail("BufferOverflowException expected but not thrown");
- } catch (IndexOutOfBoundsException ioobe) {
- // expected
- }
-
- try {
- buf.position(BUFFER_LENGTH - 1);
- buf.put(myInts, 0, 2); // should fail
- fail("BufferOverflowException expected but not thrown");
- } catch (BufferOverflowException boe) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java
deleted file mode 100644
index 4150e38..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-@TestTargetClass(java.nio.LongBuffer.class)
-public class DirectLongBufferTest extends LongBufferTest {
- public void setUp(){
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*8).asLongBuffer();
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- public void tearDown(){
- buf = null;
- baseBuf = null;
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct LongBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies array method for direct LongBuffer.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies arrayOffset method for direct LongBuffer.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct LongBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies order method for direct LongBuffer.",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java
deleted file mode 100644
index fdab359..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java
+++ /dev/null
@@ -1,167 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.BufferOverflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.ShortBuffer;
-import java.nio.IntBuffer;
-
-@TestTargetClass(java.nio.ShortBuffer.class)
-public class DirectShortBufferTest extends ShortBufferTest {
- public void setUp(){
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*2).asShortBuffer();
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- public void tearDown(){
- buf = null;
- baseBuf = null;
- }
-
- /**
- * Regression for http://code.google.com/p/android/issues/detail?id=3279
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {short[].class, int.class, int.class}
- )
- public void testPutWhenOffsetIsNonZero() {
- ByteBuffer byteBuffer = ByteBuffer.allocateDirect(40);
- byteBuffer.order(ByteOrder.nativeOrder());
- ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
-
- short[] source = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
-
- shortBuffer.put(source, 2, 2);
- shortBuffer.put(source, 4, 2);
- assertEquals(4, shortBuffer.get(0));
- assertEquals(5, shortBuffer.get(1));
- assertEquals(6, shortBuffer.get(2));
- assertEquals(7, shortBuffer.get(3));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for direct ShortBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies array method for direct ShortBuffer.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies arrayOffset method for direct ShortBuffer.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for direct ShortBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertTrue(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies order method for direct ShortBuffer.",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test for ShortToByteBufferAdapter",
- clazz = ByteBuffer.class,
- method = "asShortBuffer",
- args = {}
- )
- public void testRangeChecks() {
- short[] myShorts = new short[BUFFER_LENGTH];
-
- for (short i = 0; i < BUFFER_LENGTH; i++) {
- myShorts[i] = (short) (1000 + i);
- }
-
- buf.position(0);
- buf.put(myShorts, 0, BUFFER_LENGTH);
- buf.position(0);
- buf.put(myShorts, 0, BUFFER_LENGTH);
-
- try {
- buf.put(myShorts, 0, 1); // should fail
- fail("BufferOverflowException expected but not thrown");
- } catch (BufferOverflowException boe) {
- // expected
- }
-
- try {
- buf.position(0);
- buf.put(myShorts, 0, BUFFER_LENGTH + 1); // should fail
- fail("BufferOverflowException expected but not thrown");
- } catch (IndexOutOfBoundsException ioobe) {
- // expected
- }
-
- try {
- buf.position(BUFFER_LENGTH - 1);
- buf.put(myShorts, 0, 2); // should fail
- fail("BufferOverflowException expected but not thrown");
- } catch (BufferOverflowException boe) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java
deleted file mode 100644
index b4154ba..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java
+++ /dev/null
@@ -1,971 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.DoubleBuffer;
-import java.nio.InvalidMarkException;
-
-/**
- * Tests java.nio.DoubleBuffer
- */
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public abstract class DoubleBufferTest extends AbstractBufferTest {
-
- protected static final int SMALL_TEST_LENGTH = 5;
-
- protected static final int BUFFER_LENGTH = 20;
-
- protected DoubleBuffer buf;
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = DoubleBuffer.allocate(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static DoubleBuffer allocate(int capacity) test covers
- * following usecases: 1. case for check DoubleBuffer testBuf properties 2.
- * case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: DoubleBuffer testBuf properties is satisfy the conditions
- // specification
- DoubleBuffer testBuf = DoubleBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = DoubleBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = DoubleBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /*
- * Test with bit sequences that represent the IEEE754 doubles Positive
- * infinity, negative infinity, and NaN.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary values.",
- method = "put",
- args = {double.class}
- )
- public void testNaNs() {
- long[] nans = new long[] { 0x7ff0000000000000L, 0xfff0000000000000L,
- 0x7ff8000000000000L };
- for (int i = 0; i < nans.length; i++) {
- long longBitsIn = nans[i];
- double dbl = Double.longBitsToDouble(longBitsIn);
- long longBitsOut = Double.doubleToRawLongBits(dbl);
- // Sanity check
- assertTrue(longBitsIn == longBitsOut);
-
- // Store the double and retrieve it
- ByteBuffer buffer = ByteBuffer.allocate(8);
- buffer.putDouble(dbl);
- double bufDoubleOut = buffer.getDouble(0);
-
- // Check the bits sequence was not normalized
- long bufLongOut = Double.doubleToRawLongBits(bufDoubleOut);
- assertTrue(longBitsIn == bufLongOut);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- double array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- double array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- DoubleBuffer wrapped = DoubleBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- DoubleBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), 0);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // BEGIN android-added
- // copied from a newer version of Harmony
- DoubleBuffer dbuffer1 = DoubleBuffer.wrap(new double[] { Double.NaN });
- DoubleBuffer dbuffer2 = DoubleBuffer.wrap(new double[] { Double.NaN });
- DoubleBuffer dbuffer3 = DoubleBuffer.wrap(new double[] { 42d });
-
- assertEquals("Failed equal comparison with NaN entry", 0, dbuffer1
- .compareTo(dbuffer2));
- assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer3
- .compareTo(dbuffer1));
- assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer1
- .compareTo(dbuffer3));
- // END android-added
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("Fails on RI. See comment below")
- public void testCompact() {
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- DoubleBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), buf.capacity());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0.0, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 0);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0.0, buf.capacity());
- try {
- // Fails on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact(). So RI doesn't reset
- // mark position
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(5);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 4);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 1.0, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.DoubleBuffer.class}
- )
- public void testCompareTo() {
- DoubleBuffer other = DoubleBuffer.allocate(buf.capacity());
- loadTestData1(other);
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- other.limit(5);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
-
- DoubleBuffer dbuffer1 = DoubleBuffer.wrap(new double[] { Double.NaN });
- DoubleBuffer dbuffer2 = DoubleBuffer.wrap(new double[] { Double.NaN });
- DoubleBuffer dbuffer3 = DoubleBuffer.wrap(new double[] { 42d });
-
- assertEquals("Failed equal comparison with NaN entry", 0, dbuffer1
- .compareTo(dbuffer2));
- assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer3
- .compareTo(dbuffer1));
- assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer1
- .compareTo(dbuffer3));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- DoubleBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to buf
- duplicate.reset();
- assertEquals(duplicate.position(), 0);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // duplicate share the same content with buf
- // FIXME
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- // equal to self
- assertTrue(buf.equals(buf));
- DoubleBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- DoubleBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > 5);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for double get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i), 0.01);
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer get(double[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {double[].class}
- )
- public void testGetdoubleArray() {
- double array[] = new double[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- DoubleBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i), 0.01);
- assertSame(ret, buf);
- }
-
- buf.get(new double[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((double[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer get(double[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {double[].class, int.class, int.class}
- )
- public void testGetdoubleArrayintint() {
- buf.clear();
- double array[] = new double[buf.capacity()];
-
- try {
- buf.get(new double[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, 2, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get((double[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- buf.clear();
- DoubleBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for double get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i), 0.01);
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- if (buf.hasArray()) {
- assertNotNull(buf.array());
- } else {
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- // expected
- // Note:can not tell when to catch
- // UnsupportedOperationException or
- // ReadOnlyBufferException, so catch all.
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- DoubleBuffer readonly = buf.asReadOnlyBuffer();
- DoubleBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
-
- assertTrue(buf.capacity() > 5);
- duplicate.position(buf.capacity() / 2);
- assertTrue(buf.hashCode() != duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify direct buffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.nativeOrder(), buf.order());
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer put(double)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify boundary values, and ReadOnlyBufferException.",
- method = "put",
- args = {double.class}
- )
- public void testPutdouble() {
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- DoubleBuffer ret = buf.put((double) i);
- assertEquals(buf.get(i), (double) i, 0.0);
- assertSame(ret, buf);
- }
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer put(double[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {double[].class}
- )
- public void testPutdoubleArray() {
- double array[] = new double[1];
-
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- array[0] = (double) i;
- DoubleBuffer ret = buf.put(array);
- assertEquals(buf.get(i), (double) i, 0.0);
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer put(double[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {double[].class, int.class, int.class}
- )
- public void testPutdoubleArrayintint() {
- buf.clear();
- double array[] = new double[buf.capacity()];
-
- try {
- buf.put(new double[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((double[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- loadTestData2(array, 0, array.length);
- DoubleBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer put(java.nio.DoubleBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.DoubleBuffer.class}
- )
- public void testPutDoubleBuffer() {
- DoubleBuffer other = DoubleBuffer.allocate(buf.capacity());
-
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(DoubleBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
-
- loadTestData2(other);
- other.clear();
- buf.clear();
- DoubleBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.DoubleBuffer put(int, double)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class, double.class}
- )
- public void testPutintdouble() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), 0);
- DoubleBuffer ret = buf.put(i, (double) i);
- assertEquals(buf.get(i), (double) i, 0.0);
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- DoubleBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(slice.position(), 0);
- assertEquals(slice.limit(), buf.remaining());
- assertEquals(slice.capacity(), buf.remaining());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- // FIXME:
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, 0, slice.capacity());
- buf.put(2, 500);
- assertEquals(slice.get(1), 500, 0.0);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String str = buf.toString();
- assertTrue(str.indexOf("Double") >= 0 || str.indexOf("double") >= 0);
- assertTrue(str.indexOf("" + buf.position()) >= 0);
- assertTrue(str.indexOf("" + buf.limit()) >= 0);
- assertTrue(str.indexOf("" + buf.capacity()) >= 0);
- }
-
- /*
- * test for method static DoubleBuffer wrap(double[] array) test covers
- * following usecases: 1. case for check DoubleBuffer buf2 properties 2.
- * case for check equal between buf2 and double array[] 3. case for check a
- * buf2 dependens to array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {double[].class}
- )
- public void test_Wrap$D() {
- double array[] = new double[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- DoubleBuffer buf2 = DoubleBuffer.wrap(array);
-
- // case: DoubleBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.limit(), array.length);
- assertEquals(buf2.position(), 0);
-
- // case: DoubleBuffer buf2 is equal to double array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: DoubleBuffer buf2 is depended to double array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method static DoubleBuffer wrap(double[] array, int offset, int
- * length) test covers following usecases: 1. case for check DoubleBuffer
- * buf2 properties 2. case for check equal between buf2 and double array[]
- * 3. case for check a buf2 dependens to array[] 4. case expected
- * IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {double[].class, int.class, int.class}
- )
- public void test_Wrap$DII() {
- double array[] = new double[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- DoubleBuffer buf2 = DoubleBuffer.wrap(array, offset, length);
-
- // case: DoubleBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.position(), offset);
- assertEquals(buf2.limit(), offset + length);
- assertEquals(buf2.arrayOffset(), 0);
-
- // case: DoubleBuffer buf2 is equal to double array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: DoubleBuffer buf2 is depended to double array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = DoubleBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- void loadTestData1(double array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (double) i;
- }
- }
-
- void loadTestData2(double array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (double) length - i;
- }
- }
-
- void loadTestData1(DoubleBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (double) i);
- }
- }
-
- void loadTestData2(DoubleBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (double) buf.capacity() - i);
- }
- }
-
- private void assertContentEquals(DoubleBuffer buf, double array[],
- int offset, int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(i), array[offset + i], 0.01);
- }
- }
-
- private void assertContentEquals(DoubleBuffer buf, DoubleBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i), 0.01);
- }
- }
-
- private void assertContentLikeTestData1(DoubleBuffer buf, int startIndex,
- double startValue, int length) {
- double value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value, 0.01);
- value = value + 1.0;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java
deleted file mode 100644
index 7ddc788..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java
+++ /dev/null
@@ -1,33 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class DuplicateDirectByteBufferTest extends DirectByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.duplicate();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java
deleted file mode 100644
index 875699c..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.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 org.apache.harmony.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class DuplicateHeapByteBufferTest extends HeapByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.duplicate();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java
deleted file mode 100644
index ce15ff4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.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 org.apache.harmony.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class DuplicateWrappedByteBufferTest extends WrappedByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.duplicate();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java
deleted file mode 100644
index b4bd3ff..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java
+++ /dev/null
@@ -1,978 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.FloatBuffer;
-import java.nio.InvalidMarkException;
-
-/**
- * Tests java.nio.FloatBuffer
- *
- */
-@TestTargetClass(java.nio.FloatBuffer.class)
-public abstract class FloatBufferTest extends AbstractBufferTest {
-
- protected static final int SMALL_TEST_LENGTH = 5;
-
- protected static final int BUFFER_LENGTH = 20;
-
- protected FloatBuffer buf;
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = FloatBuffer.allocate(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static FloatBuffer allocate(int capacity) test covers
- * following usecases: 1. case for check FloatBuffer testBuf properties 2.
- * case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: FloatBuffer testBuf properties is satisfy the conditions
- // specification
- FloatBuffer testBuf = FloatBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = FloatBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = FloatBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary values.",
- method = "put",
- args = {float.class}
- )
- public void testNaNs() {
- int[] nans = new int[] { 0x7f800000, 0xff800000, 0x7fc00000 };
- for (int i = 0; i < nans.length; i++) {
- int intBitsIn = nans[i];
- float flt = Float.intBitsToFloat(intBitsIn);
- int intBitsOut = Float.floatToRawIntBits(flt);
- // Sanity check
- assertTrue(intBitsIn == intBitsOut);
-
- // Store the float and retrieve it
- ByteBuffer buffer = ByteBuffer.allocate(8);
- buffer.putFloat(flt);
- float bufFloatOut = buffer.getFloat(0);
-
- // Check the bits sequence was not normalized
- int bufIntOut = Float.floatToRawIntBits(bufFloatOut);
- assertTrue(intBitsIn == bufIntOut);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- float array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- float array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- FloatBuffer wrapped = FloatBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- FloatBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), 0);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("Fails on RI. See comment below")
- public void testCompact() {
-
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- FloatBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), buf.capacity());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0.0f, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 0);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0.0f, buf.capacity());
- try {
- // Fails on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact(). So RI doesn't reset
- // mark position
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(5);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 4);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 1.0f, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.FloatBuffer.class}
- )
- public void testCompareTo() {
- try {
- buf.compareTo(null);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
-
- // compare to self
- assertEquals(0, buf.compareTo(buf));
-
- // normal cases
- assertTrue(buf.capacity() > 5);
- buf.clear();
- FloatBuffer other = FloatBuffer.allocate(buf.capacity());
- loadTestData1(other);
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- other.limit(5);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
-
- FloatBuffer fbuffer1 = FloatBuffer.wrap(new float[] { Float.NaN });
- FloatBuffer fbuffer2 = FloatBuffer.wrap(new float[] { Float.NaN });
- FloatBuffer fbuffer3 = FloatBuffer.wrap(new float[] { 42f });
-
- assertEquals("Failed equal comparison with NaN entry", 0, fbuffer1
- .compareTo(fbuffer2));
- assertEquals("Failed greater than comparison with NaN entry", 1, fbuffer3
- .compareTo(fbuffer1));
- assertEquals("Failed greater than comparison with NaN entry", 1, fbuffer1
- .compareTo(fbuffer3));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- FloatBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to buf
- duplicate.reset();
- assertEquals(duplicate.position(), 0);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // duplicate share the same content with buf
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- // equal to self
- assertTrue(buf.equals(buf));
- FloatBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- FloatBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > 5);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for float get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i), 0.01);
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.FloatBuffer get(float[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {float[].class}
- )
- public void testGetfloatArray() {
- float array[] = new float[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- FloatBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i), 0.01);
- assertSame(ret, buf);
- }
-
- buf.get(new float[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((float[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.FloatBuffer get(float[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {float[].class, int.class, int.class}
- )
- public void testGetfloatArrayintint() {
- buf.clear();
- float array[] = new float[buf.capacity()];
-
- try {
- buf.get(new float[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, 2, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get((float[])null, 2, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- buf.clear();
- FloatBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for float get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i), 0.01);
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- if (buf.hasArray()) {
- assertNotNull(buf.array());
- } else {
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- // expected
- // Note:can not tell when to catch
- // UnsupportedOperationException or
- // ReadOnlyBufferException, so catch all.
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- FloatBuffer readonly = buf.asReadOnlyBuffer();
- FloatBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
-
- assertTrue(buf.capacity() > 5);
- duplicate.position(buf.capacity() / 2);
- assertTrue(buf.hashCode() != duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify direct buffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- buf.order();
- if (buf.hasArray()) {
- assertEquals(ByteOrder.nativeOrder(), buf.order());
- }
- }
-
- /*
- * Class under test for java.nio.FloatBuffer put(float)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {float.class}
- )
- public void testPutfloat() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- FloatBuffer ret = buf.put((float) i);
- assertEquals(buf.get(i), (float) i, 0.0);
- assertSame(ret, buf);
- }
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.FloatBuffer put(float[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {float[].class}
- )
- public void testPutfloatArray() {
- float array[] = new float[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- array[0] = (float) i;
- FloatBuffer ret = buf.put(array);
- assertEquals(buf.get(i), (float) i, 0.0);
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.position(buf.limit());
- buf.put((float[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.FloatBuffer put(float[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {float[].class, int.class, int.class}
- )
- public void testPutfloatArrayintint() {
- buf.clear();
- float array[] = new float[buf.capacity()];
- try {
- buf.put(new float[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((float[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- loadTestData2(array, 0, array.length);
- FloatBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.FloatBuffer put(java.nio.FloatBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.FloatBuffer.class}
- )
- public void testPutFloatBuffer() {
- FloatBuffer other = FloatBuffer.allocate(buf.capacity());
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(FloatBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.flip();
- buf.put((FloatBuffer)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- buf.clear();
- loadTestData2(other);
- other.clear();
- buf.clear();
- FloatBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.FloatBuffer put(int, float)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class, float.class}
- )
- public void testPutintfloat() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), 0);
- FloatBuffer ret = buf.put(i, (float) i);
- assertEquals(buf.get(i), (float) i, 0.0);
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- FloatBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(slice.position(), 0);
- assertEquals(slice.limit(), buf.remaining());
- assertEquals(slice.capacity(), buf.remaining());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, 0, slice.capacity());
- buf.put(2, 500);
- assertEquals(slice.get(1), 500, 0.0);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String str = buf.toString();
- assertTrue(str.indexOf("Float") >= 0 || str.indexOf("float") >= 0);
- assertTrue(str.indexOf("" + buf.position()) >= 0);
- assertTrue(str.indexOf("" + buf.limit()) >= 0);
- assertTrue(str.indexOf("" + buf.capacity()) >= 0);
- }
-
- /*
- * test for method static FloatBuffer wrap(float[] array) test covers
- * following usecases: 1. case for check FloatBuffer buf2 properties 2. case
- * for check equal between buf2 and float array[] 3. case for check a buf2
- * dependens to array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {float[].class}
- )
- public void test_Wrap$S() {
- float array[] = new float[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- FloatBuffer buf2 = FloatBuffer.wrap(array);
-
- // case: FloatBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.limit(), array.length);
- assertEquals(buf2.position(), 0);
-
- // case: FloatBuffer buf2 is equal to float array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: FloatBuffer buf2 is depended to float array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method static FloatBuffer wrap(float[] array, int offset, int
- * length) test covers following usecases: 1. case for check FloatBuffer
- * buf2 properties 2. case for check equal between buf2 and float array[] 3.
- * case for check a buf2 dependens to array[] 4. case expected
- * IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {float[].class, int.class, int.class}
- )
- public void test_Wrap$SII() {
- float array[] = new float[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- FloatBuffer buf2 = FloatBuffer.wrap(array, offset, length);
-
- // case: FloatBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.position(), offset);
- assertEquals(buf2.limit(), offset + length);
- assertEquals(buf2.arrayOffset(), 0);
-
- // case: FloatBuffer buf2 is equal to float array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: FloatBuffer buf2 is depended to float array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = FloatBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- void loadTestData1(float array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (float) i;
- }
- }
-
- void loadTestData2(float array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (float) length - i;
- }
- }
-
- void loadTestData1(FloatBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (float) i);
- }
- }
-
- void loadTestData2(FloatBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (float) buf.capacity() - i);
- }
- }
-
- void assertContentEquals(FloatBuffer buf, float array[],
- int offset, int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(i), array[offset + i], 0.01);
- }
- }
-
- void assertContentEquals(FloatBuffer buf, FloatBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i), 0.01);
- }
- }
-
- void assertContentLikeTestData1(FloatBuffer buf,
- int startIndex, float startValue, int length) {
- float value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value, 0.01);
- value = value + 1.0f;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java
deleted file mode 100644
index d0a77d9..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java
+++ /dev/null
@@ -1,53 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class HeapByteBufferTest extends ByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- /**
- * @tests java.nio.ByteBuffer#allocate(int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedByteBuffer_IllegalArg() {
- try {
- ByteBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java
deleted file mode 100644
index 2267092..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java
+++ /dev/null
@@ -1,48 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.CharBuffer;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class HeapCharBufferTest extends CharBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedCharBuffer_IllegalArg() {
- try {
- CharBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java
deleted file mode 100644
index cb995e6..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java
+++ /dev/null
@@ -1,48 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.DoubleBuffer;
-
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public class HeapDoubleBufferTest extends DoubleBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedDoubleBuffer_IllegalArg() {
- try {
- DoubleBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java
deleted file mode 100644
index ef94033..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java
+++ /dev/null
@@ -1,48 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.FloatBuffer;
-
-@TestTargetClass(java.nio.FloatBuffer.class)
-public class HeapFloatBufferTest extends FloatBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedFloatBuffer_IllegalArg() {
- try {
- FloatBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java
deleted file mode 100644
index 2c1730e..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java
+++ /dev/null
@@ -1,48 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.IntBuffer;
-
-@TestTargetClass(java.nio.IntBuffer.class)
-public class HeapIntBufferTest extends IntBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedIntBuffer_IllegalArg() {
- try {
- IntBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java
deleted file mode 100644
index 39af9e3..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java
+++ /dev/null
@@ -1,48 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.LongBuffer;
-
-@TestTargetClass(java.nio.LongBuffer.class)
-public class HeapLongBufferTest extends LongBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedLongBuffer_IllegalArg() {
- try {
- LongBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java
deleted file mode 100644
index 368b0f1..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java
+++ /dev/null
@@ -1,48 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ShortBuffer;
-
-@TestTargetClass(java.nio.ShortBuffer.class)
-public class HeapShortBufferTest extends ShortBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "allocate",
- args = {int.class}
- )
- public void testAllocatedShortBuffer_IllegalArg() {
- try {
- ShortBuffer.allocate(-1);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java
deleted file mode 100644
index dbe8aa4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java
+++ /dev/null
@@ -1,954 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.IntBuffer;
-import java.nio.InvalidMarkException;
-
-/**
- * Tests java.nio.IntBuffer
- *
- */
-@TestTargetClass(java.nio.IntBuffer.class)
-public abstract class IntBufferTest extends AbstractBufferTest {
-
-
- protected static final int SMALL_TEST_LENGTH = 5;
-
- protected static final int BUFFER_LENGTH = 20;
-
- protected IntBuffer buf;
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = IntBuffer.allocate(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static IntBuffer allocate(int capacity) test covers
- * following usecases: 1. case for check IntBuffer testBuf properties 2.
- * case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: IntBuffer testBuf properties is satisfy the conditions
- // specification
- IntBuffer testBuf = IntBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = IntBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = IntBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- int array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- int array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- IntBuffer wrapped = IntBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- IntBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), 0);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("Fails on RI. See comment below")
- public void testCompact() {
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- IntBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), buf.capacity());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 0);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0, buf.capacity());
- try {
- // Fails on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact(). So RI doesn't reset
- // mark position
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(5);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 4);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 1, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.IntBuffer.class}
- )
- public void testCompareTo() {
- // compare to self
- assertEquals(0, buf.compareTo(buf));
-
- // normal cases
- assertTrue(buf.capacity() > 5);
- buf.clear();
- IntBuffer other = IntBuffer.allocate(buf.capacity());
- loadTestData1(other);
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- other.limit(5);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- IntBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to buf
- duplicate.reset();
- assertEquals(duplicate.position(), 0);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // duplicate share the same content with buf
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- // equal to self
- assertTrue(buf.equals(buf));
- IntBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- IntBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > 5);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for int get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.IntBuffer get(int[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int[].class}
- )
- public void testGetintArray() {
- int array[] = new int[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- IntBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i));
- assertSame(ret, buf);
- }
-
- buf.get(new int[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((int[])null);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.IntBuffer get(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int[].class, int.class, int.class}
- )
- public void testGetintArrayintint() {
- buf.clear();
- int array[] = new int[buf.capacity()];
-
- try {
- buf.get(new int[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, 2, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get((int[])null, 2, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- buf.clear();
- IntBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for int get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- if (buf.hasArray()) {
- assertNotNull(buf.array());
- } else {
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- // expected
- // Note:can not tell when to catch
- // UnsupportedOperationException or
- // ReadOnlyBufferException, so catch all.
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- IntBuffer readonly = buf.asReadOnlyBuffer();
- IntBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
-
- assertTrue(buf.capacity() > 5);
- duplicate.position(buf.capacity() / 2);
- assertTrue(buf.hashCode() != duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for non direct buffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.nativeOrder(), buf.order());
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class}
- )
- public void testPutint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- IntBuffer ret = buf.put((int) i);
- assertEquals(buf.get(i), (int) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(int[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int[].class}
- )
- public void testPutintArray() {
- int array[] = new int[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- array[0] = (int) i;
- IntBuffer ret = buf.put(array);
- assertEquals(buf.get(i), (int) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.position(buf.limit());
- buf.put((int[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int[].class, int.class, int.class}
- )
- public void testPutintArrayintint() {
- buf.clear();
- int array[] = new int[buf.capacity()];
- try {
- buf.put(new int[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((int[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- loadTestData2(array, 0, array.length);
- IntBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression Test",
- method = "put",
- args = {int[].class, int.class, int.class}
- )
- public void testPutintArrayintint2() {
- // Regression test
- ByteBuffer buf = ByteBuffer.allocateDirect(20);
- IntBuffer intBuf = buf.asIntBuffer();
- int[] src = new int[5];
- intBuf.put(src);
- intBuf.clear();
- try {
- intBuf.put(src);
- } catch (BufferOverflowException e) {
- fail("should not throw a BufferOverflowException");
- }
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(java.nio.IntBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.IntBuffer.class}
- )
- public void testPutIntBuffer() {
- IntBuffer other = IntBuffer.allocate(buf.capacity());
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(IntBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.flip();
- buf.put((IntBuffer)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
-
- loadTestData2(other);
- other.clear();
- buf.clear();
- IntBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class, int.class}
- )
- public void testPutintint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), 0);
- IntBuffer ret = buf.put(i, (int) i);
- assertEquals(buf.get(i), (int) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- IntBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(slice.position(), 0);
- assertEquals(slice.limit(), buf.remaining());
- assertEquals(slice.capacity(), buf.remaining());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, 0, slice.capacity());
- buf.put(2, 500);
- assertEquals(slice.get(1), 500);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String str = buf.toString();
- assertTrue(str.indexOf("Int") >= 0 || str.indexOf("int") >= 0);
- assertTrue(str.indexOf("" + buf.position()) >= 0);
- assertTrue(str.indexOf("" + buf.limit()) >= 0);
- assertTrue(str.indexOf("" + buf.capacity()) >= 0);
- }
-
- /*
- * test for method static IntBuffer wrap(int[] array) test covers following
- * usecases: 1. case for check IntBuffer buf2 properties 2. case for check
- * equal between buf2 and int array[] 3. case for check a buf2 dependens to
- * array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {int[].class}
- )
- public void test_Wrap$I() {
- int array[] = new int[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- IntBuffer buf2 = IntBuffer.wrap(array);
-
- // case: IntBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.limit(), array.length);
- assertEquals(buf2.position(), 0);
-
- // case: IntBuffer buf2 is equal to int array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: IntBuffer buf2 is depended to int array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method static IntBuffer wrap(int[] array, int offset, int
- * length) test covers following usecases: 1. case for check IntBuffer buf2
- * properties 2. case for check equal between buf2 and int array[] 3. case
- * for check a buf2 dependens to array[] 4. case expected
- * IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {int[].class, int.class, int.class}
- )
- public void test_Wrap$III() {
- int array[] = new int[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- IntBuffer buf2 = IntBuffer.wrap(array, offset, length);
-
- // case: IntBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.position(), offset);
- assertEquals(buf2.limit(), offset + length);
- assertEquals(buf2.arrayOffset(), 0);
-
- // case: IntBuffer buf2 is equal to int array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: IntBuffer buf2 is depended to int array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = IntBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- void loadTestData1(int array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (int)i;
- }
- }
-
- void loadTestData2(int array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (int)length - i;
- }
- }
-
- void loadTestData1(IntBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (int)i);
- }
- }
-
- void loadTestData2(IntBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (int)buf.capacity() - i);
- }
- }
-
- void assertContentEquals(IntBuffer buf, int array[],
- int offset, int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(i), array[offset + i]);
- }
- }
-
- void assertContentEquals(IntBuffer buf, IntBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i));
- }
- }
-
- void assertContentLikeTestData1(IntBuffer buf,
- int startIndex, int startValue, int length) {
- int value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value);
- value = value + 1;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java
deleted file mode 100644
index 67029b8..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java
+++ /dev/null
@@ -1,74 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.InvalidMarkException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(InvalidMarkException.class)
-public class InvalidMarkExceptionTest extends TestCase {
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new InvalidMarkException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new InvalidMarkException());
- }
-
- /**
- *@tests {@link java.nio.InvalidMarkException#InvalidMarkException()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvalidMarkException",
- args = {}
- )
- public void test_Constructor() {
- InvalidMarkException exception = new InvalidMarkException();
- assertNull(exception.getMessage());
- assertNull(exception.getLocalizedMessage());
- assertNull(exception.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java
deleted file mode 100644
index 81d30ca..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java
+++ /dev/null
@@ -1,936 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteOrder;
-import java.nio.InvalidMarkException;
-import java.nio.LongBuffer;
-
-/**
- * Tests java.nio.LongBuffer
- *
- */
-@TestTargetClass(java.nio.LongBuffer.class)
-public abstract class LongBufferTest extends AbstractBufferTest {
-
-
- protected static final int SMALL_TEST_LENGTH = 5;
-
- protected static final int BUFFER_LENGTH = 20;
-
- protected LongBuffer buf;
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = LongBuffer.allocate(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static LongBuffer allocate(int capacity) test covers
- * following usecases: 1. case for check LongBuffer testBuf properties 2.
- * case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: LongBuffer testBuf properties is satisfy the conditions
- // specification
- LongBuffer testBuf = LongBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = LongBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = LongBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- long array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- long array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- LongBuffer wrapped = LongBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- LongBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), 0);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("Fails on RI. See comment below")
- public void testCompact() {
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- LongBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), buf.capacity());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 0);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 0, buf.capacity());
- try {
- // Fails on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact(). So RI doesn't reset
- // mark position
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(5);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 4);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, 1, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.LongBuffer.class}
- )
- public void testCompareTo() {
- // compare to self
- assertEquals(0, buf.compareTo(buf));
-
- // normal cases
- assertTrue(buf.capacity() > 5);
- buf.clear();
- LongBuffer other = LongBuffer.allocate(buf.capacity());
- loadTestData1(other);
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- other.limit(5);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- LongBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to buf
- duplicate.reset();
- assertEquals(duplicate.position(), 0);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // duplicate share the same content with buf
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- // equal to self
- assertTrue(buf.equals(buf));
- LongBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- LongBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > 5);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for long get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.LongBuffer get(long[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {long[].class}
- )
- public void testGetlongArray() {
- long array[] = new long[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- LongBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i));
- assertSame(ret, buf);
- }
-
- buf.get(new long[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((long[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.LongBuffer get(long[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {long[].class, int.class, int.class}
- )
- public void testGetlongArrayintint() {
- buf.clear();
- long array[] = new long[buf.capacity()];
-
- try {
- buf.get(new long[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, 2, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get((long[])null, 2, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- buf.clear();
- LongBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for long get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- if (buf.hasArray()) {
- assertNotNull(buf.array());
- } else {
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- // expected
- // Note:can not tell when to catch
- // UnsupportedOperationException or
- // ReadOnlyBufferException, so catch all.
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- LongBuffer readonly = buf.asReadOnlyBuffer();
- LongBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
-
- assertTrue(buf.capacity() > 5);
- duplicate.position(buf.capacity() / 2);
- assertTrue(buf.hashCode() != duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for non direct buffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.nativeOrder(), buf.order());
- }
-
- /*
- * Class under test for java.nio.LongBuffer put(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {long.class}
- )
- public void testPutlong() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- LongBuffer ret = buf.put((long) i);
- assertEquals(buf.get(i), (long) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.LongBuffer put(long[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {long[].class}
- )
- public void testPutlongArray() {
- long array[] = new long[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- array[0] = (long) i;
- LongBuffer ret = buf.put(array);
- assertEquals(buf.get(i), (long) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.position(buf.limit());
- buf.put((long[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.LongBuffer put(long[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {long[].class, int.class, int.class}
- )
- public void testPutlongArrayintint() {
- buf.clear();
- long array[] = new long[buf.capacity()];
- try {
- buf.put(new long[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((long[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- loadTestData2(array, 0, array.length);
- LongBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.LongBuffer put(java.nio.LongBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.LongBuffer.class}
- )
- public void testPutLongBuffer() {
- LongBuffer other = LongBuffer.allocate(buf.capacity());
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(LongBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.flip();
- buf.put((LongBuffer)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
-
- loadTestData2(other);
- other.clear();
- buf.clear();
- LongBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.LongBuffer put(int, long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class, long.class}
- )
- public void testPutintlong() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), 0);
- LongBuffer ret = buf.put(i, (long) i);
- assertEquals(buf.get(i), (long) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- LongBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(slice.position(), 0);
- assertEquals(slice.limit(), buf.remaining());
- assertEquals(slice.capacity(), buf.remaining());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, 0, slice.capacity());
- buf.put(2, 500);
- assertEquals(slice.get(1), 500);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String str = buf.toString();
- assertTrue(str.indexOf("Long") >= 0 || str.indexOf("long") >= 0);
- assertTrue(str.indexOf("" + buf.position()) >= 0);
- assertTrue(str.indexOf("" + buf.limit()) >= 0);
- assertTrue(str.indexOf("" + buf.capacity()) >= 0);
- }
-
- /*
- * test for method public static LongBuffer wrap(long[] array) test covers
- * following usecases: 1. case for check LongBuffer buf2 properties 2. case
- * for check equal between buf2 and ling array[] 3. case for check a buf2
- * dependens to array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {long[].class}
- )
- public void test_Wrap$L() {
- long array[] = new long[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- LongBuffer buf2 = LongBuffer.wrap(array);
-
- // case: LongBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.limit(), array.length);
- assertEquals(buf2.position(), 0);
-
- // case: LongBuffer buf2 is equal to long array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: LongBuffer buf2 is depended to long array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method public static LongBuffer wrap(long[] array, int offset,
- * int length) test covers following usecases: 1. case for check LongBuffer
- * buf2 properties 2. case for check equal between buf2 and long array[] 3.
- * case for check a buf2 dependens to array[] 4. case expected
- * IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {long[].class, int.class, int.class}
- )
- public void test_Wrap$LII() {
- long array[] = new long[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- LongBuffer buf2 = LongBuffer.wrap(array, offset, length);
-
- // case: LongBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.position(), offset);
- assertEquals(buf2.limit(), offset + length);
- assertEquals(buf2.arrayOffset(), 0);
-
- // case: LongBuffer buf2 is equal to long array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: LongBuffer buf2 is depended to long array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = LongBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- void loadTestData1(long array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (long) i;
- }
- }
-
- void loadTestData2(long array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (long) length - i;
- }
- }
-
- void loadTestData1(LongBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (long) i);
- }
- }
-
- void loadTestData2(LongBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (long) buf.capacity() - i);
- }
- }
-
- void assertContentEquals(LongBuffer buf, long array[],
- int offset, int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(i), array[offset + i]);
- }
- }
-
- void assertContentEquals(LongBuffer buf, LongBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i));
- }
- }
-
- void assertContentLikeTestData1(LongBuffer buf,
- int startIndex, long startValue, int length) {
- long value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value);
- value = value + 1;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java
deleted file mode 100644
index f88a163..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java
+++ /dev/null
@@ -1,194 +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.
- */
-
-// BEGIN android-note
-// This test was copied from a newer version of Harmony
-// END android-note
-
-package org.apache.harmony.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.nio.ByteBuffer;
-import java.nio.IntBuffer;
-import java.nio.MappedByteBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileChannel.MapMode;
-
-@TestTargetClass(
- value = MappedByteBuffer.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "isLoaded",
- args = {}
- )
- }
-)
-public class MappedByteBufferTest extends DirectByteBufferTest {
-
- File tmpFile;
- FileChannel fc;
-
- /**
- * A regression test for failing to correctly set capacity of underlying
- * wrapped buffer from a mapped byte buffer.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "A regression test for failing to correctly set capacity",
- method = "asIntBuffer",
- args = {}
- )
- public void test_asIntBuffer() {
- int len = buf.capacity();
- assertEquals("Got wrong number of bytes", BUFFER_LENGTH, len);
-
- // Read in our 26 bytes
- for (int i = 0; i < BUFFER_LENGTH - 20; i++) {
- byte b = buf.get();
- assertEquals("Got wrong byte value", (byte) i, b);
- }
-
- // Now convert to an IntBuffer to read our ints
- IntBuffer ibuffer = buf.asIntBuffer();
- for (int i = BUFFER_LENGTH - 20; i < BUFFER_LENGTH; i+=4) {
- int val = ibuffer.get();
- int res = i * 16777216 + (i + 1) * 65536 + (i + 2) * 256 + (i + 3);
- assertEquals("Got wrong int value", res, val);
- }
- }
-
- /**
- * @tests {@link java.nio.MappedByteBuffer#force()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "force",
- args = {}
- )
- public void test_force() throws IOException {
- // buffer was not mapped in read/write mode
- FileInputStream fileInputStream = new FileInputStream(tmpFile);
- FileChannel fileChannelRead = fileInputStream.getChannel();
- MappedByteBuffer mmbRead = fileChannelRead.map(MapMode.READ_ONLY, 0,
- fileChannelRead.size());
-
- mmbRead.force();
-
- FileInputStream inputStream = new FileInputStream(tmpFile);
- FileChannel fileChannelR = inputStream.getChannel();
- MappedByteBuffer resultRead = fileChannelR.map(MapMode.READ_ONLY, 0,
- fileChannelR.size());
-
- //If this buffer was not mapped in read/write mode, then invoking this method has no effect.
- assertEquals(
- "Invoking force() should have no effect when this buffer was not mapped in read/write mode",
- mmbRead, resultRead);
-
- // Buffer was mapped in read/write mode
- RandomAccessFile randomFile = new RandomAccessFile(tmpFile, "rw");
- FileChannel fileChannelReadWrite = randomFile.getChannel();
- MappedByteBuffer mmbReadWrite = fileChannelReadWrite.map(
- FileChannel.MapMode.READ_WRITE, 0, fileChannelReadWrite.size());
-
- mmbReadWrite.put((byte) 'o');
- mmbReadWrite.force();
-
- RandomAccessFile random = new RandomAccessFile(tmpFile, "rw");
- FileChannel fileChannelRW = random.getChannel();
- MappedByteBuffer resultReadWrite = fileChannelRW.map(
- FileChannel.MapMode.READ_WRITE, 0, fileChannelRW.size());
-
- // Invoking force() will change the buffer
- assertFalse(mmbReadWrite.equals(resultReadWrite));
-
- fileChannelRead.close();
- fileChannelR.close();
- fileChannelReadWrite.close();
- fileChannelRW.close();
- }
-
- /**
- * @tests {@link java.nio.MappedByteBuffer#load()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "load",
- args = {}
- )
- public void test_load() throws IOException {
- FileInputStream fileInputStream = new FileInputStream(tmpFile);
- FileChannel fileChannelRead = fileInputStream.getChannel();
- MappedByteBuffer mmbRead = fileChannelRead.map(MapMode.READ_ONLY, 0,
- fileChannelRead.size());
-
- assertEquals(mmbRead, mmbRead.load());
-
- RandomAccessFile randomFile = new RandomAccessFile(tmpFile, "rw");
- FileChannel fileChannelReadWrite = randomFile.getChannel();
- MappedByteBuffer mmbReadWrite = fileChannelReadWrite.map(
- FileChannel.MapMode.READ_WRITE, 0, fileChannelReadWrite.size());
-
- assertEquals(mmbReadWrite, mmbReadWrite.load());
-
- fileChannelRead.close();
- fileChannelReadWrite.close();
- }
-
- protected void setUp() throws IOException {
- // Create temp file with 26 bytes and 5 ints
- tmpFile = File.createTempFile("MappedByteBufferTest", ".tmp");
- tmpFile.createNewFile();
- tmpFile.deleteOnExit();
-
- fillTempFile();
-
- // Map file
- RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw");
- fc = raf.getChannel();
- capacity = (int) fc.size();
- buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, capacity);
- baseBuf = buf;
- }
-
- protected void tearDown() throws IOException {
- fc.close();
- }
-
- private void fillTempFile() throws IOException {
- FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
- FileChannel fileChannel = fileOutputStream.getChannel();
- ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER_LENGTH);
-
- loadTestData1(byteBuffer);
- byteBuffer.clear();
- fileChannel.write(byteBuffer);
-
- fileChannel.close();
- fileOutputStream.close();
- }
-}
\ No newline at end of file
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java
deleted file mode 100644
index 4be8a43..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java
+++ /dev/null
@@ -1,91 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ReadOnlyBufferException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(ReadOnlyBufferException.class)
-public class ReadOnlyBufferExceptionTest extends TestCase {
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "ReadOnlyBufferException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new ReadOnlyBufferException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "ReadOnlyBufferException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new ReadOnlyBufferException());
- }
-
- /**
- *@tests {@link java.nio.ReadOnlyBufferException#ReadOnlyBufferException()}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "ReadOnlyBufferException",
- args = {}
- )
- public void test_Constructor() {
- ReadOnlyBufferException exception = new ReadOnlyBufferException();
- assertNull(exception.getMessage());
- assertNull(exception.getLocalizedMessage());
- assertNull(exception.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java
deleted file mode 100644
index 2c25f12..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java
+++ /dev/null
@@ -1,289 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.CharBuffer;
-import java.nio.ReadOnlyBufferException;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class ReadOnlyCharBufferTest extends CharBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that isReadOnly returns true for read only CharBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that hasArray returns false for read only CharBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- CharBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(), duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "compact",
- args = {}
- )
- public void testCompact() {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {char.class}
- )
- public void testPutchar() {
- try {
- buf.put((char) 0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException and NullPointerException.",
- method = "put",
- args = {char[].class}
- )
- public void testPutcharArray() {
- char array[] = new char[1];
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((char[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {char[].class, int.class, int.class}
- )
- public void testPutcharArrayintint() {
- char array[] = new char[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((char[]) null, 0, 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.CharBuffer.class}
- )
- public void testPutCharBuffer() {
- CharBuffer other = CharBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((CharBuffer) null);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class, char.class}
- )
- public void testPutintchar() {
- try {
- buf.put(0, (char) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(-1, (char) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void testPutStringintint() {
- buf.clear();
- String str = String.valueOf(new char[buf.capacity()]);
- try {
- buf.put(str, 0, str.length());
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((String) null, 0, 0);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(str, -1, str.length());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- String longStr = String.valueOf(new char[buf.capacity()+1]);
- try {
- buf.put(longStr, 0, longStr.length());
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.lang.String.class}
- )
- public void testPutString() {
- String str = " ";
- try {
- buf.put(str);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((String)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java
deleted file mode 100644
index e9e1582..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java
+++ /dev/null
@@ -1,56 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class ReadOnlyDirectByteBufferTest extends DirectByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only ByteBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- super.readOnlyHashCode(true);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java
deleted file mode 100644
index 8a1466f..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java
+++ /dev/null
@@ -1,231 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.DoubleBuffer;
-import java.nio.ReadOnlyBufferException;
-
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public class ReadOnlyDoubleBufferTest extends DoubleBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only DoubleBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that hasArray returns false value.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- DoubleBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(), duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "compact",
- args = {}
- )
- public void testCompact() {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {double.class}
- )
- public void testPutdouble() {
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {double[].class}
- )
- public void testPutdoubleArray() {
- double array[] = new double[1];
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((double[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {double[].class, int.class, int.class}
- )
- public void testPutdoubleArrayintint() {
- double array[] = new double[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((double[]) null, 0, 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(new double[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.DoubleBuffer.class}
- )
- public void testPutDoubleBuffer() {
- DoubleBuffer other = DoubleBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((DoubleBuffer) null);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class, double.class}
- )
- public void testPutintdouble() {
- try {
- buf.put(0, (double) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(-1, (double) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java
deleted file mode 100644
index 414f1ac..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java
+++ /dev/null
@@ -1,232 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.FloatBuffer;
-import java.nio.ReadOnlyBufferException;
-
-@TestTargetClass(java.nio.FloatBuffer.class)
-public class ReadOnlyFloatBufferTest extends FloatBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only FloatBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that hasArray returns false for Read Only FloatBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- FloatBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(), duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "compact",
- args = {}
- )
- public void testCompact() {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {float.class}
- )
- public void testPutfloat() {
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {float[].class}
- )
- public void testPutfloatArray() {
- float array[] = new float[1];
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((float[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {float[].class, int.class, int.class}
- )
- public void testPutfloatArrayintint() {
- float array[] = new float[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((float[]) null, 0, 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(new float[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.FloatBuffer.class}
- )
- public void testPutFloatBuffer() {
- FloatBuffer other = FloatBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((FloatBuffer) null);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class, float.class}
- )
- public void testPutintfloat() {
- try {
- buf.put(0, (float) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(-1, (float) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java
deleted file mode 100644
index ccb57af..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java
+++ /dev/null
@@ -1,103 +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.nio.tests.java.nio;
-
-import java.nio.ReadOnlyBufferException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class ReadOnlyHeapByteBufferTest extends HeapByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only ByteBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies false returned value.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- super.readOnlyHashCode(false);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java
deleted file mode 100644
index 3bcc5b1..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java
+++ /dev/null
@@ -1,31 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class ReadOnlyHeapCharBufferTest extends ReadOnlyCharBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
deleted file mode 100644
index 48dfe8a..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
+++ /dev/null
@@ -1,31 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public class ReadOnlyHeapDoubleBufferTest extends ReadOnlyDoubleBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
deleted file mode 100644
index 7e969a3..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
+++ /dev/null
@@ -1,30 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.FloatBuffer.class)
-public class ReadOnlyHeapFloatBufferTest extends ReadOnlyFloatBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java
deleted file mode 100644
index ddddfe1..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java
+++ /dev/null
@@ -1,30 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.IntBuffer.class)
-public class ReadOnlyHeapIntBufferTest extends ReadOnlyIntBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java
deleted file mode 100644
index b7fda62..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java
+++ /dev/null
@@ -1,30 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.LongBuffer.class)
-public class ReadOnlyHeapLongBufferTest extends ReadOnlyLongBufferTest{
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java
deleted file mode 100644
index b850c38..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java
+++ /dev/null
@@ -1,30 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ShortBuffer.class)
-public class ReadOnlyHeapShortBufferTest extends ReadOnlyShortBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java
deleted file mode 100644
index 44262ef..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java
+++ /dev/null
@@ -1,232 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.IntBuffer;
-import java.nio.ReadOnlyBufferException;
-
-@TestTargetClass(java.nio.IntBuffer.class)
-public class ReadOnlyIntBufferTest extends IntBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only IntBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method returns false for read only IntBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- IntBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(), duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "compact",
- args = {}
- )
- public void testCompact() {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class}
- )
- public void testPutint() {
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int[].class}
- )
- public void testPutintArray() {
- int array[] = new int[1];
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((int[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int[].class, int.class, int.class}
- )
- public void testPutintArrayintint() {
- int array[] = new int[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((int[]) null, -1, 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(new int[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.IntBuffer.class}
- )
- public void testPutIntBuffer() {
- IntBuffer other = IntBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((IntBuffer) null);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class, int.class}
- )
- public void testPutintint() {
- try {
- buf.put(0, (int) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(-1, (int) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java
deleted file mode 100644
index 8b104e0..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java
+++ /dev/null
@@ -1,232 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.LongBuffer;
-import java.nio.ReadOnlyBufferException;
-
-@TestTargetClass(java.nio.LongBuffer.class)
-public class ReadOnlyLongBufferTest extends LongBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only LongBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that hasArray method returns false for read only LongBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- LongBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(), duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "compact",
- args = {}
- )
- public void testCompact() {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {long.class}
- )
- public void testPutlong() {
- try {
- buf.put(0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {long[].class}
- )
- public void testPutlongArray() {
- long array[] = new long[1];
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((long[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {long[].class, int.class, int.class}
- )
- public void testPutlongArrayintint() {
- long array[] = new long[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((long[]) null, 0, 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(new long[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.LongBuffer.class}
- )
- public void testPutLongBuffer() {
- LongBuffer other = LongBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((LongBuffer) null);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class, long.class}
- )
- public void testPutintlong() {
- try {
- buf.put(0, (long) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(-1, (long) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java
deleted file mode 100644
index ce0c777..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java
+++ /dev/null
@@ -1,232 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ReadOnlyBufferException;
-import java.nio.ShortBuffer;
-
-@TestTargetClass(java.nio.ShortBuffer.class)
-public class ReadOnlyShortBufferTest extends ShortBufferTest {
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only ShortBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for read only ShortBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- ShortBuffer duplicate = buf.duplicate();
- assertEquals(buf.hashCode(), duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "compact",
- args = {}
- )
- public void testCompact() {
- try {
- buf.compact();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {short.class}
- )
- public void testPutshort() {
- try {
- buf.put((short)0);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {short[].class}
- )
- public void testPutshortArray() {
- short array[] = new short[1];
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((short[]) null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {short[].class, int.class, int.class}
- )
- public void testPutshortArrayintint() {
- short array[] = new short[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((short[]) null, 0, 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(new short[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.ShortBuffer.class}
- )
- public void testPutShortBuffer() {
- ShortBuffer other = ShortBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((ShortBuffer) null);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException.",
- method = "put",
- args = {int.class, short.class}
- )
- public void testPutintshort() {
- try {
- buf.put(0, (short) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put(-1, (short) 0);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
deleted file mode 100644
index 75064de..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
+++ /dev/null
@@ -1,105 +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.nio.tests.java.nio;
-
-import java.nio.ReadOnlyBufferException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class ReadOnlyWrappedByteBufferTest extends WrappedByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isReadOnly method for read only wrapped ByteBuffer.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertTrue(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies hasArray method for read only wrapped ByteBuffer.",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- assertFalse(buf.hasArray());
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- super.readOnlyHashCode(false);
- }
-
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
deleted file mode 100644
index 3e45662..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
+++ /dev/null
@@ -1,38 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.CharBuffer;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class ReadOnlyWrappedCharBufferTest1 extends ReadOnlyCharBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = CharBuffer.wrap(new char[BUFFER_LENGTH]);
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
deleted file mode 100644
index ab3f66c..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
+++ /dev/null
@@ -1,37 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.DoubleBuffer;
-
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public class ReadOnlyWrappedDoubleBufferTest extends ReadOnlyDoubleBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = DoubleBuffer.wrap(new double[BUFFER_LENGTH]);
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf =null;
- baseBuf = null;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
deleted file mode 100644
index 3731683..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
+++ /dev/null
@@ -1,37 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.FloatBuffer;
-
-@TestTargetClass(java.nio.FloatBuffer.class)
-public class ReadOnlyWrappedFloatBufferTest extends ReadOnlyFloatBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = FloatBuffer.wrap(new float[BUFFER_LENGTH]);
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
deleted file mode 100644
index f5bdf40..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
+++ /dev/null
@@ -1,37 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.IntBuffer;
-
-@TestTargetClass(java.nio.IntBuffer.class)
-public class ReadOnlyWrappedIntBufferTest extends ReadOnlyIntBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = IntBuffer.wrap(new int[BUFFER_LENGTH]);
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
deleted file mode 100644
index ee2ba73..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
+++ /dev/null
@@ -1,37 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.LongBuffer;
-
-@TestTargetClass(java.nio.LongBuffer.class)
-public class ReadOnlyWrappedLongBufferTest extends ReadOnlyLongBufferTest{
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = LongBuffer.wrap(new long[BUFFER_LENGTH]);
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
deleted file mode 100644
index 34ac3e4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
+++ /dev/null
@@ -1,37 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ShortBuffer;
-
-@TestTargetClass(java.nio.ShortBuffer.class)
-public class ReadOnlyWrappedShortBufferTest extends ReadOnlyShortBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = ShortBuffer.wrap(new short[BUFFER_LENGTH]);
- loadTestData1(buf);
- buf = buf.asReadOnlyBuffer();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java
deleted file mode 100644
index 02f6ce9..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java
+++ /dev/null
@@ -1,947 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.InvalidMarkException;
-import java.nio.ShortBuffer;
-
-/**
- * Tests java.nio.ShortBuffer
- *
- */
-@TestTargetClass(java.nio.ShortBuffer.class)
-public abstract class ShortBufferTest extends AbstractBufferTest {
-
- protected static final int SMALL_TEST_LENGTH = 5;
-
- protected static final int BUFFER_LENGTH = 20;
-
- protected ShortBuffer buf;
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = ShortBuffer.allocate(BUFFER_LENGTH);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /*
- * test for method static ShortBuffer allocate(int capacity) test covers
- * following usecases: 1. case for check ShortBuffer testBuf properties 2.
- * case expected IllegalArgumentException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "allocate",
- args = {int.class}
- )
- public void test_AllocateI() {
- // case: ShortBuffer testBuf properties is satisfy the conditions
- // specification
- ShortBuffer testBuf = ShortBuffer.allocate(20);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(20, testBuf.limit());
- assertEquals(20, testBuf.capacity());
-
- testBuf = ShortBuffer.allocate(0);
- assertEquals(0, testBuf.position());
- assertNotNull(testBuf.array());
- assertEquals(0, testBuf.arrayOffset());
- assertEquals(0, testBuf.limit());
- assertEquals(0, testBuf.capacity());
-
- // case: expected IllegalArgumentException
- try {
- testBuf = ShortBuffer.allocate(-20);
- fail("allocate method does not throws expected exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "array",
- args = {}
- )
- public void testArray() {
- short array[] = buf.array();
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(array, buf.arrayOffset(), buf.capacity());
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData1(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
-
- loadTestData2(buf);
- assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- short array[] = buf.array();
- for(int i = 0; i < buf.capacity(); i++) {
- array[i] = (short) i;
- }
- int offset = buf.arrayOffset();
- assertContentEquals(buf, array, offset, buf.capacity());
-
- ShortBuffer wrapped = ShortBuffer.wrap(array, 3, array.length - 3);
-
- loadTestData1(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
-
- loadTestData2(array, wrapped.arrayOffset(), wrapped.capacity());
- assertContentEquals(buf, array, offset, buf.capacity());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asReadOnlyBuffer",
- args = {}
- )
- public void testAsReadOnlyBuffer() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // readonly's contents should be the same as buf
- ShortBuffer readonly = buf.asReadOnlyBuffer();
- assertNotSame(buf, readonly);
- assertTrue(readonly.isReadOnly());
- assertEquals(buf.position(), readonly.position());
- assertEquals(buf.limit(), readonly.limit());
- assertEquals(buf.isDirect(), readonly.isDirect());
- assertEquals(buf.order(), readonly.order());
- assertContentEquals(buf, readonly);
-
- // readonly's position, mark, and limit should be independent to buf
- readonly.reset();
- assertEquals(readonly.position(), 0);
- readonly.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compact",
- args = {}
- )
- @AndroidOnly("Fails on RI. See comment below")
- public void testCompact() {
- // case: buffer is full
- buf.clear();
- buf.mark();
- loadTestData1(buf);
- ShortBuffer ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), buf.capacity());
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (short) 0, buf.capacity());
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: buffer is empty
- buf.position(0);
- buf.limit(0);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 0);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (short) 0, buf.capacity());
- try {
- // Fails on RI. Spec doesn't specify the behavior if
- // actually nothing to be done by compact(). So RI doesn't reset
- // mark position
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // case: normal
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(5);
- buf.mark();
- ret = buf.compact();
- assertSame(ret, buf);
- assertEquals(buf.position(), 4);
- assertEquals(buf.limit(), buf.capacity());
- assertContentLikeTestData1(buf, 0, (short) 1, 4);
- try {
- buf.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.nio.ShortBuffer.class}
- )
- public void testCompareTo() {
- // compare to self
- assertEquals(0, buf.compareTo(buf));
-
- // normal cases
- assertTrue(buf.capacity() > 5);
- buf.clear();
- ShortBuffer other = ShortBuffer.allocate(buf.capacity());
- loadTestData1(other);
- assertEquals(0, buf.compareTo(other));
- assertEquals(0, other.compareTo(buf));
- buf.position(1);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- other.position(2);
- assertTrue(buf.compareTo(other) < 0);
- assertTrue(other.compareTo(buf) > 0);
- buf.position(2);
- other.limit(5);
- assertTrue(buf.compareTo(other) > 0);
- assertTrue(other.compareTo(buf) < 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "duplicate",
- args = {}
- )
- public void testDuplicate() {
- buf.clear();
- buf.mark();
- buf.position(buf.limit());
-
- // duplicate's contents should be the same as buf
- ShortBuffer duplicate = buf.duplicate();
- assertNotSame(buf, duplicate);
- assertEquals(buf.position(), duplicate.position());
- assertEquals(buf.limit(), duplicate.limit());
- assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
- assertEquals(buf.isDirect(), duplicate.isDirect());
- assertEquals(buf.order(), duplicate.order());
- assertContentEquals(buf, duplicate);
-
- // duplicate's position, mark, and limit should be independent to buf
- duplicate.reset();
- assertEquals(duplicate.position(), 0);
- duplicate.clear();
- assertEquals(buf.position(), buf.limit());
- buf.reset();
- assertEquals(buf.position(), 0);
-
- // duplicate share the same content with buf
- if (!duplicate.isReadOnly()) {
- loadTestData1(buf);
- assertContentEquals(buf, duplicate);
- loadTestData2(duplicate);
- assertContentEquals(buf, duplicate);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- // equal to self
- assertTrue(buf.equals(buf));
- ShortBuffer readonly = buf.asReadOnlyBuffer();
- assertTrue(buf.equals(readonly));
- ShortBuffer duplicate = buf.duplicate();
- assertTrue(buf.equals(duplicate));
-
- // always false, if type mismatch
- assertFalse(buf.equals(Boolean.TRUE));
-
- assertTrue(buf.capacity() > 5);
-
- buf.limit(buf.capacity()).position(0);
- readonly.limit(readonly.capacity()).position(1);
- assertFalse(buf.equals(readonly));
-
- buf.limit(buf.capacity() - 1).position(0);
- duplicate.limit(duplicate.capacity()).position(0);
- assertFalse(buf.equals(duplicate));
- }
-
- /*
- * Class under test for short get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void testGet() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get();
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ShortBuffer get(short[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {short[].class}
- )
- public void testGetshortArray() {
- short array[] = new short[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- ShortBuffer ret = buf.get(array);
- assertEquals(array[0], buf.get(i));
- assertSame(ret, buf);
- }
-
- buf.get(new short[0]);
-
- try {
- buf.get(array);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
-
- try {
- buf.get((short[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ShortBuffer get(short[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {short[].class, int.class, int.class}
- )
- public void testGetshortArrayintint() {
- buf.clear();
- short array[] = new short[buf.capacity()];
-
- try {
- buf.get(new short[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferUnderflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.get(array, array.length, 0);
- try {
- buf.get(array, array.length + 1, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.get((short[])null, 2, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.get(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- buf.clear();
- ShortBuffer ret = buf.get(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for short get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void testGetint() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- assertEquals(buf.get(), buf.get(i));
- }
- try {
- buf.get(-1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.get(buf.limit());
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hasArray",
- args = {}
- )
- public void testHasArray() {
- if (buf.hasArray()) {
- assertNotNull(buf.array());
- } else {
- try {
- buf.array();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- // expected
- // Note:can not tell when to catch
- // UnsupportedOperationException or
- // ReadOnlyBufferException, so catch all.
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- buf.clear();
- ShortBuffer readonly = buf.asReadOnlyBuffer();
- ShortBuffer duplicate = buf.duplicate();
- assertTrue(buf.hashCode() == readonly.hashCode());
-
- assertTrue(buf.capacity() > 5);
- duplicate.position(buf.capacity() / 2);
- assertTrue(buf.hashCode() != duplicate.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isDirect method for non direct ShortBuffer.",
- method = "isDirect",
- args = {}
- )
- public void testIsDirect() {
- assertFalse(buf.isDirect());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Abstract method.",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- assertFalse(buf.isReadOnly());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "order",
- args = {}
- )
- public void testOrder() {
- assertEquals(ByteOrder.nativeOrder(), buf.order());
- }
-
- /*
- * Class under test for java.nio.ShortBuffer put(short)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {short.class}
- )
- public void testPutshort() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- ShortBuffer ret = buf.put((short) i);
- assertEquals(buf.get(i), (short) i);
- assertSame(ret, buf);
- }
- try {
- buf.put((short) 0);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ShortBuffer put(short[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {short[].class}
- )
- public void testPutshortArray() {
- short array[] = new short[1];
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), i);
- array[0] = (short) i;
- ShortBuffer ret = buf.put(array);
- assertEquals(buf.get(i), (short) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(array);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.position(buf.limit());
- buf.put((short[])null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Class under test for java.nio.ShortBuffer put(short[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {short[].class, int.class, int.class}
- )
- public void testPutshortArrayintint() {
- buf.clear();
- short array[] = new short[buf.capacity()];
- try {
- buf.put(new short[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, -1, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, array.length + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- buf.put(array, array.length, 0);
- assertEquals(buf.position(), 0);
- try {
- buf.put(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put((short[])null, 0, -1);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(array, 2, array.length);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- assertEquals(buf.position(), 0);
-
- loadTestData2(array, 0, array.length);
- ShortBuffer ret = buf.put(array, 0, array.length);
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(buf, array, 0, array.length);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.IntBuffer put(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test",
- method = "put",
- args = {short[].class, int.class, int.class}
- )
- public void testPutshortArrayintint2() {
- // Regression test
- ByteBuffer buf = ByteBuffer.allocateDirect(10);
- ShortBuffer shortBuf = buf.asShortBuffer();
- short[] src = new short[5];
- shortBuf.put(src);
- shortBuf.clear();
- try {
- shortBuf.put(src);
- } catch (BufferOverflowException e) {
- fail("should not throw a BufferOverflowException");
- }
- }
-
- /*
- * Class under test for java.nio.ShortBuffer put(java.nio.ShortBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {java.nio.ShortBuffer.class}
- )
- public void testPutShortBuffer() {
- ShortBuffer other = ShortBuffer.allocate(buf.capacity());
- try {
- buf.put(buf);
- fail("Should throw Exception");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- buf.put(ShortBuffer.allocate(buf.capacity() + 1));
- fail("Should throw Exception");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.flip();
- buf.put((ShortBuffer)null);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
-
- loadTestData2(other);
- other.clear();
- buf.clear();
- ShortBuffer ret = buf.put(other);
- assertEquals(other.position(), other.capacity());
- assertEquals(buf.position(), buf.capacity());
- assertContentEquals(other, buf);
- assertSame(ret, buf);
- }
-
- /*
- * Class under test for java.nio.ShortBuffer put(int, short)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ReadOnlyBufferException.",
- method = "put",
- args = {int.class, short.class}
- )
- public void testPutintshort() {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.position(), 0);
- ShortBuffer ret = buf.put(i, (short) i);
- assertEquals(buf.get(i), (short) i);
- assertSame(ret, buf);
- }
- try {
- buf.put(-1, (short) 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- buf.put(buf.limit(), (short) 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- public void testSlice() {
- assertTrue(buf.capacity() > 5);
- buf.position(1);
- buf.limit(buf.capacity() - 1);
-
- ShortBuffer slice = buf.slice();
- assertEquals(buf.isReadOnly(), slice.isReadOnly());
- assertEquals(buf.isDirect(), slice.isDirect());
- assertEquals(buf.order(), slice.order());
- assertEquals(slice.position(), 0);
- assertEquals(slice.limit(), buf.remaining());
- assertEquals(slice.capacity(), buf.remaining());
- try {
- slice.reset();
- fail("Should throw Exception");
- } catch (InvalidMarkException e) {
- // expected
- }
-
- // slice share the same content with buf
- if (!slice.isReadOnly()) {
- loadTestData1(slice);
- assertContentLikeTestData1(buf, 1, (short) 0, slice.capacity());
- buf.put(2, (short) 500);
- assertEquals(slice.get(1), 500);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() {
- String str = buf.toString();
- assertTrue(str.indexOf("Short") >= 0 || str.indexOf("short") >= 0);
- assertTrue(str.indexOf("" + buf.position()) >= 0);
- assertTrue(str.indexOf("" + buf.limit()) >= 0);
- assertTrue(str.indexOf("" + buf.capacity()) >= 0);
- }
-
- /*
- * test for method static ShortBuffer wrap(short[] array) test covers
- * following usecases: 1. case for check ShortBuffer buf2 properties 2. case
- * for check equal between buf2 and short array[] 3. case for check a buf2
- * dependens to array[]
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {short[].class}
- )
- public void test_Wrap$S() {
- short array[] = new short[BUFFER_LENGTH];
- loadTestData1(array, 0, BUFFER_LENGTH);
- ShortBuffer buf2 = ShortBuffer.wrap(array);
-
- // case: ShortBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.limit(), array.length);
- assertEquals(buf2.position(), 0);
-
- // case: ShortBuffer buf2 is equal to short array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: ShortBuffer buf2 is depended to short array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
- }
-
- /*
- * test for method static ShortBuffer wrap(short[] array, int offset, int
- * length) test covers following usecases: 1. case for check ShortBuffer
- * buf2 properties 2. case for check equal between buf2 and short array[] 3.
- * case for check a buf2 dependens to array[] 4. case expected
- * IndexOutOfBoundsException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {short[].class, int.class, int.class}
- )
- public void test_Wrap$SII() {
- short array[] = new short[BUFFER_LENGTH];
- int offset = 5;
- int length = BUFFER_LENGTH - offset;
- loadTestData1(array, 0, BUFFER_LENGTH);
- ShortBuffer buf2 = ShortBuffer.wrap(array, offset, length);
-
- // case: ShortBuffer buf2 properties is satisfy the conditions
- // specification
- assertEquals(buf2.capacity(), array.length);
- assertEquals(buf2.position(), offset);
- assertEquals(buf2.limit(), offset + length);
- assertEquals(buf2.arrayOffset(), 0);
-
- // case: ShortBuffer buf2 is equal to short array[]
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: ShortBuffer buf2 is depended to short array[]
- loadTestData2(array, 0, buf.capacity());
- assertContentEquals(buf2, array, 0, array.length);
-
- // case: expected IndexOutOfBoundsException
- try {
- offset = 7;
- buf2 = ShortBuffer.wrap(array, offset, length);
- fail("wrap method does not throws expected exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- void loadTestData1(short array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (short) i;
- }
- }
-
- void loadTestData2(short array[], int offset, int length) {
- for (int i = 0; i < length; i++) {
- array[offset + i] = (short) (length - i);
- }
- }
-
- void loadTestData1(ShortBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (short) i);
- }
- }
-
- void loadTestData2(ShortBuffer buf) {
- buf.clear();
- for (int i = 0; i < buf.capacity(); i++) {
- buf.put(i, (short) (buf.capacity() - i));
- }
- }
-
- void assertContentEquals(ShortBuffer buf, short array[],
- int offset, int length) {
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(i), array[offset + i]);
- }
- }
-
- void assertContentEquals(ShortBuffer buf, ShortBuffer other) {
- assertEquals(buf.capacity(), other.capacity());
- for (int i = 0; i < buf.capacity(); i++) {
- assertEquals(buf.get(i), other.get(i));
- }
- }
-
- void assertContentLikeTestData1(ShortBuffer buf,
- int startIndex, short startValue, int length) {
- short value = startValue;
- for (int i = 0; i < length; i++) {
- assertEquals(buf.get(startIndex + i), value);
- value = (short) (value + 1);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java
deleted file mode 100644
index cc1d0b4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java
+++ /dev/null
@@ -1,35 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class SliceDirectByteBufferTest extends DirectByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- capacity = BUFFER_LENGTH - 2;
- buf.position(1).limit(BUFFER_LENGTH - 1);
- buf = buf.slice();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java
deleted file mode 100644
index 40670b2..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class SliceHeapByteBufferTest extends HeapByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- capacity = BUFFER_LENGTH - 2;
- buf.position(1).limit(BUFFER_LENGTH - 1);
- buf = buf.slice();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java
deleted file mode 100644
index 0ddbe06..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.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.nio.tests.java.nio;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class SliceWrappedByteBufferTest extends WrappedByteBufferTest {
-
- protected void setUp() throws Exception {
- super.setUp();
- capacity = BUFFER_LENGTH - 2;
- buf.position(1).limit(BUFFER_LENGTH - 1);
- buf = buf.slice();
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java
deleted file mode 100644
index eb0e608..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java
+++ /dev/null
@@ -1,96 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ByteBuffer;
-
-@TestTargetClass(java.nio.ByteBuffer.class)
-public class WrappedByteBufferTest extends ByteBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = ByteBuffer.wrap(new byte[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /**
- * @tests java.nio.ByteBuffer#allocate(byte[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException, NullPointerException.",
- method = "wrap",
- args = {byte[].class, int.class, int.class}
- )
- public void testWrappedByteBuffer_IllegalArg() {
- byte array[] = new byte[BUFFER_LENGTH];
- try {
- ByteBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ByteBuffer.wrap(array, BUFFER_LENGTH + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ByteBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ByteBuffer.wrap(array, 0, BUFFER_LENGTH + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ByteBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ByteBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ByteBuffer.wrap((byte[])null, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java
deleted file mode 100644
index d7325b0..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java
+++ /dev/null
@@ -1,94 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.CharBuffer;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class WrappedCharBufferTest1 extends CharBufferTest {
-
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = CharBuffer.wrap(new char[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- baseBuf = null;
- buf = null;
- }
-
- /**
- * @tests java.nio.CharBuffer#allocate(char[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException, NullPointerException.",
- method = "wrap",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void testWrappedCharBuffer_IllegalArg() {
- char array[] = new char[BUFFER_LENGTH];
- try {
- CharBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(array, BUFFER_LENGTH + 1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(array, 0, BUFFER_LENGTH + 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap((char[])null, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java
deleted file mode 100644
index 5f7a6b9..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java
+++ /dev/null
@@ -1,185 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.nio.BufferOverflowException;
-import java.nio.CharBuffer;
-import java.nio.ReadOnlyBufferException;
-
-@TestTargetClass(java.nio.CharBuffer.class)
-public class WrappedCharBufferTest2 extends ReadOnlyCharBufferTest {
- protected static final String TEST_STRING = "123456789abcdef12345";
-
- protected void setUp() throws Exception {
- super.setUp();
- capacity = TEST_STRING.length();
- buf = CharBuffer.wrap(TEST_STRING);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- baseBuf = null;
- buf = null;
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException, IndexOutOfBoundsException.",
- method = "wrap",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void testWrappedCharSequence_IllegalArg() {
- String str = TEST_STRING;
- try {
- CharBuffer.wrap(str, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(str, 21, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(str, 2, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap(str, 0, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- CharBuffer.wrap((String)null, -1, 21);
- fail("Should throw Exception");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedOperationException for CharSequenceAdapter.",
- method = "array",
- args = {}
- )
- public void testArray() {
- try {
- buf.array();
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedOperationException.",
- method = "arrayOffset",
- args = {}
- )
- public void testArrayOffset() {
- try {
- buf.arrayOffset();
- fail("Should throw Exception");
- } catch (UnsupportedOperationException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException, NullPointerException, BufferOverflowException, IndexOutOfBoundsException.",
- method = "put",
- args = {char[].class, int.class, int.class}
- )
- public void testPutcharArrayintint() {
- char array[] = new char[1];
- try {
- buf.put(array, 0, array.length);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((char[]) null, 0, 1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
- fail("Should throw BufferOverflowException");
- } catch (BufferOverflowException e) {
- // expected
- }
- try {
- buf.put(array, -1, array.length);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ReadOnlyBufferException, NullPointerException, IllegalArgumentException.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- public void testPutCharBuffer() {
- CharBuffer other = CharBuffer.allocate(1);
- try {
- buf.put(other);
- fail("Should throw ReadOnlyBufferException");
- } catch (ReadOnlyBufferException e) {
- // expected
- }
- try {
- buf.put((CharBuffer) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- buf.put(buf);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "slice",
- args = {}
- )
- @AndroidOnly("Fails on RI")
- public void testSlice() {
- super.testSlice();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java
deleted file mode 100644
index 20a5eba..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.DoubleBuffer;
-
-@TestTargetClass(java.nio.DoubleBuffer.class)
-public class WrappedDoubleBufferTest extends DoubleBufferTest {
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = DoubleBuffer.wrap(new double[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- buf = null;
- baseBuf = null;
- }
-
- /**
- * @tests java.nio.CharBuffer#allocate(char[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {double[].class, int.class, int.class}
- )
- public void testWrappedDoubleuffer_IllegalArg() {
- double array[] = new double[20];
- try {
- DoubleBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- DoubleBuffer.wrap(array, 21, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- DoubleBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- DoubleBuffer.wrap(array, 0, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- DoubleBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- DoubleBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- DoubleBuffer.wrap((double[])null, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
-
- DoubleBuffer buf = DoubleBuffer.wrap(array, 2, 16);
- assertEquals(buf.position(), 2);
- assertEquals(buf.limit(), 18);
- assertEquals(buf.capacity(), 20);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java
deleted file mode 100644
index eb3f2b8..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.FloatBuffer;
-
-@TestTargetClass(java.nio.FloatBuffer.class)
-public class WrappedFloatBufferTest extends FloatBufferTest {
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = FloatBuffer.wrap(new float[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- baseBuf = null;
- buf = null;
- }
-
- /**
- * @tests java.nio.CharBuffer#allocate(char[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {float[].class, int.class, int.class}
- )
- public void testWrappedFloatBuffer_IllegalArg() {
- float array[] = new float[20];
- try {
- FloatBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- FloatBuffer.wrap(array, 21, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- FloatBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- FloatBuffer.wrap(array, 0, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- FloatBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- FloatBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- FloatBuffer.wrap((float[])null, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
-
- FloatBuffer buf = FloatBuffer.wrap(array, 2, 16);
- assertEquals(buf.position(), 2);
- assertEquals(buf.limit(), 18);
- assertEquals(buf.capacity(), 20);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java
deleted file mode 100644
index 90a4dab..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.IntBuffer;
-
-@TestTargetClass(java.nio.IntBuffer.class)
-public class WrappedIntBufferTest extends IntBufferTest {
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = IntBuffer.wrap(new int[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- baseBuf = null;
- buf = null;
- }
-
- /**
- * @tests java.nio.CharBuffer#allocate(char[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {int[].class, int.class, int.class}
- )
- public void testWrappedIntBuffer_IllegalArg() {
- int array[] = new int[20];
- try {
- IntBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- IntBuffer.wrap(array, 21, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- IntBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- IntBuffer.wrap(array, 0, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- IntBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- IntBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- IntBuffer.wrap((int[])null, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
-
- IntBuffer buf = IntBuffer.wrap(array, 2, 16);
- assertEquals(buf.position(), 2);
- assertEquals(buf.limit(), 18);
- assertEquals(buf.capacity(), 20);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java
deleted file mode 100644
index dcf6465..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.LongBuffer;
-
-@TestTargetClass(java.nio.LongBuffer.class)
-public class WrappedLongBufferTest extends LongBufferTest {
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = LongBuffer.wrap(new long[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- baseBuf = null;
- buf = null;
- }
-
- /**
- * @tests java.nio.CharBuffer#allocate(char[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {long[].class, int.class, int.class}
- )
- public void testWrappedLongBuffer_IllegalArg() {
- long array[] = new long[20];
- try {
- LongBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- LongBuffer.wrap(array, 21, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- LongBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- LongBuffer.wrap(array, 0, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- LongBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- LongBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- LongBuffer.wrap((long[])null, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
-
- LongBuffer buf = LongBuffer.wrap(array, 2, 16);
- assertEquals(buf.position(), 2);
- assertEquals(buf.limit(), 18);
- assertEquals(buf.capacity(), 20);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java
deleted file mode 100644
index 1d1c2c4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java
+++ /dev/null
@@ -1,97 +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.nio.tests.java.nio;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.ShortBuffer;
-
-@TestTargetClass(java.nio.ShortBuffer.class)
-public class WrappedShortBufferTest extends ShortBufferTest {
- protected void setUp() throws Exception {
- capacity = BUFFER_LENGTH;
- buf = ShortBuffer.wrap(new short[BUFFER_LENGTH]);
- loadTestData1(buf);
- baseBuf = buf;
- }
-
- protected void tearDown() throws Exception {
- baseBuf = null;
- buf = null;
- }
-
- /**
- * @tests java.nio.CharBuffer#allocate(char[],int,int)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {short[].class, int.class, int.class}
- )
- public void testWrappedShortBuffer_IllegalArg() {
- short array[] = new short[20];
- try {
- ShortBuffer.wrap(array, -1, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ShortBuffer.wrap(array, 21, 0);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ShortBuffer.wrap(array, 0, -1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ShortBuffer.wrap(array, 0, 21);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ShortBuffer.wrap(array, Integer.MAX_VALUE, 1);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ShortBuffer.wrap(array, 1, Integer.MAX_VALUE);
- fail("Should throw Exception");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- ShortBuffer.wrap((short[])null, -1, 0);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- }
-
- ShortBuffer buf = ShortBuffer.wrap(array, 2, 16);
- assertEquals(buf.position(), 2);
- assertEquals(buf.limit(), 18);
- assertEquals(buf.capacity(), 20);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java
deleted file mode 100644
index 0f6c837..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java
+++ /dev/null
@@ -1,58 +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.nio.tests.java.nio.channels;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite(AllTests.class.getName());
- //$JUnit-BEGIN$
- suite.addTestSuite(AlreadyConnectedExceptionTest.class);
- suite.addTestSuite(AsynchronousCloseExceptionTest.class);
- suite.addTestSuite(CancelledKeyExceptionTest.class);
- suite.addTestSuite(ChannelsTest.class);
- suite.addTestSuite(ClosedByInterruptExceptionTest.class);
- suite.addTestSuite(ClosedChannelExceptionTest.class);
- suite.addTestSuite(ClosedSelectorExceptionTest.class);
- suite.addTestSuite(ConnectionPendingExceptionTest.class);
- suite.addTestSuite(DatagramChannelTest.class);
- suite.addTestSuite(FileLockInterruptionExceptionTest.class);
- suite.addTestSuite(FileLockTest.class);
- suite.addTestSuite(IllegalBlockingModeExceptionTest.class);
- suite.addTestSuite(IllegalSelectorExceptionTest.class);
- suite.addTestSuite(MapModeTest.class);
- suite.addTestSuite(NoConnectionPendingExceptionTest.class);
- suite.addTestSuite(NonReadableChannelExceptionTest.class);
- suite.addTestSuite(NonWritableChannelExceptionTest.class);
- suite.addTestSuite(NotYetBoundExceptionTest.class);
- suite.addTestSuite(NotYetConnectedExceptionTest.class);
- suite.addTestSuite(OverlappingFileLockExceptionTest.class);
- suite.addTestSuite(PipeTest.class);
- suite.addTestSuite(SelectableChannelTest.class);
- suite.addTestSuite(SelectionKeyTest.class);
- suite.addTestSuite(SelectorTest.class);
- suite.addTestSuite(SinkChannelTest.class);
- suite.addTestSuite(SourceChannelTest.class);
- suite.addTestSuite(UnresolvedAddressExceptionTest.class);
- suite.addTestSuite(UnsupportedAddressTypeExceptionTest.class);
- // $JUnit-END$
- return suite;
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
deleted file mode 100644
index 3b0dfc9..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.AlreadyConnectedException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(AlreadyConnectedException.class)
-/**
- * Tests for AlreadyConnectedException
- */
-public class AlreadyConnectedExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.AlreadyConnectedException#AlreadyConnectedException()}
- */
- public void test_Constructor() {
- AlreadyConnectedException e = new AlreadyConnectedException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "AlreadyConnectedException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new AlreadyConnectedException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "AlreadyConnectedException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new AlreadyConnectedException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
deleted file mode 100644
index 7f7ca65..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.AsynchronousCloseException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for AsynchronousCloseException
- */
-@TestTargetClass(AsynchronousCloseException.class)
-public class AsynchronousCloseExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.AsynchronousCloseException#AsynchronousCloseException()}
- */
- public void test_Constructor() {
- AsynchronousCloseException e = new AsynchronousCloseException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "AsynchronousCloseException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new AsynchronousCloseException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "AsynchronousCloseException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new AsynchronousCloseException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java
deleted file mode 100644
index 60e0c3a..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.CancelledKeyException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for CancelledKeyException
- */
-@TestTargetClass(CancelledKeyException.class)
-public class CancelledKeyExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.CancelledKeyException#CancelledKeyException()}
- */
- public void test_Constructor() {
- CancelledKeyException e = new CancelledKeyException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "CancelledKeyException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new CancelledKeyException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "CancelledKeyException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new CancelledKeyException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java
deleted file mode 100644
index f0c44f4..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java
+++ /dev/null
@@ -1,1141 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.channels.Channels;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.IllegalBlockingModeException;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.WritableByteChannel;
-import java.nio.charset.Charset;
-import java.nio.charset.UnsupportedCharsetException;
-
-import tests.support.Support_PortManager;
-
-import junit.framework.TestCase;
-
-/**
- * Note: the test case uses a temp text file named "test" which contains 31
- * characters : "P@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]"
- *
- */
-@TestTargetClass(Channels.class)
-public class ChannelsTest extends TestCase {
- private static final String CODE_SET = "GB2312";
-
- private static final String BAD_CODE_SET = "GB2313";
-
- private FileInputStream fins;
-
- private FileOutputStream fouts;
-
- private final int writebufSize = 60;
-
- private final int testNum = 10;
-
- private final int fileSize = 31;// the file size
-
- private File tmpFile;
-
- protected void setUp() throws Exception {
- super.setUp();
- // Make the test file same in every test
- tmpFile = File.createTempFile("test","tmp");
- tmpFile.deleteOnExit();
- this.writeFileSame();
- }
-
- protected void tearDown() throws Exception {
- if (null != this.fins) {
- this.fins.close();
- this.fins = null;
- }
- if (null != this.fouts) {
- this.fouts.close();
- this.fouts = null;
- }
-
- tmpFile.delete();
- super.tearDown();
-
- }
-
- private void writeFileSame() throws IOException {
- this.fouts = new FileOutputStream(tmpFile);
- byte[] bit = new byte[1];
- bit[0] = 80;
- this.fouts.write(bit);
- this.fouts.flush();
- String writebuf = "";
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- this.fouts.write(writebuf.getBytes());
- }
-
- /*
- * This private method is to assert if the file size is the same as the
- * compare Number in the test
- */
- private void assertFileSizeSame(File fileToTest, int compareNumber)
- throws IOException {
- FileInputStream file = new FileInputStream(fileToTest);
- assertEquals(file.available(), compareNumber);
- file.close();
- }
-
- // test if new Channel to input is null
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newChannel",
- args = {java.io.InputStream.class}
- )
- public void testNewChannelInputStream_InputNull() throws IOException {
- ByteBuffer byteBuf = ByteBuffer.allocate(this.testNum);
- this.fins = null;
- int readres = this.testNum;
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- assertNotNull(rbChannel);
- try {
- readres = rbChannel.read(byteBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(this.testNum, readres);
- }
-
- // test if buffer to read is null
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newChannel",
- args = {java.io.InputStream.class}
- )
- public void testNewChannelInputStream_BufferNull() throws IOException {
- ByteBuffer byteBuf = ByteBuffer.allocate(this.testNum);
- int readres = this.testNum;
- this.fins = new FileInputStream(tmpFile);
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- assertNotNull(rbChannel);
- try {
- readres = rbChannel.read(null);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(this.testNum, readres);
- readres = 0;
- try {
- readres = rbChannel.read(byteBuf);
- } catch (NullPointerException e) {
- fail();
- }
- assertEquals(this.testNum, readres);
- }
-
- /*
- * Test method for 'java.nio.channels.Channels.NewChannel'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newChannel",
- args = {java.io.InputStream.class}
- )
- public void testNewChannelInputStream() throws IOException {
- int bufSize = 10;
- int readres = 0;
- byte[] byteArray = new byte[bufSize];
- ByteBuffer byteBuf = ByteBuffer.allocate(bufSize);
- this.fins = new FileInputStream(tmpFile);
- readres = this.fins.read(byteArray);
-
- assertEquals(bufSize, readres);
- assertFalse(0 == this.fins.available());
-
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- // fins still reads.
- assertFalse(0 == this.fins.available());
- readres = this.fins.read(byteArray);
- assertEquals(bufSize, readres);
-
- // rbChannel also reads.
- assertNotNull(rbChannel);
- readres = rbChannel.read(byteBuf);
-
- assertEquals(bufSize, readres);
- InputStream ins = Channels.newInputStream(rbChannel);
- assertNotNull(ins);
- assertEquals(0, ins.available());
- }
-
- // test if fout to change is null
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newChannel",
- args = {java.io.OutputStream.class}
- )
- public void testNewChannelOutputStream_inputNull() throws IOException {
- int writeres = this.testNum;
- ByteBuffer writebuf = ByteBuffer.allocate(this.writebufSize);
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf.putChar((char) (val + 64));
- }
- this.fouts = null;
- WritableByteChannel rbChannel = Channels.newChannel(this.fouts);
- writeres = rbChannel.write(writebuf);
- assertEquals(0, writeres);
-
- writebuf.flip();
- try {
- writeres = rbChannel.write(writebuf);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- }
- }
-
- // test if write buf is null
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newChannel",
- args = {java.io.OutputStream.class}
- )
- public void testNewChannelOutputStream_BufNull() throws IOException {
- int writeres = this.testNum;
- ByteBuffer writebuf = null;
- try {
- this.fouts = new FileOutputStream(tmpFile);
- } catch (FileNotFoundException e) {
- fail();
- }
-
- WritableByteChannel rbChannel = Channels.newChannel(this.fouts);
- try {
- writeres = rbChannel.write(writebuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(this.testNum, writeres);
- }
-
- /*
- * Test method for 'java.nio.channels.Channels.NewChannel(OutputStream)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newChannel",
- args = {java.io.OutputStream.class}
- )
- public void testNewChannelOutputStream() throws IOException {
- int writeNum = 0;
- ByteBuffer writebuf = ByteBuffer.allocateDirect(this.writebufSize);
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf.putChar((char) (val + 64));
- }
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel testChannel = this.fouts.getChannel();
- WritableByteChannel rbChannel = Channels.newChannel(this.fouts);
-
- assertTrue(testChannel.isOpen());
- assertTrue(rbChannel.isOpen());
-
- byte[] bit = new byte[1];
- bit[0] = 80;
- this.fouts.write(bit);
- this.fouts.flush();
- this.fins = new FileInputStream(tmpFile);
- assertEquals(this.fins.available(), 1);
- this.fins.close();
-
- writeNum = rbChannel.write(writebuf);
- // write success ,but output null
- assertEquals(0, writeNum);
- // close of fouts does not affect on channel
- this.fouts.close();
- writeNum = rbChannel.write(writebuf);
- assertEquals(0, writeNum);
- try {
- writeNum = testChannel.write(writebuf);
- fail();
- } catch (ClosedChannelException e) {
- // correct
- }
- assertEquals(0, writeNum);
- // close of rbchannel does affect on testchannel(same channel)
- rbChannel.close();
- try {
- writeNum = testChannel.write(writebuf);
- fail();
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newInputStream",
- args = {java.nio.channels.ReadableByteChannel.class}
- )
- public void testNewInputStreamReadableByteChannel_InputNull()
- throws Exception {
- byte[] readbuf = new byte[this.testNum];
- this.fins = new FileInputStream(tmpFile);
- ReadableByteChannel readbc = this.fins.getChannel();
- assertEquals(this.fileSize, this.fins.available());
- assertTrue(readbc.isOpen());
- InputStream testins = Channels.newInputStream(null);
- assertNotNull(testins);
-
- try {
- testins.read(readbuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, testins.available());
- try {
- testins.close();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newInputStream",
- args = {java.nio.channels.ReadableByteChannel.class}
- )
- public void testNewInputStreamReadableByteChannel() throws Exception {
- ByteBuffer readbcbuf = ByteBuffer.allocateDirect(this.testNum);
- byte[] readbuf = new byte[this.testNum];
- this.fins = new FileInputStream(tmpFile);
- ReadableByteChannel readbc = this.fins.getChannel();
- assertEquals(this.fileSize, this.fins.available());
- assertTrue(readbc.isOpen());
- InputStream testins = Channels.newInputStream(readbc);
- // read in testins and fins use the same pointer
- testins.read(readbuf);
- assertEquals(this.fins.available(), this.fileSize - this.testNum);
- int readNum = readbc.read(readbcbuf);
- assertEquals(readNum, this.testNum);
- assertEquals(this.fins.available(), this.fileSize - this.testNum * 2);
- testins.read(readbuf);
- assertEquals(this.fins.available(), this.fileSize - this.testNum * 3);
-
- assertFalse(testins.markSupported());
- try {
- testins.mark(10);
- } catch (UnsupportedOperationException e) {
- // expected;
- }
-
- try {
- testins.reset();
- } catch (IOException e) {
- // expected;
- }
-
- // readbc.close() affect testins
- readbc.close();
- assertFalse(readbc.isOpen());
- try {
- testins.read(readbuf);
- fail();
- } catch (ClosedChannelException e) {
- // correct
- }
-
- // Read methods throw IllegalBlockingModeException if underlying channel
- // is in non-blocking mode.
- SocketChannel chan = SocketChannel.open();
- chan.configureBlocking(false);
- testins = Channels.newInputStream(chan);
- try {
- testins.read();
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- testins.read(new byte[1]);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- testins.read(new byte[1], 0, 1);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newOutputStream",
- args = {java.nio.channels.WritableByteChannel.class}
- )
- public void testNewOutputStreamWritableByteChannel_InputNull()
- throws Exception {
- byte[] writebuf = new byte[this.testNum];
- OutputStream testouts = Channels.newOutputStream(null);
- assertNotNull(testouts);
- try {
- testouts.write(writebuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- testouts.flush();
- try {
- testouts.close();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- WritableByteChannel writebc = Channels.newChannel((OutputStream) null);
- assertTrue(writebc.isOpen());
- OutputStream testoutputS = Channels.newOutputStream(writebc);
- try {
- testoutputS.write(writebuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newOutputStream",
- args = {java.nio.channels.WritableByteChannel.class}
- )
- public void testNewOutputStreamWritableByteChannel() throws Exception {
- byte[] writebuf = new byte[this.testNum];
- ByteBuffer writebcbuf = ByteBuffer.allocateDirect(this.testNum);
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel writebc = this.fouts.getChannel();
-
- assertTrue(writebc.isOpen());
- OutputStream testouts = Channels.newOutputStream(writebc);
-
- // read in testins and fins use the same pointer
- testouts.write(writebuf);
- this.assertFileSizeSame(tmpFile, this.testNum);
- writebc.write(writebcbuf);
- this.assertFileSizeSame(tmpFile, this.testNum * 2);
- testouts.write(writebuf);
- this.assertFileSizeSame(tmpFile, this.testNum * 3);
- // readbc.close() affect testins
- writebc.close();
- assertFalse(writebc.isOpen());
- try {
- testouts.write(writebuf);
- fail();
- } catch (ClosedChannelException e) {
- // correct
- }
-
- // Write methods throw IllegalBlockingModeException if underlying
- // channel is in non-blocking mode.
- SocketChannel chan = SocketChannel.open();
- chan.configureBlocking(false);
- testouts = Channels.newOutputStream(chan);
- try {
- testouts.write(10);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- testouts.write(new byte[1]);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- testouts.write(new byte[1], 0, 1);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedCharsetException.",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.nio.charset.CharsetDecoder.class, int.class}
- )
- public void testnewReaderCharsetError() throws Exception {
- this.fins = new FileInputStream(tmpFile);
-
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- try {
- Channels.newReader(rbChannel, Charset.forName(BAD_CODE_SET)
- .newDecoder(),
- -1);
- fail();
- } catch (UnsupportedCharsetException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedCharsetException.",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.lang.String.class}
- )
- public void testnewReaderCharsetError2() throws Exception {
- this.fins = new FileInputStream(tmpFile);
-
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- try {
- Channels.newReader(rbChannel, BAD_CODE_SET);
- fail();
- } catch (UnsupportedCharsetException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedCharsetException.",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.nio.charset.CharsetEncoder.class, int.class}
- )
- public void testnewWriterCharsetError() throws Exception {
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- try {
- Channels.newWriter(wbChannel, Charset.forName(BAD_CODE_SET)
- .newEncoder(), -1);
- fail();
- } catch (UnsupportedCharsetException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedCharsetException.",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.lang.String.class}
- )
- public void testnewWriterCharsetError2() throws Exception {
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- try {
- Channels.newWriter(wbChannel, BAD_CODE_SET);
- fail();
- } catch (UnsupportedCharsetException e) {
- // correct
- }
- }
-
- /*
- * Test method for
- * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.nio.charset.CharsetDecoder.class, int.class}
- )
- public void testNewReaderReadableByteChannelCharsetDecoderI_InputNull()
- throws IOException {
- int bufSize = this.testNum;
- int readres = 0;
- CharBuffer charBuf = CharBuffer.allocate(bufSize);
- this.fins = new FileInputStream(tmpFile);
- // channel null
- Reader testReader = Channels.newReader(null, Charset.forName(CODE_SET)
- .newDecoder(), -1);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read((CharBuffer) null);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, readres);
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
-
- this.fins = null;
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- // channel with null inputs
- testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET)
- .newDecoder(),
- -1);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * Test method for
- * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.lang.String.class}
- )
- public void testNewReaderReadableByteChannelString_InputNull()
- throws IOException {
- int bufSize = this.testNum;
- int readres = 0;
- CharBuffer charBuf = CharBuffer.allocate(bufSize);
- this.fins = new FileInputStream(tmpFile);
- // channel null
- Reader testReader = Channels.newReader(null, CODE_SET);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read((CharBuffer) null);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, readres);
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
-
- this.fins = null;
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- // channel with null inputs
- testReader = Channels.newReader(rbChannel, CODE_SET);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * Test method for
- * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.nio.charset.CharsetDecoder.class, int.class}
- )
- public void testNewReaderReadableByteChannelCharsetDecoderI_internalBufferZero()
- throws IOException {
- int bufSize = this.testNum;
- int readres = 0;
- CharBuffer charBuf = CharBuffer.allocate(bufSize);
- this.fins = new FileInputStream(tmpFile);
- // channel null
- Reader testReader = Channels.newReader(null, Charset.forName(CODE_SET)
- .newDecoder(),
- 0);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read((CharBuffer) null);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, readres);
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- this.fins = null;
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- // channel with null inputs
- testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET)
- .newDecoder(),
- -1);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * Test method for
- * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.lang.String.class}
- )
- public void testNewReaderReadableByteChannelString_internalBufferZero()
- throws IOException {
- int bufSize = this.testNum;
- int readres = 0;
- CharBuffer charBuf = CharBuffer.allocate(bufSize);
- this.fins = new FileInputStream(tmpFile);
- // channel null
- Reader testReader = Channels.newReader(null, CODE_SET);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read((CharBuffer) null);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, readres);
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- this.fins = null;
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- // channel with null inputs
- testReader = Channels.newReader(rbChannel, CODE_SET);
- assertNotNull(testReader);
- assertFalse(testReader.ready());
- try {
- readres = testReader.read(charBuf);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * Test method for
- * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newReader",
- args = {java.nio.channels.ReadableByteChannel.class, java.nio.charset.CharsetDecoder.class, int.class}
- )
- })
- public void testNewReaderReadableByteChannel() throws IOException {
- int bufSize = this.testNum;
- int readres = 0;
- CharBuffer charBuf = CharBuffer.allocate(bufSize);
- this.fins = new FileInputStream(tmpFile);
- ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
- Reader testReader = Channels.newReader(rbChannel, Charset.forName(
- CODE_SET).newDecoder(),
- -1);
- Reader testReader_s = Channels.newReader(rbChannel, CODE_SET);
-
- assertEquals(this.fileSize, this.fins.available());
- // not ready...
- assertFalse(testReader.ready());
- assertFalse(testReader_s.ready());
- // still reads
- readres = testReader.read(charBuf);
- assertEquals(bufSize, readres);
- assertEquals(0, this.fins.available());
-
- try {
- readres = testReader.read((CharBuffer) null);
- fail();
- } catch (NullPointerException e) {
- // correct
- }
-
- readres = testReader_s.read(charBuf);
- assertEquals(0, readres);
- assertTrue(testReader.ready());
- assertFalse(testReader_s.ready());
- }
-
- /*
- * Zero-Buffer
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.nio.charset.CharsetEncoder.class, int.class}
- )
- public void testNewWriterWritableByteChannelCharsetEncoderI_internalBufZero()
- throws IOException {
-
- String writebuf = "";
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- // null channel
- Writer testWriter = Channels.newWriter(null, Charset.forName(CODE_SET)
- .newEncoder(),
- -1);
- // can write to buffer
- testWriter.write(writebuf);
- try {
- testWriter.flush();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- try {
- testWriter.close();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
-
- // channel with null input
- this.fouts = null;
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- testWriter = Channels.newWriter(wbChannel, Charset.forName(CODE_SET)
- .newEncoder(),
- -1);
- // can write to buffer
- testWriter.write(writebuf);
- try {
- testWriter.flush();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- try {
- testWriter.close();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * Zero-Buffer
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.lang.String.class}
- )
- public void testNewWriterWritableByteChannelString_internalBufZero()
- throws IOException {
-
- String writebuf = "";
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- // null channel
- Writer testWriter = Channels.newWriter(null, CODE_SET);
- // can write to buffer
- testWriter.write(writebuf);
- try {
- testWriter.flush();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- try {
- testWriter.close();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
-
- // channel with null input
- this.fouts = null;
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- testWriter = Channels.newWriter(wbChannel, CODE_SET);
- // can write to buffer
- testWriter.write(writebuf);
- try {
- testWriter.flush();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- try {
- testWriter.close();
- fail();
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * this test cannot be passed when buffer set to 0!
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.nio.charset.CharsetEncoder.class, int.class}
- )
- public void testNewWriterWritableByteChannelCharsetEncoderI_InputNull()
- throws IOException {
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- Writer testWriter = Channels.newWriter(wbChannel, Charset.forName(
- CODE_SET).newEncoder(),
- 1);
-
- String writebuf = "";
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- // can write to buffer
- testWriter.write(writebuf);
- testWriter.flush();
- testWriter.close();
-
- }
-
- /*
- * this test cannot be passed when buffer set to 0!
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.lang.String.class}
- )
- public void testNewWriterWritableByteChannelString_InputNull()
- throws IOException {
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- Writer testWriter = Channels.newWriter(wbChannel, CODE_SET);
-
- String writebuf = "";
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- // can write to buffer
- testWriter.write(writebuf);
- testWriter.flush();
- testWriter.close();
-
- }
-
- /*
- * Test method for
- * 'java.nio.channels.Channels.newWriter(WritableByteChannel, String)'
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.nio.charset.CharsetEncoder.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newWriter",
- args = {java.nio.channels.WritableByteChannel.class, java.lang.String.class}
- )
- })
- public void testNewWriterWritableByteChannelString() throws IOException {
- this.fouts = new FileOutputStream(tmpFile);
- WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
- Writer testWriter = Channels.newWriter(wbChannel, CODE_SET);
- Writer testWriter_s = Channels.newWriter(wbChannel, Charset.forName(
- CODE_SET).newEncoder(),
- -1);
-
- String writebuf = "";
- for (int val = 0; val < this.writebufSize / 2; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- byte[] bit = new byte[1];
- bit[0] = 80;
- this.fouts.write(bit);
- this.assertFileSizeSame(tmpFile, 1);
-
- // writer continues to write after '1',what the fouts write
- testWriter.write(writebuf);
- testWriter.flush();
- this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
- // testwriter_s does not know if testwrite writes
- testWriter_s.write(writebuf);
- testWriter.flush();
- this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
- // testwriter_s even does not know if himself writes?
- testWriter_s.write(writebuf);
- testWriter.flush();
- this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
-
- // close the fouts, no longer writable for testWriter
- for (int val = 0; val < this.writebufSize; val++) {
- writebuf = writebuf + ((char) (val + 64));
- }
- this.fouts.close();
- testWriter_s.write(writebuf);
- testWriter.flush();
- this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
-
- SocketChannel chan = SocketChannel.open();
- chan.configureBlocking(false);
- Writer writer = Channels.newWriter(chan, CODE_SET);
- try {
- writer.write(10);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write(new char[10]);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write("test");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write(new char[10], 0, 1);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write("test", 0, 1);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
-
- writer = Channels.newWriter(chan, Charset.forName(
- CODE_SET).newEncoder(),
- -1);
- try {
- writer.write(10);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write(new char[10]);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write("test");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write(new char[10], 0, 1);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- writer.write("test", 0, 1);
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Channels#newReader(ReadableByteChannel channel,
- * String charsetName)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalBlockingModeException.",
- method = "newInputStream",
- args = {java.nio.channels.ReadableByteChannel.class}
- )
- public void test_newInputStream_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());
-
- Reader reader = Channels.newReader(sc, "UTF16");
- int i = reader.read();
- assertEquals(-1, i);
-
- try {
- Channels.newInputStream(sc).read();
- fail("should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
-
- sc.close();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
deleted file mode 100644
index 85b9649..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
+++ /dev/null
@@ -1,87 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.ClosedByInterruptException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for ClosedByInterruptException
- */
-@TestTargetClass(ClosedByInterruptException.class)
-public class ClosedByInterruptExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.ClosedByInterruptException#ClosedByInterruptException()}
- */
- public void test_Constructor() {
- ClosedByInterruptException e = new ClosedByInterruptException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ClosedByInterruptException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new ClosedByInterruptException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ClosedByInterruptException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new ClosedByInterruptException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java
deleted file mode 100644
index de58615..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.ClosedChannelException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for ClosedChannelException
- */
-@TestTargetClass(ClosedChannelException.class)
-public class ClosedChannelExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.ClosedChannelException#ClosedChannelException()}
- */
- public void test_Constructor() {
- ClosedChannelException e = new ClosedChannelException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ClosedChannelException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new ClosedChannelException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ClosedChannelException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new ClosedChannelException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java
deleted file mode 100644
index c1a9ecd..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.ClosedSelectorException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for ClosedSelectorException
- */
-@TestTargetClass(ClosedSelectorException.class)
-public class ClosedSelectorExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.ClosedSelectorException#ClosedSelectorException()}
- */
- public void test_Constructor() {
- ClosedSelectorException e = new ClosedSelectorException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ClosedSelectorException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new ClosedSelectorException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ClosedSelectorException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new ClosedSelectorException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java
deleted file mode 100644
index 30749fe..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-
-import java.nio.channels.ConnectionPendingException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for ConnectionPendingException
- */
-@TestTargetClass(ConnectionPendingException.class)
-public class ConnectionPendingExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.ConnectionPendingException#ConnectionPendingException()}
- */
- public void test_Constructor() {
- ConnectionPendingException e = new ConnectionPendingException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ConnectionPendingException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new ConnectionPendingException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "ConnectionPendingException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new ConnectionPendingException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java
deleted file mode 100644
index b304d45..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/DatagramChannelTest.java
+++ /dev/null
@@ -1,4703 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-import java.nio.channels.AsynchronousCloseException;
-import java.nio.channels.ClosedByInterruptException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.DatagramChannel;
-import java.nio.channels.IllegalBlockingModeException;
-import java.nio.channels.NotYetConnectedException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.UnresolvedAddressException;
-import java.nio.channels.UnsupportedAddressTypeException;
-import java.nio.channels.spi.SelectorProvider;
-
-import junit.framework.TestCase;
-import tests.support.Support_PortManager;
-
-/**
- * Test for DatagramChannel
- *
- */
-@TestTargetClass(
- value = DatagramChannel.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "connect",
- args = {java.net.SocketAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "connect",
- args = {java.net.SocketAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- }
-)
-public class DatagramChannelTest extends TestCase {
-
- private static final int CAPACITY_NORMAL = 200;
-
- private static final int CAPACITY_1KB = 1024;
-
- private static final int CAPACITY_64KB = 65536;
-
- private static final int CAPACITY_ZERO = 0;
-
- private static final int CAPACITY_ONE = 1;
-
- private static final int TIME_UNIT = 500;
-
- private InetSocketAddress localAddr1;
-
- private InetSocketAddress localAddr2;
-
- private DatagramChannel channel1;
-
- private DatagramChannel channel2;
-
- private DatagramSocket datagramSocket1;
-
- private DatagramSocket datagramSocket2;
-
- // The port to be used in test cases.
- private int testPort;
-
- protected void setUp() throws Exception {
- super.setUp();
- this.channel1 = DatagramChannel.open();
- this.channel2 = DatagramChannel.open();
- int[] ports = Support_PortManager.getNextPortsForUDP(5);
- this.localAddr1 = new InetSocketAddress("127.0.0.1", ports[0]);
- this.localAddr2 = new InetSocketAddress("127.0.0.1", ports[1]);
- this.datagramSocket1 = new DatagramSocket(ports[2]);
- this.datagramSocket2 = new DatagramSocket(ports[3]);
- testPort = ports[4];
- }
-
- protected void tearDown() throws Exception {
- if (null != this.channel1) {
- try {
- this.channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.channel2) {
- try {
- this.channel2.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.datagramSocket1) {
- try {
- this.datagramSocket1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.datagramSocket2) {
- try {
- this.datagramSocket2.close();
- } catch (Exception e) {
- //ignore
- }
- }
- localAddr1 = null;
- localAddr2 = null;
- super.tearDown();
- }
-
- // -------------------------------------------------------------------
- // Test for methods in abstract class.
- // -------------------------------------------------------------------
- /*
- * Test method for 'java.nio.channels.DatagramChannel()'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramChannel",
- args = {java.nio.channels.spi.SelectorProvider.class}
- )
- public void testConstructor() throws IOException {
- DatagramChannel channel =
- SelectorProvider.provider().openDatagramChannel();
- assertNotNull(channel);
- assertSame(SelectorProvider.provider(),channel.provider());
- channel = DatagramChannel.open();
- assertNotNull(channel);
- assertSame(SelectorProvider.provider(), channel.provider());
- }
-
- /*
- * Test method for 'java.nio.channels.DatagramChannel.validOps()'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "validOps",
- args = {}
- )
- public void testValidOps() {
- MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
- .provider());
- MockDatagramChannel testMocknull = new MockDatagramChannel(null);
- int val = this.channel1.validOps();
- assertEquals(5, val);
- assertEquals(val, testMock.validOps());
- assertEquals(val, testMocknull.validOps());
- }
-
- /*
- * Test method for 'java.nio.channels.DatagramChannel.open()'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the result of the setUp method.",
- method = "open",
- args = {}
- )
- public void testOpen() {
- MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
- .provider());
- MockDatagramChannel testMocknull = new MockDatagramChannel(null);
- assertNull(testMocknull.provider());
- assertNotNull(testMock.provider());
- assertEquals(this.channel1.provider(), testMock.provider());
- assertEquals(5, testMock.validOps());
- }
-
- /*
- * Test method for 'java.nio.channels.DatagramChannel.open()'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
- public void testIsOpen() throws Exception {
- assertTrue(this.channel1.isOpen());
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies default status of DatagramChannel.",
- method = "validOps",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies default status of DatagramChannel.",
- method = "provider",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies default status of DatagramChannel.",
- method = "isRegistered",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies default status of DatagramChannel.",
- method = "isBlocking",
- args = {}
- )
- })
- public void testChannelBasicStatus() {
- DatagramSocket gotSocket = this.channel1.socket();
- assertFalse(gotSocket.isClosed());
- assertTrue(this.channel1.isBlocking());
- assertFalse(this.channel1.isRegistered());
- assertEquals((SelectionKey.OP_READ | SelectionKey.OP_WRITE),
- this.channel1.validOps());
- assertEquals(SelectorProvider.provider(), this.channel1.provider());
- }
-
- /*
- * Test method for 'java.nio.channels.DatagramChannel.read(ByteBuffer)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testReadByteBufferArray() throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.read(readBuf);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- assertEquals(0, this.channel1.read(readBuf));
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- assertEquals(0, this.channel1.read(readBuf));
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testReadByteBufferArray_ConnectedBufNull()
- throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- try {
- this.channel1.read((ByteBuffer[])null);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- datagramSocket1.close();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testReadByteBufferArray_NotConnectedBufNull()
- throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.read((ByteBuffer[])null);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- }
-
- /*
- * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify all exceptions according to specification.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testWriteByteBufferArray_Block() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.write(writeBuf);
- fail("Should throw NotYetConnectedException.");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf));
- // cannot be buffered again!
- assertEquals(0, this.channel1.write(writeBuf));
- }
-
- public void disabled_testWriteByteBufferArray_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.write(targetBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- public void disabled_testWriteByteBufferArray_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
- channel1.write(targetBuf);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- /*
- * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testWriteByteBufferArray_NonBlock() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- // non-block mode
- this.channel1.configureBlocking(false);
- try {
- this.channel1.write(writeBuf);
- fail("Should throw NotYetConnectedException.");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf));
- // cannot be buffered again!
- assertEquals(0, this.channel1.write(writeBuf));
- this.channel1.close();
- try {
- this.channel1.write(writeBuf, 0, 1);
- fail("Should throw ClosedChannelEception.");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testWriteByteBufferArray_BlockClosed() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- // non-block mode
- this.channel1.configureBlocking(false);
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.close();
- try {
- channel1.write(writeBuf);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testWriteByteBufferArray_NonBlockClosed() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.close();
- try {
- channel1.write(writeBuf);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- /*
- * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testWriteByteBufferArray_NotConnectedBufNull()
- throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- try {
- this.channel1.write((ByteBuffer[])null);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- }
-
- /*
- * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testWriteByteBufferArray_ConnectedBufNull()
- throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- try {
- this.channel1.write((ByteBuffer[])null);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // correct
- }
- datagramSocket1.close();
- try {
- this.channel1.write((ByteBuffer[])null);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- // -------------------------------------------------------------------
- // Test for socket()
- // -------------------------------------------------------------------
-
- /**
- * Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws SocketException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_BasicStatusBeforeConnect() throws SocketException {
- assertFalse(this.channel1.isConnected());// not connected
- DatagramSocket s1 = this.channel1.socket();
- assertSocketBeforeConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
- // same
- assertSame(s1, s2);
- }
-
- /**
- * Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
- this.channel1.connect(localAddr1);
- DatagramSocket s1 = this.channel1.socket();
- assertSocketAfterConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
- // same
- assertSame(s1, s2);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_NonBlock_BasicStatusAfterConnect()
- throws IOException {
- this.channel1.connect(localAddr1);
- this.channel1.configureBlocking(false);
- DatagramSocket s1 = this.channel1.socket();
- assertSocketAfterConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
- // same
- assertSame(s1, s2);
- }
-
- /**
- * Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_ActionsBeforeConnect() throws IOException {
- assertFalse(this.channel1.isConnected());// not connected
- DatagramSocket s = this.channel1.socket();
- assertSocketActionBeforeConnect(s);
- }
-
- /**
- * Test method for 'DatagramChannelImpl.socket()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_Block_ActionsAfterConnect() throws IOException {
- assertFalse(this.channel1.isConnected());// not connected
- this.channel1.connect(localAddr1);
- DatagramSocket s = this.channel1.socket();
- assertSocketActionAfterConnect(s);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_NonBlock_ActionsAfterConnect() throws IOException {
- this.channel1.connect(localAddr1);
- this.channel1.configureBlocking(false);
- DatagramSocket s = this.channel1.socket();
- assertSocketActionAfterConnect(s);
- }
-
- private void assertSocketBeforeConnect(DatagramSocket s)
- throws SocketException {
- assertFalse(s.isBound());
- assertFalse(s.isClosed());
- assertFalse(s.isConnected());
- assertFalse(s.getBroadcast());
- assertFalse(s.getReuseAddress());
- assertNull(s.getInetAddress());
- assertTrue(s.getLocalAddress().isAnyLocalAddress());
- assertEquals(s.getLocalPort(), 0);
- assertNull(s.getLocalSocketAddress());
- assertEquals(s.getPort(), -1);
- assertTrue(s.getReceiveBufferSize() >= 8192);
- assertNull(s.getRemoteSocketAddress());
- assertFalse(s.getReuseAddress());
- assertTrue(s.getSendBufferSize() >= 8192);
- assertEquals(s.getSoTimeout(), 0);
- assertEquals(s.getTrafficClass(), 0);
- }
-
- private void assertSocketAfterConnect(DatagramSocket s)
- throws SocketException {
- assertTrue(s.isBound());
- assertFalse(s.isClosed());
- assertTrue(s.isConnected());
- assertFalse(s.getBroadcast());
- assertFalse(s.getReuseAddress());
- assertSame(s.getInetAddress(), localAddr1.getAddress());
- assertEquals(s.getLocalAddress(), localAddr1.getAddress());
- assertNotNull(s.getLocalSocketAddress());
- assertEquals(s.getPort(), localAddr1.getPort());
- assertTrue(s.getReceiveBufferSize() >= 8192);
- // not same , but equals
- assertNotSame(s.getRemoteSocketAddress(), localAddr1);
- assertEquals(s.getRemoteSocketAddress(), localAddr1);
- assertFalse(s.getReuseAddress());
- assertTrue(s.getSendBufferSize() >= 8192);
- assertEquals(s.getSoTimeout(), 0);
- assertEquals(s.getTrafficClass(), 0);
- }
-
- private void assertSocketActionBeforeConnect(DatagramSocket s)
- throws IOException {
- s.connect(localAddr2);
- assertFalse(this.channel1.isConnected());
- assertFalse(s.isConnected());
-
- s.disconnect();
- assertFalse(this.channel1.isConnected());
- assertFalse(s.isConnected());
-
- s.close();
- assertTrue(s.isClosed());
- assertFalse(this.channel1.isOpen());
- }
-
- private void assertSocketActionAfterConnect(DatagramSocket s)
- throws IOException {
- assertEquals(s.getPort(), localAddr1.getPort());
- s.connect(localAddr2);
- assertTrue(this.channel1.isConnected());
- assertTrue(s.isConnected());
- // not changed
- assertEquals(s.getPort(), localAddr1.getPort());
-
- s.disconnect();
- assertFalse(this.channel1.isConnected());
- assertFalse(s.isConnected());
-
- s.close();
- assertTrue(s.isClosed());
- assertFalse(this.channel1.isOpen());
- }
-
- // -------------------------------------------------------------------
- // Test for configureBlocking()
- // -------------------------------------------------------------------
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {ByteBuffer.class}
- )
- public void testConfigureBlocking_Read() throws Exception {
- assertTrue(this.channel1.isBlocking());
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_1KB);
- new Thread() {
- public void run() {
- try {
- sleep(TIME_UNIT * 5);
- channel1.configureBlocking(false);
- assertFalse(channel1.isBlocking());
- datagramSocket1.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }.start();
- SocketAddress addr = channel1.receive(buf);
- assertNull(addr);
- }
-
- // -------------------------------------------------------------------
- // Test for isConnected()
- // -------------------------------------------------------------------
-
- /**
- * Test method for 'DatagramChannelImpl.isConnected()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isConnected",
- args = {}
- )
- public void testIsConnected_WithServer() throws IOException {
- connectLocalServer();
- assertTrue(this.channel1.isConnected());
- disconnectAfterConnected();
- this.datagramSocket1.close();
- this.channel1.close();
- assertFalse(this.channel1.isConnected());
- }
-
- // -------------------------------------------------------------------
- // Test for connect()
- // -------------------------------------------------------------------
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_BlockWithServer() throws IOException {
- // blocking mode
- assertTrue(this.channel1.isBlocking());
- connectLocalServer();
- datagramSocket1.close();
- disconnectAfterConnected();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_BlockNoServer() throws IOException {
- connectWithoutServer();
- disconnectAfterConnected();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_NonBlockWithServer() throws IOException {
- // Non blocking mode
- this.channel1.configureBlocking(false);
- connectLocalServer();
- datagramSocket1.close();
- disconnectAfterConnected();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_Null() throws IOException {
- assertFalse(this.channel1.isConnected());
- try {
- this.channel1.connect(null);
- fail("Should throw an IllegalArgumentException here.");
- } catch (IllegalArgumentException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedAddressTypeException.",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_UnsupportedType() throws IOException {
- assertFalse(this.channel1.isConnected());
- class SubSocketAddress extends SocketAddress {
- private static final long serialVersionUID = 1L;
-
- public SubSocketAddress() {
- super();
- }
- }
- SocketAddress newTypeAddress = new SubSocketAddress();
- try {
- this.channel1.connect(newTypeAddress);
- fail("Should throw an UnsupportedAddressTypeException here.");
- } catch (UnsupportedAddressTypeException e) {
- // OK.
- }
- }
-
- public void disabled_testConnect_Block_close() throws Exception {
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.connect(localAddr1);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- public void disabled_testConnect_Block_interrupt() throws Exception {
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- channel1.connect(localAddr1);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnresolvedAddressException.",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_Unresolved() throws IOException {
- assertFalse(this.channel1.isConnected());
- InetSocketAddress unresolved = new InetSocketAddress(
- "unresolved address", 1080);
- try {
- this.channel1.connect(unresolved);
- fail("Should throw an UnresolvedAddressException here.");
- } catch (UnresolvedAddressException e) {
- // OK.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_EmptyHost() throws Exception {
- assertFalse(this.channel1.isConnected());
-
- assertEquals(this.channel1, this.channel1
- .connect(new InetSocketAddress("", 1081)));
-
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException.",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_ClosedChannelException() throws IOException {
- assertFalse(this.channel1.isConnected());
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- this.channel1.connect(localAddr1);
- fail("Should throw ClosedChannelException.");
- } catch (ClosedChannelException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalStateException.",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_IllegalStateException() throws IOException {
- assertFalse(this.channel1.isConnected());
- this.channel1.connect(localAddr1);
- assertTrue(this.channel1.isConnected());
- // connect after connected.
- try {
- this.channel1.connect(localAddr1);
- fail("Should throw IllegalStateException.");
- } catch (IllegalStateException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
- *
- * @throws IOException
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException.",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void testConnect_CheckOpenBeforeStatus() throws IOException {
- assertFalse(this.channel1.isConnected());
- this.channel1.connect(localAddr1);
- assertTrue(this.channel1.isConnected());
- // connect after connected.
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- // checking open is before checking status.
- try {
- this.channel1.connect(localAddr1);
- fail("Should throw ClosedChannelException.");
- } catch (ClosedChannelException e) {
- // OK.
- }
- }
-
- private void disconnectAfterConnected() throws IOException {
- assertTrue(this.channel1.isConnected());
- this.channel1.disconnect();
- assertFalse(this.channel1.isConnected());
- }
-
- private void disconnectAfterClosed() throws IOException {
- assertFalse(this.channel1.isOpen());
- assertFalse(this.channel1.isConnected());
- this.channel1.disconnect();
- assertFalse(this.channel1.isConnected());
- }
-
- private void connectLocalServer() throws IOException {
- assertFalse(this.channel1.isConnected());
- assertTrue(this.datagramSocket1.isBound());
- assertSame(this.channel1, this.channel1.connect(localAddr1));
- assertTrue(this.channel1.isConnected());
- }
-
- private void connectWithoutServer() throws IOException {
- assertFalse(this.channel1.isConnected());
- this.datagramSocket1.close();
- assertTrue(this.datagramSocket1.isClosed());
- assertSame(this.channel1, this.channel1.connect(localAddr1));
- assertTrue(this.channel1.isConnected());
- }
-
- // -------------------------------------------------------------------
- // Test for disconnect()
- // -------------------------------------------------------------------
-
- /**
- * Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IOException.",
- method = "disconnect",
- args = {}
- )
- public void testDisconnect_BeforeConnect() throws IOException {
- assertFalse(this.channel1.isConnected());
- assertEquals(this.channel1, this.channel1.disconnect());
- assertFalse(this.channel1.isConnected());
- }
-
- /**
- * Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void testDisconnect_UnconnectedClosed() throws IOException {
- assertFalse(this.channel1.isConnected());
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- assertEquals(this.channel1, this.channel1.disconnect());
- assertFalse(this.channel1.isConnected());
- }
-
- /**
- * Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void testDisconnect_BlockWithServerChannelClosed()
- throws IOException {
- assertTrue(this.channel1.isBlocking());
- connectLocalServer();
- // disconnect after channel close
- this.channel1.close();
- disconnectAfterClosed();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void testDisconnect_NonBlockWithServerChannelClosed()
- throws IOException {
- this.channel1.configureBlocking(false);
- connectLocalServer();
- // disconnect after channel close
- this.channel1.close();
- disconnectAfterClosed();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void testDisconnect_BlockWithServerServerClosed()
- throws IOException {
- assertTrue(this.channel1.isBlocking());
- connectLocalServer();
- // disconnect after server close
- this.datagramSocket1.close();
- assertTrue(this.channel1.isOpen());
- assertTrue(this.channel1.isConnected());
- disconnectAfterConnected();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.disconnect()'
- *
- * @throws IOException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void testDisconnect_NonBlockWithServerServerClosed()
- throws IOException {
- this.channel1.configureBlocking(false);
- assertFalse(this.channel1.isBlocking());
- connectLocalServer();
- // disconnect after server close
- this.datagramSocket1.close();
- assertTrue(this.channel1.isOpen());
- assertTrue(this.channel1.isConnected());
- disconnectAfterConnected();
- }
-
- // -------------------------------------------------------------------
- // Test for receive(): Behavior Without Server.
- // -------------------------------------------------------------------
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedNull() throws Exception {
- assertFalse(this.channel1.isConnected());
- try {
- this.channel1.receive(null);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedReadonly() throws Exception {
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
- .asReadOnlyBuffer();
- assertTrue(dst.isReadOnly());
- try {
- this.channel1.receive(dst);
- fail("Should throw an IllegalArgumentException here.");
- } catch (IllegalArgumentException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedBufEmpty() throws Exception {
- this.channel1.configureBlocking(false);
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- assertNull(this.channel1.receive(dst));
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedBufZero() throws Exception {
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ZERO);
- assertNull(this.channel1.receive(dst));
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedBufNotEmpty() throws Exception {
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- // buf is not empty
- dst.put((byte) 88);
- assertEquals(dst.position() + CAPACITY_NORMAL - 1, dst.limit());
- assertNull(this.channel1.receive(dst));
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedBufFull() throws Exception {
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
- // buf is full
- dst.put((byte) 88);
- assertEquals(dst.position(), dst.limit());
- assertNull(this.channel1.receive(dst));
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedClose() throws Exception {
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- assertNull(this.channel1.receive(dst));
- fail("Should throw a ClosedChannelException here.");
- } catch (ClosedChannelException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedCloseNull() throws Exception {
- assertFalse(this.channel1.isConnected());
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- // checking buffer before checking open
- try {
- this.channel1.receive(null);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_UnconnectedCloseReadonly() throws Exception {
- assertFalse(this.channel1.isConnected());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
- .asReadOnlyBuffer();
- assertTrue(dst.isReadOnly());
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- this.channel1.receive(dst);
- fail("Should throw an IllegalArgumentException here.");
- } catch (IllegalArgumentException e) {
- // OK.
- }
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerBufEmpty() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNonBlockNoServer(CAPACITY_NORMAL);
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_BlockNoServerNull() throws Exception {
- assertTrue(this.channel1.isBlocking());
- receiveNoServerNull();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerNull() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNoServerNull();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_BlockNoServerReadonly() throws Exception {
- assertTrue(this.channel1.isBlocking());
- receiveNoServerReadonly();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerReadonly() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNoServerReadonly();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerBufZero() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNonBlockNoServer(CAPACITY_ZERO);
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerBufNotEmpty() throws Exception {
- this.channel1.configureBlocking(false);
- connectWithoutServer();
- ByteBuffer dst = allocateNonEmptyBuf();
- assertNull(this.channel1.receive(dst));
- }
-
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerBufFull() throws Exception {
- this.channel1.configureBlocking(false);
- connectWithoutServer();
- ByteBuffer dst = allocateFullBuf();
- assertNull(this.channel1.receive(dst));
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_BlockNoServerChannelClose() throws Exception {
- assertTrue(this.channel1.isBlocking());
- receiveNoServerChannelClose();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerChannelClose() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNoServerChannelClose();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_BlockNoServerCloseNull() throws Exception {
- assertTrue(this.channel1.isBlocking());
- receiveNoServerChannelCloseNull();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerCloseNull() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNoServerChannelCloseNull();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_NonBlockNoServerCloseReadonly() throws Exception {
- this.channel1.configureBlocking(false);
- receiveNoServerChannelCloseReadonly();
- }
-
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_BlockNoServerCloseReadonly() throws Exception {
- assertTrue(this.channel1.isBlocking());
- receiveNoServerChannelCloseReadonly();
- }
-
- private void receiveNoServerNull() throws IOException {
- connectWithoutServer();
- try {
- this.channel1.receive(null);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // OK.
- }
- }
-
- private void receiveNoServerReadonly() throws IOException {
- connectWithoutServer();
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
- .asReadOnlyBuffer();
- assertTrue(dst.isReadOnly());
- try {
- this.channel1.receive(dst);
- fail("Should throw an IllegalArgumentException here.");
- } catch (IllegalArgumentException e) {
- // OK.
- }
- }
-
- private void receiveNonBlockNoServer(int size) throws IOException {
- connectWithoutServer();
- ByteBuffer dst = ByteBuffer.allocateDirect(size);
- assertNull(this.channel1.receive(dst));
- }
-
- private void receiveNoServerChannelClose() throws IOException {
- connectWithoutServer();
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- assertNull(this.channel1.receive(dst));
- fail("Should throw a ClosedChannelException here.");
- } catch (ClosedChannelException e) {
- // OK.
- }
- }
-
- private void receiveNoServerChannelCloseNull() throws IOException {
- connectWithoutServer();
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- this.channel1.receive(null);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // OK.
- }
- }
-
- private void receiveNoServerChannelCloseReadonly() throws IOException {
- connectWithoutServer();
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
- .asReadOnlyBuffer();
- assertTrue(dst.isReadOnly());
- try {
- this.channel1.receive(dst);
- fail("Should throw an IllegalArgumentException here.");
- } catch (IllegalArgumentException e) {
- // OK.
- }
- }
-
- private ByteBuffer allocateFullBuf() {
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
- // buf is full
- dst.put((byte) 88);
- assertEquals(dst.position(), dst.limit());
- return dst;
- }
-
- private ByteBuffer allocateNonEmptyBuf() {
- ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- // buf is not empty
- dst.put((byte) 88);
- dst.put((byte) 99);
- assertEquals(dst.position() + CAPACITY_NORMAL - 2, dst.limit());
- return dst;
- }
-
- // -------------------------------------------------------------------
- // Test for send(): Behavior without server.
- // -------------------------------------------------------------------
-
- private void sendDataBlocking(InetSocketAddress addr, ByteBuffer writeBuf)
- throws IOException {
- InetSocketAddress ipAddr = addr;
- assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr));
- assertTrue(this.channel1.isOpen());
- assertTrue(this.channel1.isBlocking());
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- }
-
- private void sendDataNonBlocking(InetSocketAddress addr, ByteBuffer writeBuf)
- throws IOException {
- InetSocketAddress ipAddr = addr;
- this.channel1.configureBlocking(false);
- assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr));
- assertTrue(this.channel1.isOpen());
- assertFalse(this.channel1.isBlocking());
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- }
-
- /*
- * Test method for 'DatagramChannelImpl.send(ByteBuffer, SocketAddress)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerBlockingCommon() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataBlocking(localAddr1, writeBuf);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerNonblockingCommon() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataNonBlocking(localAddr1, writeBuf);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerTwice() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataBlocking(localAddr1, writeBuf);
- // can not buffer twice!
- assertEquals(0, this.channel1.send(writeBuf, localAddr1));
- try {
- channel1.send(writeBuf, localAddr2);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerNonBlockingTwice() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataNonBlocking(localAddr1, writeBuf);
- // can not buffer twice!
- assertEquals(0, this.channel1.send(writeBuf, localAddr1));
- try {
- channel1.send(writeBuf, localAddr2);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerBufNull() throws IOException {
- try {
- sendDataBlocking(localAddr1, null);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerBufNullTwice() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- try {
- sendDataBlocking(localAddr1, null);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // correct
- }
- sendDataBlocking(localAddr1, writeBuf);
- try {
- channel1.send(null, localAddr2);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "DOesn't verify all exceptions according to spec.",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerAddrNull() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- try {
- sendDataBlocking(null, writeBuf);
- fail("Should throw a NPE here.");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_NoServerAddrNullTwice() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- try {
- sendDataBlocking(null, writeBuf);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- sendDataBlocking(localAddr1, writeBuf);
- try {
- channel1.send(writeBuf, null);
- fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- // -------------------------------------------------------------------
- // Test for receive()and send(): Send and Receive with Real Data
- // -------------------------------------------------------------------
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Normal() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2,
- "some normal string in testReceiveSend_Normal");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_NotBound() throws Exception {
- // not bound
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
- assertNull(channel1.receive(buf));
- assertFalse(channel1.socket().isBound());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_NonBlock_NotBound() throws Exception {
- // not bound
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- ByteBuffer buf = ByteBuffer.wrap(new byte[CAPACITY_NORMAL]);
- assertNull(this.channel1.receive(buf));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Normal_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket(
- "some normal string in testReceiveSend_Normal_S2C", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2,
- "some normal string in testReceiveSend_Normal_S2C");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Normal_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- String str1 = "some normal string in testReceiveSend_Normal_C2S";
- sendByChannel(str1, localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_NonBlock_Normal_C2S() throws Exception {
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- String str1 = "some normal string in testReceiveSend_Normal_C2S";
- sendByChannel(str1, localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Normal_S2S() throws Exception {
- String msg = "normal string in testReceiveSend_Normal_S2S";
- this.datagramSocket1 = new DatagramSocket(testPort);
- DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
- localAddr2);
- datagramSocket2 = new DatagramSocket(localAddr2.getPort());
- this.datagramSocket1.send(rdp);
- byte[] buf = new byte[CAPACITY_NORMAL];
- this.datagramSocket2.setSoTimeout(TIME_UNIT);
- rdp = new DatagramPacket(buf, buf.length);
- this.datagramSocket2.receive(rdp);
- assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Empty() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_NonBlock_Empty() throws Exception {
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
- this.channel1.socket().bind(localAddr2);
- sendByChannel("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Empty_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_NonBlock_Empty_S2C() throws Exception {
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Empty_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("", localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_NonBlock_Empty_C2S() throws Exception {
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("", localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceiveSend_Empty_S2S() throws Exception {
- String msg = "";
- this.datagramSocket1 = new DatagramSocket(testPort);
- DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
- localAddr2);
- datagramSocket2 = new DatagramSocket(localAddr2.getPort());
- this.datagramSocket1.send(rdp);
- byte[] buf = new byte[CAPACITY_NORMAL];
- this.datagramSocket2.setSoTimeout(TIME_UNIT);
- rdp = new DatagramPacket(buf, buf.length);
- this.datagramSocket2.receive(rdp);
- assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Oversize() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("0123456789", localAddr2);
- receiveByChannel(5, localAddr2, "01234");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Oversize_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("0123456789", localAddr2);
- receiveByDatagramSocket(5, localAddr2, "01234");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_NonBlock_Oversize_C2S() throws Exception {
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("0123456789", localAddr2);
- receiveByDatagramSocket(5, localAddr2, "01234");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_Block_Oversize_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("0123456789", localAddr2);
- receiveByChannel(5, localAddr2, "01234");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- })
- public void testReceiveSend_8K() throws Exception {
- StringBuffer str8k = new StringBuffer();
- for (int i = 0; i < 8 * CAPACITY_1KB; i++) {
- str8k.append("a");
- }
- String str = str8k.toString();
- this.channel1.socket().bind(localAddr2);
- sendByChannel(str, localAddr2);
- receiveByChannel(8 * CAPACITY_1KB, localAddr2, str);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testReceiveSend_64K() throws Exception {
- StringBuffer str64k = new StringBuffer();
- for (int i = 0; i < CAPACITY_64KB; i++) {
- str64k.append("a");
- }
- String str = str64k.toString();
- try {
- Thread.sleep(TIME_UNIT);
- channel2.send(ByteBuffer.wrap(str.getBytes()), localAddr1);
- fail("Should throw SocketException!");
- } catch (SocketException e) {
- //expected
- }
- }
-
- private void sendByChannel(String data, InetSocketAddress address)
- throws Exception {
- try {
- assertEquals(data.length(), this.channel2.send(ByteBuffer.wrap(data
- .getBytes()), address));
- } finally {
- this.channel2.close();
- }
- }
-
- private void sendByDatagramSocket(String data, InetSocketAddress address)
- throws Exception {
- this.datagramSocket1 = new DatagramSocket(testPort);
- DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(),
- address);
- this.datagramSocket1.send(rdp);
- }
-
- private void receiveByChannel(int bufSize, InetSocketAddress address,
- String expectedString) throws IOException {
- try {
- ByteBuffer buf = ByteBuffer.wrap(new byte[bufSize]);
- InetSocketAddress returnAddr = null;
- long startTime = System.currentTimeMillis();
- do {
- returnAddr = (InetSocketAddress) this.channel1.receive(buf);
- // continue loop when channel1 is non-blocking and no data was
- // received.
- if (channel1.isBlocking() || null != returnAddr) {
- break;
- }
- // avoid dead loop
- assertTimeout(startTime, 10000);
- } while (true);
- int length = returnAddr.getAddress().getAddress().length;
- for (int i = 0; i < length; i++) {
- assertEquals(returnAddr.getAddress().getAddress()[i],
- InetAddress.getByName("127.0.0.1").getAddress()[i]);
- }
- // port is NOT equal
- assertFalse(returnAddr.getPort() == address.getPort());
- assertEquals(new String(buf.array(), 0, bufSize).trim(),
- expectedString);
- } finally {
- this.channel1.close();
- }
- }
-
- /*
- * Fails if the difference between current time and start time is greater
- * than timeout.
- */
- private void assertTimeout(long startTime, long timeout) {
- long currentTime = System.currentTimeMillis();
- if ((currentTime - startTime) > timeout) {
- fail("Timeout");
- }
- }
-
- private void receiveByDatagramSocket(int bufSize,
- InetSocketAddress address, String expectedString)
- throws IOException {
- byte[] buf = new byte[bufSize];
- this.datagramSocket1.setSoTimeout(6000);
- DatagramPacket rdp = new DatagramPacket(buf, buf.length);
- this.datagramSocket1.receive(rdp);
- assertEquals(new String(buf, 0, bufSize).trim(), expectedString);
- }
-
- // -------------------------------------------------------------------
- // Test for security check of receive and send
- // -------------------------------------------------------------------
-
- private class mockAddress extends SocketAddress {
- private static final long serialVersionUID = 1L;
- }
-
- public void disabled_testSend_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.send(targetBuf, localAddr1);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- public void disabled_testSend_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
- channel1.send(targetBuf, localAddr1);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.receive(targetBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "receive",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReceive_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
- channel1.receive(targetBuf);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- // -------------------------------------------------------------------
- // Test for write()
- // -------------------------------------------------------------------
-
- private void connectWriteBuf(InetSocketAddress ipAddr, ByteBuffer buf)
- throws IOException {
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- assertEquals(CAPACITY_NORMAL, this.channel1.write(buf));
- assertEquals(0, this.channel1.write(buf));
- }
-
- private void noconnectWrite(ByteBuffer buf) throws IOException {
- try {
- this.channel1.write(buf);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- }
-
- /*
- * Test method for 'DatagramChannelImpl.write(ByteBuffer)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_Block() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- connectWriteBuf(localAddr1, writeBuf);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_NonBlock() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- this.channel1.configureBlocking(false);
- connectWriteBuf(localAddr1, writeBuf);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_BlockClosed() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- noconnectWrite(writeBuf);
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.close();
- try {
- channel1.write(writeBuf);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_NonBlockClosed() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- // non block mode
- this.channel1.configureBlocking(false);
- noconnectWrite(writeBuf);
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.close();
- try {
- channel1.write(writeBuf);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_BlockBufNull() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.write((ByteBuffer) null);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- try {
- this.channel1.write((ByteBuffer) null);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, this.channel1.write(writeBuf));
- datagramSocket1.close();
- try {
- this.channel1.write((ByteBuffer) null);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_NonBlockBufNull() throws IOException {
- ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
-
- // non block mode
- this.channel1.configureBlocking(false);
-
- try {
- this.channel1.write((ByteBuffer) null);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- try {
- this.channel1.write((ByteBuffer) null);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, this.channel1.write(writeBuf));
- datagramSocket1.close();
- try {
- this.channel1.write((ByteBuffer) null);
- fail("Should throw NPE.");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- /*
- * Test method for 'DatagramChannelImpl.write(ByteBuffer[], int, int)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify all exceptions according to specification.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_Block() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.write(writeBuf, 0, 2);
- fail("Should throw NotYetConnectedException.");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
- // cannot be buffered again!
- assertEquals(0, this.channel1.write(writeBuf, 0, 1));
- this.channel1.close();
- try {
- this.channel1.write(writeBuf, 0, 1);
- fail("Should throw ClosedChannelEception.");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- public void disabled_testWriteByteBufferArrayII_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.write(targetBuf, 0 ,2);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- public void disabled_testWriteByteBufferArrayII_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
- channel1.write(targetBuf, 0, 2);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_NonBlock() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- // non-block mode
- this.channel1.configureBlocking(false);
- try {
- this.channel1.write(writeBuf, 0, 2);
- fail("Should throw NotYetConnectedException.");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
- // cannot be buffered again!
- assertEquals(0, this.channel1.write(writeBuf, 0, 1));
- this.channel1.close();
- try {
- this.channel1.write(writeBuf, 0, 1);
- fail("Should throw ClosedChannelEception.");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_BlockClosed() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- // non-block mode
- this.channel1.configureBlocking(false);
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.close();
- try {
- channel1.write(writeBuf, 0, 2);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_NonBlockClosed() throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.close();
- try {
- channel1.write(writeBuf, 0, 2);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_NotConnectedIndexBad()
- throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.write(writeBuf, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 1, 2);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 2, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 3, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_ConnectedIndexBad()
- throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- try {
- this.channel1.write(writeBuf, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 1, 2);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 2, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 3, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_NotConnectedBufNull()
- throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- try {
- this.channel1.write(null, 0, 20);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, 2);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testWriteByteBufferArrayII_ConnectedBufNull()
- throws IOException {
- ByteBuffer[] writeBuf = new ByteBuffer[2];
- writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- try {
- this.channel1.write(null, 0, 20);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, 2);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // correct
- }
- datagramSocket1.close();
- try {
- this.channel1.write(null, 0, 20);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.write(writeBuf, 0, 2);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // correct
- }
- }
-
- // -------------------------------------------------------------------
- // Test for read()
- // -------------------------------------------------------------------
-
- /*
- * Test method for 'DatagramChannelImpl.read(ByteBuffer)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- try {
- this.channel1.read(readBuf);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(localAddr1);
- assertTrue(this.channel1.isConnected());
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- assertEquals(0, this.channel1.read(readBuf));
- this.channel1.close();
- try {
- this.channel1.read(readBuf);
- fail("Should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // OK.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer_BufNull() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.read(readBuf);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- try {
- channel1.read((ByteBuffer) null);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- assertEquals(0, this.channel1.read(readBuf));
- datagramSocket1.close();
- }
-
- /*
- * Test method for 'DatagramChannelImpl.read(ByteBuffer[], int, int)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify AsynchronousCloseException, ClosedByInterruptException, IOException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII() throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.read(readBuf, 0, 2);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- assertEquals(0, this.channel1.read(readBuf, 0, 1));
- assertEquals(0, this.channel1.read(readBuf, 0, 2));
- this.channel1.close();
- assertFalse(this.channel1.isOpen());
- try {
- assertEquals(0, this.channel1.read(readBuf, 0, 1));
- } catch (ClosedChannelException e) {
- // correct
- }
-
- datagramSocket1.close();
- //regression test for HARMONY-932
- try {
- DatagramChannel.open().read(new ByteBuffer[] {}, 2, Integer.MAX_VALUE);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- DatagramChannel.open().write(new ByteBuffer[] {}, 2, Integer.MAX_VALUE);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- DatagramChannel.open().write((ByteBuffer[])null, -1, 2);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII_ConnectedBufNull()
- throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- try {
- this.channel1.read(null, 0, 2);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- assertEquals(0, this.channel1.read(readBuf, 0, 1));
- try {
- this.channel1.read(readBuf, 0, 2);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- datagramSocket1.close();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII_NotConnectedBufNull()
- throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.read(null, 0, 2);
- fail("should throw NPE");
- } catch (NullPointerException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf, 0, 2);
- fail("should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII_ConnectedIndexBad() throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- this.channel1.connect(ipAddr);
- assertTrue(this.channel1.isConnected());
- this.channel1.configureBlocking(false);
- // note : blocking-mode will make the read process endless!
- try {
- this.channel1.read(readBuf, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf, 1, 2);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf, 2, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.read(readBuf, 3, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII_NotConnectedIndexBad()
- throws IOException {
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
- try {
- this.channel1.write(readBuf, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(readBuf, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(readBuf, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(readBuf, 1, 2);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(readBuf, 2, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- try {
- this.channel1.write(readBuf, 3, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // correct
- }
- }
-
- public void disabled_testReadByteBufferArrayII_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.read(targetBuf, 0, 2);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
- channel1.read(targetBuf, 0, 2);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- // -------------------------------------------------------------------
- // test read and write
- // -------------------------------------------------------------------
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadWrite_configureBlock() throws Exception {
- byte[] targetArray = new byte[2];
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.configureBlocking(false);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.read(targetBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- this.channel1.close();
- try {
- this.channel1.configureBlocking(true);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- this.channel1 = SelectorProvider.provider().openDatagramChannel();
- this.channel1.configureBlocking(false);
- this.channel1.register(SelectorProvider.provider().openSelector(),
- SelectionKey.OP_READ);
- try {
- this.channel1.configureBlocking(true);
- fail("should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_Zero() throws Exception {
- byte[] sourceArray = new byte[0];
- byte[] targetArray = new byte[0];
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(0, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_Normal() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- readWriteReadData(this.channel1, sourceArray, this.channel2,
- targetArray, CAPACITY_NORMAL, "testReadWrite_Block_Normal");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_Empty() throws Exception {
- // empty buf
- byte[] sourceArray = "".getBytes();
- byte[] targetArray = new byte[CAPACITY_NORMAL];
-
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(0, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- // empty message let the reader blocked
- closeBlockedReaderChannel2(targetBuf);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_changeBlock_Empty() throws Exception {
- // empty buf
- byte[] sourceArray = "".getBytes();
- byte[] targetArray = new byte[CAPACITY_NORMAL];
-
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(0, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- // empty message let the reader blocked
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel2.configureBlocking(false);
- Thread.sleep(TIME_UNIT * 5);
- channel2.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }.start();
- try {
- assertTrue(this.channel2.isBlocking());
- this.channel2.read(targetBuf);
- fail("Should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- assertFalse(this.channel2.isBlocking());
- // OK.
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_8KB() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_1KB * 8];
- byte[] targetArray = new byte[CAPACITY_1KB * 8];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- readWriteReadData(this.channel1, sourceArray, this.channel2,
- targetArray, 8 * CAPACITY_1KB, "testReadWrite_Block_8KB");
- }
-
- /*
- * sender write the sourceArray whose size is dataSize, and receiver read
- * the data into targetArray
- */
- private void readWriteReadData(DatagramChannel sender, byte[] sourceArray,
- DatagramChannel receiver, byte[] targetArray, int dataSize,
- String methodName) throws IOException {
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(dataSize, sender.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
-
- int count = 0;
- int total = 0;
- long beginTime = System.currentTimeMillis();
- while (total < dataSize && (count = receiver.read(targetBuf)) != -1) {
- total = total + count;
- // 3s timeout to avoid dead loop
- if (System.currentTimeMillis() - beginTime > 3000){
- break;
- }
- }
-
- assertEquals(dataSize, total);
- assertEquals(targetBuf.position(), total);
- targetBuf.flip();
- targetArray = targetBuf.array();
- for (int i = 0; i < targetArray.length; i++) {
- assertEquals(targetArray[i], (byte) i);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadWrite_Block_64K() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_64KB];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- try {
- channel1.write(sourceBuf);
- fail("Should throw IOException");
- } catch (IOException e) {
- // too big
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_DifferentAddr() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr1);// the different addr
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- // the wrong connected addr will make the read blocked.
- // we close the blocked channel
- closeBlockedReaderChannel2(targetBuf);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_WriterNotBind() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- // bind and connect
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- closeBlockedReaderChannel2(targetBuf);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_WriterBindLater() throws Exception {
-
- byte[] targetArray = new byte[CAPACITY_NORMAL];
-
- // bind and connect
- // writer channel1 is bound later
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- // bind later
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- // write later
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, channel1.write(sourceBuf));
- } catch (Exception e) {
- // do nothing
- }
- }
- }.start();
-
- int count = 0;
- int total = 0;
- long beginTime = System.currentTimeMillis();
- while (total < CAPACITY_NORMAL && (count = channel2.read(targetBuf)) != -1) {
- total = total + count;
- // 3s timeout to avoid dead loop
- if (System.currentTimeMillis() - beginTime > 3000){
- break;
- }
- }
-
- assertEquals(CAPACITY_NORMAL, total);
- assertEquals(targetBuf.position(), total);
- targetBuf.flip();
- targetArray = targetBuf.array();
- for (int i = 0; i < targetArray.length; i++) {
- assertEquals(targetArray[i], (byte) i);
- }
-
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_Block_ReaderNotBind() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- // reader channel2 is not bound
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- closeBlockedReaderChannel2(targetBuf);
-
- }
-
- private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
- throws IOException {
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel2.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }.start();
- try {
- assertTrue(this.channel2.isBlocking());
- this.channel2.read(targetBuf);
- fail("Should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // OK.
- }
- }
-
- // -------------------------------------------------------------------
- // Test read and write in non-block mode.
- // -------------------------------------------------------------------
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_Normal() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- readWriteReadData(this.channel1, sourceArray, this.channel2,
- targetArray, CAPACITY_NORMAL, "testReadWrite_NonBlock_Normal");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_8KB() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_1KB * 8];
- byte[] targetArray = new byte[CAPACITY_1KB * 8];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- readWriteReadData(this.channel1, sourceArray, this.channel2,
- targetArray, 8 * CAPACITY_1KB, "testReadWrite_NonBlock_8KB");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_DifferentAddr() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr1);// the different addr
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_Empty() throws Exception {
- // empty buf
- byte[] sourceArray = "".getBytes();
- byte[] targetArray = new byte[CAPACITY_NORMAL];
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(0, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_WriterNotBind() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_Zero() throws Exception {
- byte[] sourceArray = new byte[0];
- byte[] targetArray = new byte[0];
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(0, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testReadWrite_NonBlock_ReaderNotBind() throws Exception {
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- byte[] targetArray = new byte[CAPACITY_NORMAL];
- for (int i = 0; i < sourceArray.length; i++) {
- sourceArray[i] = (byte) i;
- }
-
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.connect(localAddr2);
-
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
-
- // read
- ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void testWriteByteBuffer_Positioned() throws Exception {
- // Regression test for Harmony-683
- int postion = 16;
- DatagramChannel dc = DatagramChannel.open();
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- dc.connect(localAddr1);
- // write
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- sourceBuf.position(postion);
- assertEquals(CAPACITY_NORMAL - postion, dc.write(sourceBuf));
- }
-
- public void disabled_testWriteByteBuffer_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.send(targetBuf, localAddr1);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- public void disabled_testWriteByteBuffer_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
- channel1.send(targetBuf, localAddr1);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_PositonNotZero()
- throws Exception {
- // regression test for Harmony-701
- int CAPACITY_NORMAL = 256;
- int postion = 16;
- DatagramChannel dc = DatagramChannel.open();
- byte[] sourceArray = new byte[CAPACITY_NORMAL];
- // send ByteBuffer whose position is not zero
- ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- sourceBuf.position(postion);
- int ret = dc.send(sourceBuf, localAddr1);
- // assert send (256 - 16) bytes
- assertEquals(CAPACITY_NORMAL - postion, ret);
- // assert the position of ByteBuffer has been set
- assertEquals(CAPACITY_NORMAL, sourceBuf.position());
- }
-
- /**
- * @tests DatagramChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer2() throws Exception {
- // regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
- channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
-
- ByteBuffer readBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
-
- channel1.configureBlocking(true);
- assertEquals(CAPACITY_NORMAL, channel1.read(readBuf));
- }
-
- public void disabled_testReadByteBuffer_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.read(targetBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer_Block_interrupt() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
- channel1.read(targetBuf);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- /**
- * @tests DatagramChannel#read(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void testReadByteBufferArray2() throws Exception {
- // regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
- channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
-
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
-
- channel1.configureBlocking(true);
- assertEquals(CAPACITY_NORMAL, channel1.read(readBuf));
- }
-
- public void disabled_testReadByteBufferArray_Block_close() throws Exception {
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
-
- new Thread() {
- public void run() {
- try {
- Thread.sleep(TIME_UNIT);
- channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- this.channel1.read(targetBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- public void disabled_testReadByteBufferArray_Block_interrupt() throws Exception {
- // makes emulator hang
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
-
- class MyThread extends Thread {
- public String errMsg = null;
- public void run() {
- try {
- ByteBuffer[] targetBuf = new ByteBuffer[2];
- targetBuf[0] = ByteBuffer.wrap(new byte[2]);
- targetBuf[1] = ByteBuffer.wrap(new byte[2]);
- channel1.read(targetBuf);
- errMsg = "should throw ClosedByInterruptException";
- } catch (ClosedByInterruptException e) {
- // expected
- } catch (IOException e) {
- errMsg = "Unexcted Exception was thrown: " + e.getClass() +
- ": " + e.getMessage();
- }
- }
- }
- MyThread thread = new MyThread();
- thread.start();
- try {
- Thread.sleep(TIME_UNIT);
- thread.interrupt();
- } catch (InterruptedException e) {
- // ok
- }
- thread.join(TIME_UNIT);
- if (thread.errMsg != null) {
- fail(thread.errMsg);
- }
- }
-
- /**
- * @tests DatagramChannel#read(ByteBuffer[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void testReadByteBufferArrayII2() throws Exception {
- // regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
- channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
-
- ByteBuffer[] readBuf = new ByteBuffer[2];
- readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
-
- channel1.configureBlocking(true);
- assertEquals(CAPACITY_NORMAL, channel1.read(readBuf,0,2));
- }
-
- /**
- * @tests DatagramChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer_closed_nullBuf() throws Exception {
- // regression test for Harmony-754
- ByteBuffer c = null;
- DatagramChannel channel = DatagramChannel.open();
- channel.close();
- try{
- channel.read(c);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e){
- // expected
- }
- }
-
- /**
- * @tests DatagramChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer_NotConnected_nullBuf() throws Exception {
- // regression test for Harmony-754
- ByteBuffer c = null;
- DatagramChannel channel = DatagramChannel.open();
- try{
- channel.read(c);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e){
- // expected
- }
- }
-
- /**
- * @tests DatagramChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer.class}
- )
- public void testReadByteBuffer_readOnlyBuf() throws Exception {
- // regression test for Harmony-754
- ByteBuffer c = ByteBuffer.allocate(1);
- DatagramChannel channel = DatagramChannel.open();
- try{
- channel.read(c.asReadOnlyBuffer());
- fail("Should throw NotYetConnectedException");
- } catch (NotYetConnectedException e){
- // expected
- }
- channel.connect(localAddr1);
- try{
- channel.read(c.asReadOnlyBuffer());
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e){
- // expected
- }
- }
-
- /**
- * @tests DatagramChannel#send(ByteBuffer, SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "send",
- args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
- )
- public void testSend_Closed() throws IOException{
- // regression test for Harmony-913
- channel1.close();
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
- try {
- channel1.send(buf, localAddr1);
- fail("Should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- //pass
- }
- try {
- channel1.send(null,localAddr1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- //pass
- }
- try {
- channel1.send(buf, null);
- fail("Should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- //pass
- }
- try {
- channel1.send(null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- //pass
- }
- }
-
- /**
- * @tests DatagramChannel#socket()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "socket",
- args = {}
- )
- public void testSocket_NonBlock_IllegalBlockingModeException() throws Exception {
- // regression test for Harmony-1036
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- DatagramSocket socket = channel.socket();
- try {
- socket.send(null);
- fail("should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- try {
- socket.receive(null);
- fail("should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
deleted file mode 100644
index 679efe1..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
+++ /dev/null
@@ -1,89 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.FileLockInterruptionException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for FileLockInterruptionException
- */
-@TestTargetClass(FileLockInterruptionException.class)
-public class FileLockInterruptionExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.FileLockInterruptionException#FileLockInterruptionException()}
- */
- public void test_Constructor() {
- FileLockInterruptionException e = new FileLockInterruptionException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "FileLockInterruptionException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new FileLockInterruptionException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "FileLockInterruptionException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new FileLockInterruptionException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java
deleted file mode 100644
index f8dfc8a..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java
+++ /dev/null
@@ -1,284 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
-
-import junit.framework.TestCase;
-@TestTargetClass(FileLock.class)
-/**
- * Tests class FileLock.
- */
-public class FileLockTest extends TestCase {
-
- private FileChannel readWriteChannel;
-
- private MockFileLock mockLock;
-
- class MockFileLock extends FileLock {
-
- boolean isValid = true;
-
- protected MockFileLock(FileChannel channel, long position, long size,
- boolean shared) {
- super(channel, position, size, shared);
- }
-
- public boolean isValid() {
- return isValid;
- }
-
- public void release() throws IOException {
- isValid = false;
- }
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- File tempFile = File.createTempFile("testing", "tmp");
- tempFile.deleteOnExit();
- RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "rw");
- readWriteChannel = randomAccessFile.getChannel();
- mockLock = new MockFileLock(readWriteChannel, 10, 100, false);
- }
-
- protected void tearDown() throws IOException {
- if (readWriteChannel != null) {
- readWriteChannel.close();
- }
- }
-
- /**
- * @tests java.nio.channels.FileLock#FileLock(FileChannel, long, long,
- * boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "FileLock",
- args = {java.nio.channels.FileChannel.class, long.class, long.class, boolean.class}
- )
- public void test_Constructor_Ljava_nio_channels_FileChannelJJZ() {
- FileLock fileLock1 = new MockFileLock(null, 0, 0, false);
- assertNull(fileLock1.channel());
-
- try {
- new MockFileLock(readWriteChannel, -1, 0, false);
- fail("should throw IllegalArgumentException.");
- } catch (IllegalArgumentException ex) {
- // expected
- }
- try {
- new MockFileLock(readWriteChannel, 0, -1, false);
- fail("should throw IllegalArgumentException.");
- } catch (IllegalArgumentException ex) {
- // expected
- }
- // Harmony-682 regression test
- try {
- new MockFileLock(readWriteChannel, Long.MAX_VALUE, 1, false);
- fail("should throw IllegalArgumentException.");
- } catch (IllegalArgumentException ex) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.FileLock#channel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "channel",
- args = {}
- )
- public void test_channel() {
- assertSame(readWriteChannel, mockLock.channel());
- FileLock lock = new MockFileLock(null, 0, 10, true);
- assertNull(lock.channel());
- }
-
- /**
- * @tests java.nio.channels.FileLock#position()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "position",
- args = {}
- )
- public void test_position() {
- FileLock fileLock1 = new MockFileLock(readWriteChannel, 20, 100, true);
- assertEquals(20, fileLock1.position());
-
- final long position = ((long) Integer.MAX_VALUE + 1);
- FileLock fileLock2 = new MockFileLock(readWriteChannel, position, 100,
- true);
- assertEquals(position, fileLock2.position());
- }
-
- /**
- * @tests java.nio.channels.FileLock#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- FileLock fileLock1 = new MockFileLock(readWriteChannel, 20, 100, true);
- assertEquals(100, fileLock1.size());
-
- final long position = 0x0FFFFFFFFFFFFFFFL;
- final long size = ((long) Integer.MAX_VALUE + 1);
- FileLock fileLock2 = new MockFileLock(readWriteChannel, position, size,
- true);
- assertEquals(size, fileLock2.size());
- }
-
- /**
- * @tests java.nio.channels.FileLock#isShared()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "[check with false shared parameter]",
- method = "isShared",
- args = {}
- )
- public void test_isShared() {
- assertFalse(mockLock.isShared());
- FileLock lock = new MockFileLock(null, 0, 10, true);
- assertTrue(lock.isShared());
- }
-
- /**
- * @tests java.nio.channels.FileLock#overlaps(long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "overlaps",
- args = {long.class, long.class}
- )
- public void test_overlaps_JJ() {
- assertTrue(mockLock.overlaps(0, 11));
- assertFalse(mockLock.overlaps(0, 10));
- assertTrue(mockLock.overlaps(100, 110));
- assertTrue(mockLock.overlaps(99, 110));
- assertFalse(mockLock.overlaps(-1, 10));
- //Harmony-671 regression test
- assertTrue(mockLock.overlaps(1, 120));
- assertTrue(mockLock.overlaps(20, 50));
- }
-
- /**
- * @tests java.nio.channels.FileLock#isValid()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- public void test_isValid() throws IOException {
- FileLock fileLock = readWriteChannel.lock();
- assertTrue(fileLock.isValid());
- fileLock.release();
- assertFalse(fileLock.isValid());
- }
-
- /**
- * @tests java.nio.channels.FileLock#release()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "release",
- args = {}
- )
- public void test_release() throws Exception {
- File file = File.createTempFile("test", "tmp");
- file.deleteOnExit();
- FileOutputStream fout = new FileOutputStream(file);
- FileChannel fileChannel = fout.getChannel();
- FileLock fileLock = fileChannel.lock();
- fileChannel.close();
- try {
- fileLock.release();
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- // release after release
- fout = new FileOutputStream(file);
- fileChannel = fout.getChannel();
- fileLock = fileChannel.lock();
- fileLock.release();
- fileChannel.close();
- try {
- fileLock.release();
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- //expected
- }
- }
-
- /**
- * @tests java.nio.channels.FileLock#release()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- File file = File.createTempFile("test", "tmp");
- file.deleteOnExit();
- FileOutputStream fout = new FileOutputStream(file);
- FileChannel fileChannel = fout.getChannel();
- FileLock fileLock = fileChannel.lock();
- assertTrue(fileLock.toString().length() > 0);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test",
- method = "release",
- args = {}
- )
- public void testFileLock() throws Exception {
- String fileName = File.createTempFile("test", "tmp").getAbsolutePath();
- RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
- FileLock lock = raf.getChannel().tryLock();
- raf.write("file lock test".getBytes());
- lock.release();
- raf.close();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
deleted file mode 100644
index 704763f..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
+++ /dev/null
@@ -1,89 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.IllegalBlockingModeException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for IllegalBlockingModeException
- */
-@TestTargetClass(IllegalBlockingModeException.class)
-public class IllegalBlockingModeExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.IllegalBlockingModeException#IllegalBlockingModeException()}
- */
- public void test_Constructor() {
- IllegalBlockingModeException e = new IllegalBlockingModeException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "IllegalBlockingModeException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new IllegalBlockingModeException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "IllegalBlockingModeException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest
- .verifyGolden(this, new IllegalBlockingModeException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java
deleted file mode 100644
index 7b3ae4a..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.IllegalSelectorException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for IllegalSelectorException
- */
-@TestTargetClass(IllegalSelectorException.class)
-public class IllegalSelectorExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.IllegalSelectorException#IllegalSelectorException()}
- */
- public void test_Constructor() {
- IllegalSelectorException e = new IllegalSelectorException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "IllegalSelectorException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new IllegalSelectorException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "IllegalSelectorException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new IllegalSelectorException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java
deleted file mode 100644
index c4f4222..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java
+++ /dev/null
@@ -1,69 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.FileChannel;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for FileChannel.MapMode
- */
-@TestTargetClass(java.nio.channels.FileChannel.MapMode.class)
-public class MapModeTest extends TestCase {
-
- /**
- * java.nio.channels.FileChannel.MapMode#PRIVATE,READONLY,READWRITE
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies fields.",
- method = "!Constants",
- args = {}
- )
- public void test_PRIVATE_READONLY_READWRITE() {
- assertNotNull(FileChannel.MapMode.PRIVATE);
- assertNotNull(FileChannel.MapMode.READ_ONLY);
- assertNotNull(FileChannel.MapMode.READ_WRITE);
-
- assertFalse(FileChannel.MapMode.PRIVATE
- .equals(FileChannel.MapMode.READ_ONLY));
- assertFalse(FileChannel.MapMode.PRIVATE
- .equals(FileChannel.MapMode.READ_WRITE));
- assertFalse(FileChannel.MapMode.READ_ONLY
- .equals(FileChannel.MapMode.READ_WRITE));
- }
-
- /**
- * java.nio.channels.FileChannel.MapMode#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertNotNull(FileChannel.MapMode.PRIVATE.toString());
- assertNotNull(FileChannel.MapMode.READ_ONLY.toString());
- assertNotNull(FileChannel.MapMode.READ_WRITE.toString());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.java
deleted file mode 100644
index c8dc2af..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockDatagramChannel.java
+++ /dev/null
@@ -1,81 +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.nio.tests.java.nio.channels;
-
-import java.io.IOException;
-import java.net.DatagramSocket;
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.channels.DatagramChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-class MockDatagramChannel extends DatagramChannel {
-
- public MockDatagramChannel(SelectorProvider arg0) {
- super(arg0);
- }
-
- public DatagramSocket socket() {
- return null;
- }
-
- public boolean isConnected() {
- return false;
- }
-
- public DatagramChannel connect(SocketAddress arg0) throws IOException {
- return null;
- }
-
- public DatagramChannel disconnect() throws IOException {
- return null;
- }
-
- public SocketAddress receive(ByteBuffer arg0) throws IOException {
- return null;
- }
-
- public int send(ByteBuffer arg0, SocketAddress arg1) throws IOException {
- return 0;
- }
-
- public int read(ByteBuffer arg0) throws IOException {
- return 0;
- }
-
- public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
- return 0;
- }
-
- public int write(ByteBuffer arg0) throws IOException {
- return 0;
- }
-
- public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
- return 0;
- }
-
- protected void implCloseSelectableChannel() throws IOException {
- // empty
- }
-
- protected void implConfigureBlocking(boolean arg0) throws IOException {
- // empty
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSecurityManager.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSecurityManager.java
deleted file mode 100644
index 916140f..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSecurityManager.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.apache.harmony.nio.tests.java.nio.channels;
-
-import java.security.Permission;
-
-class MockSecurityManager extends SecurityManager {
-
- String validHost = null;
-
- int validPort = -1;
-
- public boolean checkAcceptCalled = false;
- public boolean checkConnectCalled = false;
-
- MockSecurityManager() {
- super();
- this.validHost = null;
- }
-
- MockSecurityManager(String host) {
- super();
- this.validHost = host;
- }
-
- MockSecurityManager(int port) {
- super();
- this.validPort = port;
- }
-
- public void checkPermission(Permission perm) {
- // no-op
- }
-
- public void checkPermission(Permission perm, Object context) {
- // no-op
- }
-
- public void checkConnect(String host, int port) {
- checkConnectCalled = true;
- // our local addr is OK.
- if (null != this.validHost) {
- if (!this.validHost.equals(host)) {
- throw new SecurityException();
- }
- }
- if ("127.0.0.1".equals(host)) {
- return;
- }
- super.checkConnect(host, port);
- }
-
- public void checkAccept(String host, int port) {
- checkAcceptCalled = true;
- // our local addr is OK.
- if (null != this.validHost) {
- if (!this.validHost.equals(host)) {
- throw new SecurityException();
- }
- }
- if (-1 != this.validPort) {
- if (this.validPort != port) {
- throw new SecurityException();
- }
- }
- if ("127.0.0.1".equals(host)) {
- return;
- }
- super.checkAccept(host, port);
- }
-}
\ No newline at end of file
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java
deleted file mode 100644
index 2058a7a..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java
+++ /dev/null
@@ -1,46 +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.nio.tests.java.nio.channels;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-class MockServerSocketChannel extends ServerSocketChannel {
-
- protected MockServerSocketChannel(SelectorProvider arg0) {
- super(arg0);
- }
-
- public ServerSocket socket() {
- return null;
- }
-
- public SocketChannel accept() throws IOException {
- return null;
- }
-
- protected void implCloseSelectableChannel() throws IOException {
- }
-
- protected void implConfigureBlocking(boolean arg0) throws IOException {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java
deleted file mode 100644
index 9d130ca..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java
+++ /dev/null
@@ -1,75 +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.nio.tests.java.nio.channels;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-class MockSocketChannel extends SocketChannel {
-
- protected MockSocketChannel(SelectorProvider arg0) {
- super(arg0);
- }
-
- public Socket socket() {
- return null;
- }
-
- public boolean isConnected() {
- return false;
- }
-
- public boolean isConnectionPending() {
- return false;
- }
-
- public boolean connect(SocketAddress arg0) throws IOException {
- return false;
- }
-
- public boolean finishConnect() throws IOException {
- return false;
- }
-
- public int read(ByteBuffer arg0) throws IOException {
- return 0;
- }
-
- public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
- return 0;
- }
-
- public int write(ByteBuffer arg0) throws IOException {
- return 0;
- }
-
- public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
- return 0;
- }
-
- protected void implCloseSelectableChannel() throws IOException {
- }
-
- protected void implConfigureBlocking(boolean arg0) throws IOException {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
deleted file mode 100644
index 36ee09e..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
+++ /dev/null
@@ -1,89 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.NoConnectionPendingException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for NoConnectionPendingException
- */
-@TestTargetClass(NoConnectionPendingException.class)
-public class NoConnectionPendingExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.NoConnectionPendingException#NoConnectionPendingException()}
- */
- public void test_Constructor() {
- NoConnectionPendingException e = new NoConnectionPendingException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NoConnectionPendingException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new NoConnectionPendingException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NoConnectionPendingException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest
- .verifyGolden(this, new NoConnectionPendingException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java
deleted file mode 100644
index c908328..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.NonReadableChannelException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for NonReadableChannelException
- */
-@TestTargetClass(NonReadableChannelException.class)
-public class NonReadableChannelExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.NonReadableChannelException#NonReadableChannelException()}
- */
- public void test_Constructor() {
- NonReadableChannelException e = new NonReadableChannelException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NonReadableChannelException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new NonReadableChannelException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NonReadableChannelException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new NonReadableChannelException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java
deleted file mode 100644
index 9de01b0..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.NonWritableChannelException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for NonWritableChannelException
- */
-@TestTargetClass(NonWritableChannelException.class)
-public class NonWritableChannelExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.NonWritableChannelException#NonWritableChannelException()}
- */
- public void test_Constructor() {
- NonWritableChannelException e = new NonWritableChannelException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NonWritableChannelException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new NonWritableChannelException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NonWritableChannelException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new NonWritableChannelException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java
deleted file mode 100644
index 94fb682..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.NotYetBoundException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for NotYetBoundException
- */
-@TestTargetClass(NotYetBoundException.class)
-public class NotYetBoundExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.NotYetBoundException#NotYetBoundException()}
- */
- public void test_Constructor() {
- NotYetBoundException e = new NotYetBoundException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NotYetBoundException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new NotYetBoundException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NotYetBoundException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new NotYetBoundException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java
deleted file mode 100644
index 423e4a6..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.NotYetConnectedException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for NotYetConnectedException
- */
-@TestTargetClass(NotYetConnectedException.class)
-public class NotYetConnectedExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.NotYetConnectedException#NotYetConnectedException()}
- */
- public void test_Constructor() {
- NotYetConnectedException e = new NotYetConnectedException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NotYetConnectedException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new NotYetConnectedException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "NotYetConnectedException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new NotYetConnectedException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
deleted file mode 100644
index c465211..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
+++ /dev/null
@@ -1,89 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.OverlappingFileLockException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for OverlappingFileLockException
- */
-@TestTargetClass(OverlappingFileLockException.class)
-public class OverlappingFileLockExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.OverlappingFileLockException#OverlappingFileLockException()}
- */
- public void test_Constructor() {
- OverlappingFileLockException e = new OverlappingFileLockException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "OverlappingFileLockException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new OverlappingFileLockException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "OverlappingFileLockException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest
- .verifyGolden(this, new OverlappingFileLockException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java
deleted file mode 100644
index 72b5b5c..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java
+++ /dev/null
@@ -1,87 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.nio.channels.Pipe;
-import java.nio.channels.Pipe.SinkChannel;
-import java.nio.channels.Pipe.SourceChannel;
-
-import junit.framework.TestCase;
-@TestTargetClass(
- value = Pipe.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- method = "Pipe",
- args = {}
- )
- }
-)
-/*
- * Tests for Pipe and its default implementation
- */
-public class PipeTest extends TestCase {
-
- /**
- * @tests java.nio.channels.Pipe#open()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "open",
- args = {}
- )
- public void test_open() throws IOException{
- Pipe pipe = Pipe.open();
- assertNotNull(pipe);
- }
-
- /**
- * @tests java.nio.channels.Pipe#sink()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sink",
- args = {}
- )
- public void test_sink() throws IOException {
- Pipe pipe = Pipe.open();
- SinkChannel sink = pipe.sink();
- assertTrue(sink.isBlocking());
- }
-
- /**
- * @tests java.nio.channels.Pipe#source()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "source",
- args = {}
- )
- public void test_source() throws IOException {
- Pipe pipe = Pipe.open();
- SourceChannel source = pipe.source();
- assertTrue(source.isBlocking());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java
deleted file mode 100644
index 5fb6359..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java
+++ /dev/null
@@ -1,110 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.SelectableChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.spi.SelectorProvider;
-import junit.framework.TestCase;
-
-/*
- * Tests for SelectableChannel
- */
-@TestTargetClass(
- value = SelectableChannel.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "empty protected constructor",
- method = "SelectableChannel",
- args = {}
- )
- }
-)
-public class SelectableChannelTest extends TestCase {
-
- /**
- * @tests SelectableChannel#register(Selector, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Abstract method.",
- method = "register",
- args = {java.nio.channels.Selector.class, int.class}
- )
- public void test_register_LSelectorI() throws IOException {
- MockSelectableChannel msc = new MockSelectableChannel();
- // Verify that calling register(Selector, int) leads to the method
- // register(Selector, int, Object) being called with a null value
- // for the third argument.
- msc.register(Selector.open(), SelectionKey.OP_ACCEPT);
- assertTrue(msc.isCalled);
- }
-
- private class MockSelectableChannel extends SelectableChannel {
-
- private boolean isCalled = false;
-
- public Object blockingLock() {
- return null;
- }
-
- public SelectableChannel configureBlocking(boolean block)
- throws IOException {
- return null;
- }
-
- public boolean isBlocking() {
- return false;
- }
-
- public boolean isRegistered() {
- return false;
- }
-
- public SelectionKey keyFor(Selector sel) {
- return null;
- }
-
- public SelectorProvider provider() {
- return null;
- }
-
- public SelectionKey register(Selector sel, int ops, Object att)
- throws ClosedChannelException {
- if (null == att) {
- isCalled = true;
- }
- return null;
- }
-
- public int validOps() {
- return 0;
- }
-
- protected void implCloseChannel() throws IOException {
- // empty
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java
deleted file mode 100644
index 9961398..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java
+++ /dev/null
@@ -1,463 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.nio.channels.CancelledKeyException;
-import java.nio.channels.Pipe;
-import java.nio.channels.SelectableChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-import junit.framework.TestCase;
-import tests.support.Support_PortManager;
-
-/*
- * Tests for SelectionKey and its default implementation
- */
-@TestTargetClass(
- value = SelectionKey.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "empty protected constructor",
- method = "SelectionKey",
- args = {}
- )
- }
-)
-public class SelectionKeyTest extends TestCase {
-
- Selector selector;
-
- SocketChannel sc;
-
- SelectionKey selectionKey;
-
- private static String LOCAL_ADDR = "127.0.0.1";
-
- protected void setUp() throws Exception {
- super.setUp();
- selector = Selector.open();
- sc = SocketChannel.open();
- sc.configureBlocking(false);
- selectionKey = sc.register(selector, SelectionKey.OP_CONNECT);
- }
-
- protected void tearDown() throws Exception {
- selectionKey.cancel();
- selectionKey = null;
- selector.close();
- selector = null;
- super.tearDown();
- }
-
- static class MockSelectionKey extends SelectionKey {
- private int interestOps;
-
- MockSelectionKey(int ops) {
- interestOps = ops;
- }
-
- public void cancel() {
- // do nothing
- }
-
- public SelectableChannel channel() {
- return null;
- }
-
- public int interestOps() {
- return 0;
- }
-
- public SelectionKey interestOps(int operations) {
- return null;
- }
-
- public boolean isValid() {
- return true;
- }
-
- public int readyOps() {
- return interestOps;
- }
-
- public Selector selector() {
- return null;
- }
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#attach(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "attach",
- args = {java.lang.Object.class}
- )
- public void test_attach() {
- MockSelectionKey mockSelectionKey = new MockSelectionKey(SelectionKey.OP_ACCEPT);
- // no previous, return null
- Object o = new Object();
- Object check = mockSelectionKey.attach(o);
- assertNull(check);
-
- // null parameter is ok
- check = mockSelectionKey.attach(null);
- assertSame(o, check);
-
- check = mockSelectionKey.attach(o);
- assertNull(check);
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#attachment()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "attachment",
- args = {}
- )
- public void test_attachment() {
- MockSelectionKey mockSelectionKey = new MockSelectionKey(SelectionKey.OP_ACCEPT);
- assertNull(mockSelectionKey.attachment());
- Object o = new Object();
- mockSelectionKey.attach(o);
- assertSame(o, mockSelectionKey.attachment());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#channel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "channel",
- args = {}
- )
- public void test_channel() {
- assertSame(sc, selectionKey.channel());
- // can be invoked even canceled
- selectionKey.cancel();
- assertSame(sc, selectionKey.channel());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#interestOps()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "interestOps",
- args = {}
- )
- public void test_interestOps() {
- assertEquals(SelectionKey.OP_CONNECT, selectionKey.interestOps());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#interestOps(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't verify CancelledKeyException.",
- method = "interestOps",
- args = {int.class}
- )
- public void test_interestOpsI() {
- selectionKey.interestOps(SelectionKey.OP_WRITE);
- assertEquals(SelectionKey.OP_WRITE, selectionKey.interestOps());
-
- try {
- selectionKey.interestOps(SelectionKey.OP_ACCEPT);
- fail("should throw IAE.");
- } catch (IllegalArgumentException ex) {
- // expected;
- }
-
- try {
- selectionKey.interestOps(~sc.validOps());
- fail("should throw IAE.");
- } catch (IllegalArgumentException ex) {
- // expected;
- }
- try {
- selectionKey.interestOps(-1);
- fail("should throw IAE.");
- } catch (IllegalArgumentException ex) {
- // expected;
- }
-
- selectionKey.cancel();
- try {
- selectionKey.interestOps(-1);
- fail("should throw IAE.");
- } catch (CancelledKeyException ex) {
- // expected;
- }
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isValid()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- public void test_isValid() {
- assertTrue(selectionKey.isValid());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isValid()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- public void test_isValid_KeyCancelled() {
- selectionKey.cancel();
- assertFalse(selectionKey.isValid());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isValid()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- public void test_isValid_ChannelColsed() throws IOException {
- sc.close();
- assertFalse(selectionKey.isValid());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isValid()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- public void test_isValid_SelectorClosed() throws IOException {
- selector.close();
- assertFalse(selectionKey.isValid());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isAcceptable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAcceptable",
- args = {}
- )
- public void test_isAcceptable() throws IOException {
- MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
- assertTrue(mockSelectionKey1.isAcceptable());
- MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_CONNECT);
- assertFalse(mockSelectionKey2.isAcceptable());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isConnectable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isConnectable",
- args = {}
- )
- public void test_isConnectable() {
- MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_CONNECT);
- assertTrue(mockSelectionKey1.isConnectable());
- MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
- assertFalse(mockSelectionKey2.isConnectable());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isReadable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isReadable",
- args = {}
- )
- public void test_isReadable() {
- MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_READ);
- assertTrue(mockSelectionKey1.isReadable());
- MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
- assertFalse(mockSelectionKey2.isReadable());
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#isWritable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isWritable",
- args = {}
- )
- public void test_isWritable() throws Exception {
- MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_WRITE);
- assertTrue(mockSelectionKey1.isWritable());
- MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
- assertFalse(mockSelectionKey2.isWritable());
-
- Selector selector = SelectorProvider.provider().openSelector();
-
- Pipe pipe = SelectorProvider.provider().openPipe();
- pipe.open();
- pipe.sink().configureBlocking(false);
- SelectionKey key = pipe.sink().register(selector, SelectionKey.OP_WRITE);
-
- key.cancel();
- try {
- key.isWritable();
- fail("should throw IAE.");
- } catch (CancelledKeyException ex) {
- // expected;
- }
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#cancel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cancel",
- args = {}
- )
- public void test_cancel() {
- selectionKey.cancel();
- try {
- selectionKey.isAcceptable();
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
- try {
- selectionKey.isConnectable();
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
- try {
- selectionKey.isReadable();
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
- try {
- selectionKey.isWritable();
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
-
- try {
- selectionKey.readyOps();
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
-
- try {
- selectionKey.interestOps(SelectionKey.OP_CONNECT);
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
-
- try {
- selectionKey.interestOps();
- fail("should throw CancelledKeyException.");
- } catch (CancelledKeyException ex) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#readyOps()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "readyOps",
- args = {}
- )
- public void test_readyOps() throws IOException {
- int port = Support_PortManager.getNextPort();
- ServerSocket ss = new ServerSocket(port);
- try {
- sc.connect(new InetSocketAddress(LOCAL_ADDR, port));
- assertEquals(0, selectionKey.readyOps());
- assertFalse(selectionKey.isConnectable());
- selector.select();
- assertEquals(SelectionKey.OP_CONNECT, selectionKey.readyOps());
- } finally {
- ss.close();
- ss = null;
- }
-
- selectionKey.cancel();
- try {
- selectionKey.readyOps();
- fail("should throw IAE.");
- } catch (CancelledKeyException ex) {
- // expected;
- }
- }
-
- /**
- * @tests java.nio.channels.SelectionKey#selector()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "selector",
- args = {}
- )
- public void test_selector() {
- assertSame(selector, selectionKey.selector());
- selectionKey.cancel();
- assertSame(selector, selectionKey.selector());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java
deleted file mode 100644
index e15ad27..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java
+++ /dev/null
@@ -1,736 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.nio.ByteBuffer;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.ClosedSelectorException;
-import java.nio.channels.Pipe;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.SelectorProvider;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-import junit.framework.TestCase;
-import tests.support.Support_PortManager;
-
-/*
- * Tests for Selector and its default implementation
- */
-@TestTargetClass(
- value = Selector.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "empty protected constructor",
- method = "Selector",
- args = {}
- )
- }
-)
-public class SelectorTest extends TestCase {
-
- private static final int WAIT_TIME = 100;
-
- private static final int PORT = Support_PortManager.getNextPort();
-
- private static final InetSocketAddress LOCAL_ADDRESS = new InetSocketAddress(
- "127.0.0.1", PORT);
-
- Selector selector;
-
- ServerSocketChannel ssc;
-
- enum SelectType {
- NULL, TIMEOUT, NOW
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- ssc = ServerSocketChannel.open();
- ssc.configureBlocking(false);
- ServerSocket ss = ssc.socket();
- InetSocketAddress address = new InetSocketAddress(PORT);
- ss.bind(address);
- selector = Selector.open();
- }
-
- protected void tearDown() throws Exception {
- try {
- ssc.close();
- } catch (Exception e) {
- // do nothing
- }
- try {
- selector.close();
- } catch (Exception e) {
- // do nothing
- }
- super.tearDown();
- }
-
- /**
- * @tests java.nio.channels.Selector#open()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "open",
- args = {}
- )
- public void test_open() throws IOException {
- assertNotNull(selector);
- }
-
- /**
- * @tests Selector#isOpen()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
- public void test_isOpen() throws IOException {
- assertTrue(selector.isOpen());
- selector.close();
- assertFalse(selector.isOpen());
- }
-
- /**
- * @tests java.nio.channels.Selector#provider()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "provider",
- args = {}
- )
- public void test_provider() throws IOException {
- // should be system default provider
- assertNotNull(selector.provider());
- assertSame(SelectorProvider.provider(), selector.provider());
- }
-
- /**
- * @tests java.nio.channels.Selector#keys()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keys",
- args = {}
- )
- public void test_keys() throws IOException {
- SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);
-
- Set<SelectionKey> keySet = selector.keys();
- Set<SelectionKey> keySet2 = selector.keys();
-
- assertSame(keySet, keySet2);
- assertEquals(1,keySet.size());
- SelectionKey key2 = keySet.iterator().next();
- assertEquals(key,key2);
-
- // Any attempt to modify keys will cause UnsupportedOperationException
- SocketChannel sc = SocketChannel.open();
- sc.configureBlocking(false);
- SelectionKey key3 = sc.register(selector, SelectionKey.OP_READ);
- try {
- keySet2.add(key3);
- fail("should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- try {
- keySet2.remove(key3);
- fail("should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- try {
- keySet2.clear();
- fail("should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- selector.close();
- try {
- selector.keys();
- fail("should throw ClosedSelectorException");
- } catch (ClosedSelectorException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Selector#keys()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "selectedKeys",
- args = {}
- )
- public void test_selectedKeys() throws IOException {
- SocketChannel sc = SocketChannel.open();
- ssc.register(selector, SelectionKey.OP_ACCEPT);
- try {
- int count = 0;
- sc.connect(LOCAL_ADDRESS);
- count = blockingSelect(SelectType.NULL, 0);
- assertEquals(1, count);
- Set<SelectionKey> selectedKeys = selector.selectedKeys();
- Set<SelectionKey> selectedKeys2 = selector.selectedKeys();
- assertSame(selectedKeys, selectedKeys2);
-
- assertEquals(1, selectedKeys.size());
- assertEquals(ssc.keyFor(selector), selectedKeys.iterator().next());
- // add one key into selectedKeys
- try {
- selectedKeys.add(ssc.keyFor(selector));
- fail("Should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- // no exception should be thrown
- selectedKeys.clear();
-
- Set<SelectionKey> selectedKeys3 = selector.selectedKeys();
- assertSame(selectedKeys, selectedKeys3);
-
- ssc.keyFor(selector).cancel();
- assertEquals(0, selectedKeys.size());
- selector.close();
- try {
- selector.selectedKeys();
- fail("should throw ClosedSelectorException");
- } catch (ClosedSelectorException e) {
- // expected
- }
- } finally {
- sc.close();
- }
- }
-
- /**
- * @tests java.nio.channel.Selector#selectNow()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies selectNow() method for Selector registered with SelectionKeys.OP_ACCEPT, SelectionKeys.OP_CONNECT, SelectionKeys.OP_READ, SelectionKeys.OP_WRITE keys.",
- method = "selectNow",
- args = {}
- )
- public void test_selectNow() throws IOException {
- assert_select_OP_ACCEPT(SelectType.NOW, 0);
- assert_select_OP_CONNECT(SelectType.NOW, 0);
- assert_select_OP_READ(SelectType.NOW, 0);
- assert_select_OP_WRITE(SelectType.NOW, 0);
- }
-
- /**
- * @tests java.nio.channel.Selector#selectNow()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that ClosedSelectorException is thrown if selectNow() method is called for closed Selector.",
- method = "selectNow",
- args = {}
- )
- public void test_selectNow_SelectorClosed() throws IOException {
- assert_select_SelectorClosed(SelectType.NOW, 0);
- }
-
- /**
- * @test java.nio.channels.Selector#selectNow()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that selectNow() method doesn't block.",
- method = "selectNow",
- args = {}
- )
- public void test_selectNow_Timeout() throws IOException {
- // make sure selectNow doesn't block
- selector.selectNow();
- }
-
- /**
- * @tests java.nio.channel.Selector#select()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies select() method for Selector registered with SelectionKeys.OP_ACCEPT, SelectionKeys.OP_CONNECT, SelectionKeys.OP_READ, SelectionKeys.OP_WRITE keys.",
- method = "select",
- args = {}
- )
- public void test_select() throws IOException {
- assert_select_OP_ACCEPT(SelectType.NULL, 0);
- assert_select_OP_CONNECT(SelectType.NULL, 0);
- assert_select_OP_READ(SelectType.NULL, 0);
- assert_select_OP_WRITE(SelectType.NULL, 0);
- }
-
- /**
- * @tests java.nio.channel.Selector#select()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that ClosedSelectorException is thrown if select() method is called for closed Selector.",
- method = "select",
- args = {}
- )
- public void test_select_SelectorClosed() throws IOException {
- assert_select_SelectorClosed(SelectType.NULL, 0);
- }
-
- /**
- * @tests java.nio.channel.Selector#select(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies select(long) method for Selector registered with SelectionKeys.OP_ACCEPT, SelectionKeys.OP_CONNECT, SelectionKeys.OP_READ, SelectionKeys.OP_WRITE keys and different timeout's values.",
- method = "select",
- args = {long.class}
- )
- public void test_selectJ() throws IOException {
- assert_select_OP_ACCEPT(SelectType.TIMEOUT, 0);
- assert_select_OP_CONNECT(SelectType.TIMEOUT, 0);
- assert_select_OP_READ(SelectType.TIMEOUT, 0);
- assert_select_OP_WRITE(SelectType.TIMEOUT, 0);
-
- assert_select_OP_ACCEPT(SelectType.TIMEOUT, WAIT_TIME);
- assert_select_OP_CONNECT(SelectType.TIMEOUT, WAIT_TIME);
- assert_select_OP_READ(SelectType.TIMEOUT, WAIT_TIME);
- assert_select_OP_WRITE(SelectType.TIMEOUT, WAIT_TIME);
- }
-
- /**
- * @tests java.nio.channel.Selector#select(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that ClosedSelectorException is thrown if select(long) method is called for closed Selector.",
- method = "select",
- args = {long.class}
- )
- public void test_selectJ_SelectorClosed() throws IOException {
- assert_select_SelectorClosed(SelectType.TIMEOUT, 0);
- selector = Selector.open();
- assert_select_SelectorClosed(SelectType.TIMEOUT, WAIT_TIME);
- }
-
- /**
- * @tests java.nio.channel.Selector#select(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "select",
- args = {long.class}
- )
- public void test_selectJ_Exception() throws IOException {
- try {
- selector.select(-1);
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @test java.nio.channels.Selector#select(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that select(timeout) doesn't block.",
- method = "select",
- args = {long.class}
- )
- public void test_selectJ_Timeout() throws IOException {
- // make sure select(timeout) doesn't block
- selector.select(WAIT_TIME);
- }
-
- /**
- * @test java.nio.channels.Selector#select(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies select(long) method for empty selection keys.",
- method = "select",
- args = {long.class}
- )
- public void test_selectJ_Empty_Keys() throws IOException {
- // regression test, see HARMONY-3888.
- // make sure select(long) does wait for specified amount of
- // time if keys.size() == 0 (initial state of selector).
-
- final long SELECT_TIMEOUT = 2000;
-
- long time1 = System.currentTimeMillis();
- selector.select(SELECT_TIMEOUT);
- long time2 = System.currentTimeMillis();
- assertEquals("elapsed time", SELECT_TIMEOUT, (time2 - time1),
- SELECT_TIMEOUT * 0.05); // 5% accuracy
- }
-
- /**
- * @tests java.nio.channels.Selector#wakeup()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "wakeup",
- args = {}
- )
- public void test_wakeup() throws IOException {
- /*
- * make sure the test does not block on select
- */
- selector.wakeup();
- selectOnce(SelectType.NULL, 0);
- selector.wakeup();
- selectOnce(SelectType.TIMEOUT, 0);
-
- // try to wakeup select. The invocation sequence of wakeup and select
- // doesn't affect test result.
- new Thread() {
- public void run() {
-
- try {
- Thread.sleep(WAIT_TIME);
- } catch (InterruptedException e) {
- // ignore
- }
- selector.wakeup();
- }
- }.start();
- selectOnce(SelectType.NULL, 0);
-
- // try to wakeup select. The invocation sequence of wakeup and select
- // doesn't affect test result.
- new Thread() {
- public void run() {
-
- try {
- Thread.sleep(WAIT_TIME);
- } catch (InterruptedException e) {
- // ignore
- }
- selector.wakeup();
- }
- }.start();
- selectOnce(SelectType.TIMEOUT, 0);
- }
-
- public void test_keySetViewsModifications() throws IOException {
- Set<SelectionKey> keys = selector.keys();
-
- SelectionKey key1 = ssc.register(selector, SelectionKey.OP_ACCEPT);
-
- assertTrue(keys.contains(key1));
-
- SocketChannel sc = SocketChannel.open();
- sc.configureBlocking(false);
- SelectionKey key2 = sc.register(selector, SelectionKey.OP_READ);
-
- assertTrue(keys.contains(key1));
- assertTrue(keys.contains(key2));
-
- key1.cancel();
- assertTrue(keys.contains(key1));
-
- selector.selectNow();
- assertFalse(keys.contains(key1));
- assertTrue(keys.contains(key2));
- }
-
- /**
- * This test cancels a key while selecting to verify that the cancelled
- * key set is processed both before and after the call to the underlying
- * operating system.
- */
- public void test_cancelledKeys() throws Exception {
- final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
- final AtomicBoolean complete = new AtomicBoolean();
-
- final Pipe pipe = Pipe.open();
- pipe.source().configureBlocking(false);
- final SelectionKey key = pipe.source().register(selector, SelectionKey.OP_READ);
-
- Thread thread = new Thread() {
- public void run() {
- try {
- // make sure to call key.cancel() while the main thread is selecting
- Thread.sleep(500);
- key.cancel();
- assertFalse(key.isValid());
- pipe.sink().write(ByteBuffer.allocate(4)); // unblock select()
- } catch (Throwable e) {
- failure.set(e);
- } finally {
- complete.set(true);
- }
- }
- };
- assertTrue(key.isValid());
-
- thread.start();
- do {
- assertEquals(0, selector.select(5000)); // blocks
- assertEquals(0, selector.selectedKeys().size());
- } while (!complete.get()); // avoid spurious interrupts
- assertFalse(key.isValid());
-
- thread.join();
- assertNull(failure.get());
- }
-
- private void assert_select_SelectorClosed(SelectType type, int timeout)
- throws IOException {
- // selector is closed
- selector.close();
- try {
- selectOnce(type, timeout);
- fail("should throw ClosedSelectorException");
- } catch (ClosedSelectorException e) {
- // expected
- }
- }
-
- private void assert_select_OP_ACCEPT(SelectType type, int timeout)
- throws IOException, ClosedChannelException {
- SocketChannel sc = SocketChannel.open();
- SocketChannel client = null;
- try {
- ssc.register(selector, SelectionKey.OP_ACCEPT);
- sc.connect(LOCAL_ADDRESS);
- int count = blockingSelect(type, timeout);
- assertEquals(1, count);
- Set<SelectionKey> selectedKeys = selector.selectedKeys();
- assertEquals(1, selectedKeys.size());
- SelectionKey key = selectedKeys.iterator().next();
- assertEquals(ssc.keyFor(selector), key);
- assertEquals(SelectionKey.OP_ACCEPT, key.readyOps());
- // select again, it should return 0
- count = selectOnce(type, timeout);
- assertEquals(0,count);
- // but selectedKeys remains the same as previous
- assertSame(selectedKeys, selector.selectedKeys());
- client = ssc.accept();
- selectedKeys.clear();
- } finally {
- try {
- sc.close();
- } catch (IOException e) {
- // do nothing
- }
- if (null != client) {
- client.close();
- }
- }
- ssc.keyFor(selector).cancel();
- }
-
- private void assert_select_OP_CONNECT(SelectType type, int timeout)
- throws IOException, ClosedChannelException {
- SocketChannel sc = SocketChannel.open();
- sc.configureBlocking(false);
- sc.register(selector, SelectionKey.OP_CONNECT);
- try {
- sc.connect(LOCAL_ADDRESS);
- int count = blockingSelect(type, timeout);
- assertEquals(1, count);
- Set<SelectionKey> selectedKeys = selector.selectedKeys();
- assertEquals(1, selectedKeys.size());
- SelectionKey key = selectedKeys.iterator().next();
- assertEquals(sc.keyFor(selector), key);
- assertEquals(SelectionKey.OP_CONNECT, key.readyOps());
- // select again, it should return 0
- count = selectOnce(type, timeout);
- assertEquals(0, count);
- // but selectedKeys remains the same as previous
- assertSame(selectedKeys, selector.selectedKeys());
- sc.finishConnect();
- selectedKeys.clear();
- } finally {
- try {
- ssc.accept().close();
- } catch (Exception e) {
- // do nothing
- }
-
- try {
- sc.close();
- } catch (IOException e) {
- // do nothing
- }
- }
- }
-
- private void assert_select_OP_READ(SelectType type, int timeout)
- throws IOException {
- SocketChannel sc = SocketChannel.open();
- SocketChannel client = null;
- SocketChannel sc2 = SocketChannel.open();
- SocketChannel client2 = null;
- try {
- ssc.configureBlocking(true);
- sc.connect(LOCAL_ADDRESS);
- client = ssc.accept();
- sc.configureBlocking(false);
- sc.register(selector, SelectionKey.OP_READ);
- client.configureBlocking(true);
-
- sc2.connect(LOCAL_ADDRESS);
- client2 = ssc.accept();
- sc2.configureBlocking(false);
- sc2.register(selector, SelectionKey.OP_READ);
- client2.configureBlocking(true);
-
- client.write(ByteBuffer.wrap("a".getBytes()));
- int count = blockingSelect(type, timeout);
- assertEquals(1, count);
- Set<SelectionKey> selectedKeys = selector.selectedKeys();
- assertEquals(1, selectedKeys.size());
- SelectionKey key = selectedKeys.iterator().next();
- assertEquals(sc.keyFor(selector), key);
- assertEquals(SelectionKey.OP_READ, key.readyOps());
- // select again, it should return 0
- count = selectOnce(type, timeout);
- assertEquals(0, count);
- // but selectedKeys remains the same as previous
- assertSame(selectedKeys, selector.selectedKeys());
-
- sc.read(ByteBuffer.allocate(8));
-
- // the second SocketChannel should be selected this time
- client2.write(ByteBuffer.wrap("a".getBytes()));
- count = blockingSelect(type, timeout);
- assertEquals(1, count);
- // selectedKeys still includes the key of sc, because the key of sc
- // is not removed last time.
- selectedKeys = selector.selectedKeys();
- assertEquals(2, selectedKeys.size());
- } finally {
- if (null != client) {
- try {
- client.close();
- } catch (Exception e) {
- // ignore
- }
- }
- if (null != client2) {
- try {
- client2.close();
- } catch (Exception e) {
- // ignore
- }
- }
- try {
- sc.close();
- } catch (Exception e) {
- // ignore
- }
- try {
- sc2.close();
- } catch (Exception e) {
- // ignore
- }
- ssc.configureBlocking(false);
- }
- }
-
- private void assert_select_OP_WRITE(SelectType type, int timeout)
- throws IOException {
- SocketChannel sc = SocketChannel.open();
- SocketChannel client = null;
- try {
- sc.connect(LOCAL_ADDRESS);
- ssc.configureBlocking(true);
- client = ssc.accept();
- sc.configureBlocking(false);
- sc.register(selector, SelectionKey.OP_WRITE);
- int count = blockingSelect(type, timeout);
- assertEquals(1, count);
- Set<SelectionKey> selectedKeys = selector.selectedKeys();
- assertEquals(1, selectedKeys.size());
- SelectionKey key = selectedKeys.iterator().next();
- assertEquals(sc.keyFor(selector), key);
- assertEquals(SelectionKey.OP_WRITE, key.readyOps());
- // select again, it should return 0
- count = selectOnce(type, timeout);
- assertEquals(0, count);
- // but selectedKeys remains the same as previous
- assertSame(selectedKeys, selector.selectedKeys());
- } finally {
- if (null != client) {
- client.close();
- }
- try {
- sc.close();
- } catch (IOException e) {
- // do nothing
- }
- ssc.configureBlocking(false);
- }
- }
-
- private int blockingSelect(SelectType type, int timeout) throws IOException {
- int ret = 0;
- do {
- ret = selectOnce(type, timeout);
- if (ret > 0) {
- return ret;
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // ignore
- }
- } while (true);
- }
-
- private int selectOnce(SelectType type, int timeout) throws IOException {
- int ret = 0;
- switch (type) {
- case NULL:
- ret = selector.select();
- break;
- case TIMEOUT:
- ret = selector.select(timeout);
- break;
- case NOW:
- ret = selector.selectNow();
- break;
- }
- return ret;
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java
deleted file mode 100644
index eb2f9dd..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java
+++ /dev/null
@@ -1,751 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.AndroidOnly;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.channels.AsynchronousCloseException;
-import java.nio.channels.ClosedByInterruptException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.Pipe;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.Pipe.SinkChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for Pipe.SinkChannel class
- */
-@TestTargetClass(
- value = java.nio.channels.Pipe.SinkChannel.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "ClosedByInterruptException can not easily be tested",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- }
-)
-public class SinkChannelTest extends TestCase {
-
- private static final int BUFFER_SIZE = 5;
-
- private static final String ISO8859_1 = "ISO8859-1";
-
- private Pipe pipe;
-
- private Pipe.SinkChannel sink;
-
- private Pipe.SourceChannel source;
-
- private ByteBuffer buffer;
-
- private ByteBuffer positionedBuffer;
-
- protected void setUp() throws Exception {
- super.setUp();
- pipe = Pipe.open();
- sink = pipe.sink();
- source = pipe.source();
- buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1));
- positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1));
- positionedBuffer.position(BUFFER_SIZE);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#validOps()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "validOps",
- args = {}
- )
- public void test_validOps() {
- assertEquals(SelectionKey.OP_WRITE, sink.validOps());
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer [])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_LByteBuffer() throws IOException {
- ByteBuffer[] bufArray = { buffer, positionedBuffer };
- boolean[] sinkBlockingMode = { true, true, false, false };
- boolean[] sourceBlockingMode = { true, false, true, false };
- int oldPosition;
- int currentPosition;
- for (int i = 0; i < sinkBlockingMode.length; ++i) {
- sink.configureBlocking(sinkBlockingMode[i]);
- source.configureBlocking(sourceBlockingMode[i]);
- // if sink and source both are blocking mode, source only needs read
- // once to get what sink write.
- boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i];
- for (ByteBuffer buf : bufArray) {
- buf.mark();
- oldPosition = buf.position();
- sink.write(buf);
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- int totalCount = 0;
- do {
- int count = source.read(readBuf);
- if (count > 0) {
- totalCount += count;
- }
- } while (totalCount != BUFFER_SIZE && !isBlocking);
- currentPosition = buf.position();
- assertEquals(BUFFER_SIZE, currentPosition - oldPosition);
- assertEquals("bytes", new String(readBuf.array(), ISO8859_1));
- buf.reset();
- }
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_LByteBuffer_mutliThread() throws IOException,
- InterruptedException {
- final int THREAD_NUM = 20;
- final byte[] strbytes = "bytes".getBytes(ISO8859_1);
- Thread[] thread = new Thread[THREAD_NUM];
- for (int i = 0; i < THREAD_NUM; i++) {
- thread[i] = new Thread() {
- public void run() {
- try {
- sink.write(ByteBuffer.wrap(strbytes));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- };
- }
- for (int i = 0; i < THREAD_NUM; i++) {
- thread[i].start();
- }
- for (int i = 0; i < THREAD_NUM; i++) {
- thread[i].join();
- }
- ByteBuffer readBuf = ByteBuffer.allocate(THREAD_NUM * BUFFER_SIZE);
-
- long totalCount = 0;
- do {
- long count = source.read(readBuf);
- if (count < 0) {
- break;
- }
- totalCount += count;
- } while (totalCount != (THREAD_NUM * BUFFER_SIZE));
-
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < THREAD_NUM; i++) {
- buf.append("bytes");
- }
- String readString = buf.toString();
- assertEquals(readString, new String(readBuf.array(), ISO8859_1));
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
- */
- public void disabled_test_read_LByteBuffer_mutliThread_close() throws Exception {
-
- ByteBuffer sourceBuf = ByteBuffer.allocate(1000);
- sink.configureBlocking(true);
-
- new Thread() {
- public void run() {
- try {
- Thread.currentThread().sleep(500);
- sink.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- sink.write(sourceBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
- */
- public void disabled_test_read_LByteBuffer_mutliThread_interrupt() throws Exception {
-
- sink.configureBlocking(true);
-
- Thread thread = new Thread() {
- public void run() {
- try {
- sink.write(ByteBuffer.allocate(10));
- fail("should have thrown a ClosedByInterruptException.");
- } catch (ClosedByInterruptException e) {
- // expected
- return;
- } catch (IOException e) {
- fail("should throw a ClosedByInterruptException but " +
- "threw " + e.getClass() + ": " + e.getMessage());
- }
- }
- };
-
- thread.start();
- Thread.currentThread().sleep(500);
- thread.interrupt();
-
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_LByteBuffer_Exception() throws IOException {
- // write null ByteBuffer
- ByteBuffer nullBuf = null;
- try {
- sink.write(nullBuf);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- @AndroidOnly("seems to run on newer RI versions")
- public void test_write_LByteBuffer_SourceClosed() throws IOException {
- source.close();
- int written = sink.write(buffer);
- assertEquals(BUFFER_SIZE, written);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException, NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_LByteBuffer_SinkClosed() throws IOException {
- sink.close();
- try {
- sink.write(buffer);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- // write null ByteBuffer
- ByteBuffer nullBuf = null;
- try {
- sink.write(nullBuf);
- fail("should throw NullPointerException");
- } catch (ClosedChannelException e) {
- // expected on RI
- } catch (NullPointerException e) {
- // expected on Harmony/Android
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_$LByteBuffer() throws IOException {
- ByteBuffer[] bufArray = { buffer, positionedBuffer };
- boolean[] sinkBlockingMode = { true, true, false, false };
- boolean[] sourceBlockingMode = { true, false, true, false };
- for (int i = 0; i < sinkBlockingMode.length; ++i) {
- sink.configureBlocking(sinkBlockingMode[i]);
- source.configureBlocking(sourceBlockingMode[i]);
- buffer.position(0);
- positionedBuffer.position(BUFFER_SIZE);
- sink.write(bufArray);
- // if sink and source both are blocking mode, source only needs read
- // once to get what sink write.
- boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i];
- for (int j = 0; j < bufArray.length; ++j) {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- int totalCount = 0;
- do {
- int count = source.read(readBuf);
- if (count < 0) {
- break;
- }
- totalCount += count;
- } while (totalCount != BUFFER_SIZE && !isBlocking);
- assertEquals("bytes", new String(readBuf.array(), ISO8859_1));
- }
- assertEquals(BUFFER_SIZE, buffer.position());
- assertEquals(10, positionedBuffer.position());
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_$LByteBuffer_Exception() throws IOException {
- // write null ByteBuffer[]
- ByteBuffer[] nullBufArrayRef = null;
- try {
- sink.write(nullBufArrayRef);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // write ByteBuffer[] contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray = { buffer, nullBuf };
- try {
- sink.write(nullBufArray);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- @AndroidOnly("seems to run on newer RI versions")
- public void test_write_$LByteBuffer_SourceClosed() throws IOException {
- ByteBuffer[] bufArray = { buffer };
- source.close();
- long written = sink.write(bufArray);
- assertEquals(BUFFER_SIZE, written);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException, NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_write_$LByteBuffer_SinkClosed() throws IOException {
- ByteBuffer[] bufArray = { buffer };
- sink.close();
- try {
- sink.write(bufArray);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArrayRef = null;
- try {
- sink.write(nullBufArrayRef);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray = { nullBuf };
- // write ByteBuffer[] contains null element
- try {
- sink.write(nullBufArray);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_write_$LByteBufferII() throws IOException {
- ByteBuffer[] bufArray = { buffer, positionedBuffer };
- boolean[] sinkBlockingMode = { true, true, false, false };
- boolean[] sourceBlockingMode = { true, false, true, false };
- for (int i = 0; i < sinkBlockingMode.length; ++i) {
- sink.configureBlocking(sinkBlockingMode[i]);
- source.configureBlocking(sourceBlockingMode[i]);
- positionedBuffer.position(BUFFER_SIZE);
- sink.write(bufArray, 1, 1);
- // if sink and source both are blocking mode, source only needs read
- // once to get what sink write.
- boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i];
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- int totalCount = 0;
- do {
- int count = source.read(readBuf);
- if (count < 0) {
- break;
- }
- totalCount += count;
- } while (totalCount != BUFFER_SIZE && !isBlocking);
- assertEquals("bytes", new String(readBuf.array(), ISO8859_1));
- assertEquals(10, positionedBuffer.position());
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException, IndexOutOfBoundsException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_write_$LByteBufferII_Exception() throws IOException {
- // write null ByteBuffer[]
- ByteBuffer[] nullBufArrayRef = null;
- try {
- sink.write(nullBufArrayRef, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- sink.write(nullBufArrayRef, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // write ByteBuffer[] contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray = { nullBuf };
- try {
- sink.write(nullBufArray, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- sink.write(nullBufArray, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- ByteBuffer[] bufArray = { buffer, nullBuf };
- try {
- sink.write(bufArray, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray, -1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray, 0, 2);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- @AndroidOnly("seems to run on newer RI versions")
- public void test_write_$LByteBufferII_SourceClosed() throws IOException {
- ByteBuffer[] bufArray = { buffer };
- source.close();
- long written = sink.write(bufArray, 0, 1);
- assertEquals(BUFFER_SIZE, written);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException, NullPointerException, IndexOutOfBoundsException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_write_$LByteBufferII_SinkClosed() throws IOException {
- ByteBuffer[] bufArray = { buffer };
- sink.close();
- try {
- sink.write(bufArray, 0, 1);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- // write null ByteBuffer[]
- ByteBuffer[] nullBufArrayRef = null;
- try {
- sink.write(nullBufArrayRef, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- // illegal array index
- try {
- sink.write(nullBufArrayRef, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // write ByteBuffer[] contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray = { nullBuf };
- try {
- sink.write(nullBufArray, 0, 1);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- // illegal array index
- try {
- sink.write(nullBufArray, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- ByteBuffer[] bufArray2 = { buffer, nullBuf };
- // illegal array index
- try {
- sink.write(bufArray2, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray2, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray2, -1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray2, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sink.write(bufArray2, 0, 2);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SinkChannel#close()
- * @tests {@link java.nio.channels.Pipe.SinkChannel#isOpen()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- ),@TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
- })
- public void test_close() throws IOException {
- assertTrue(sink.isOpen());
- sink.close();
- assertFalse(sink.isOpen());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SinkChannel",
- args = {java.nio.channels.spi.SelectorProvider.class}
- )
- public void testConstructor() throws IOException {
- SinkChannel channel =
- SelectorProvider.provider().openPipe().sink();
- assertNotNull(channel);
- assertSame(SelectorProvider.provider(),channel.provider());
- channel = Pipe.open().sink();
- assertNotNull(channel);
- assertSame(SelectorProvider.provider(),channel.provider());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that NullPointerException is thrown if write" +
- "method is called for closed channel.",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
- public void test_socketChannel_closed() throws Exception {
- ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),49999));
- SocketChannel sc = SocketChannel.open();
- ByteBuffer buf = null;
- try{
- sc.write(buf);
- fail("should throw NPE");
- }catch (NullPointerException e){
- // expected
- }
- sc.connect(new InetSocketAddress(InetAddress.getLocalHost(),49999));
- SocketChannel sock = ssc.accept();
- ssc.close();
- sc.close();
- try{
- sc.write(buf);
- fail("should throw NPE");
- }catch (NullPointerException e){
- // expected
- }
- sock.close();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_socketChannel_empty() throws Exception {
- ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),49999));
- SocketChannel sc = SocketChannel.open();
- sc.connect(new InetSocketAddress(InetAddress.getLocalHost(),49999));
- SocketChannel sock = ssc.accept();
- ByteBuffer[] buf = {ByteBuffer.allocate(10),null};
- try{
- sc.write(buf,0,2);
- fail("should throw NPE");
- }catch (NullPointerException e){
- // expected
- }
- ssc.close();
- sc.close();
- ByteBuffer target = ByteBuffer.allocate(10);
- assertEquals(-1, sock.read(target));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java
deleted file mode 100644
index 55a0144..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java
+++ /dev/null
@@ -1,721 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargets;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.AsynchronousCloseException;
-import java.nio.channels.ClosedByInterruptException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.Pipe;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Pipe.SourceChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-import junit.framework.TestCase;
-@TestTargetClass(
- value = java.nio.channels.Pipe.SourceChannel.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "AsynchronousCloseException can not easily be tested",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- }
-)
-/**
- * Tests for java.nio.channels.Pipe.SourceChannel
- */
-public class SourceChannelTest extends TestCase {
-
- private static final int BUFFER_SIZE = 5;
-
- private static final String ISO8859_1 = "ISO8859-1";
-
- private Pipe pipe;
-
- private Pipe.SinkChannel sink;
-
- private Pipe.SourceChannel source;
-
- private ByteBuffer buffer;
-
- private ByteBuffer positionedBuffer;
-
- protected void setUp() throws Exception {
- super.setUp();
- pipe = Pipe.open();
- sink = pipe.sink();
- source = pipe.source();
- buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1));
- positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1));
- positionedBuffer.position(BUFFER_SIZE);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#validOps()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "validOps",
- args = {}
- )
- public void test_validOps() {
- assertEquals(SelectionKey.OP_READ, source.validOps());
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_LByteBuffer_DataAvailable() throws IOException {
- // if anything can read, read method will not block
- sink.write(ByteBuffer.allocate(1));
- int count = source.read(ByteBuffer.allocate(10));
- assertEquals(1, count);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_LByteBuffer_Exception() throws IOException {
- ByteBuffer nullBuf = null;
- try {
- source.read(nullBuf);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_LByteBuffer_SinkClosed() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- sink.write(buffer);
- sink.close();
- long count = source.read(readBuf);
- assertEquals(BUFFER_SIZE, count);
- // readBuf is full, read 0 byte expected
- count = source.read(readBuf);
- assertEquals(0, count);
- // readBuf is not null, -1 is expected
- readBuf.position(0);
- count = source.read(readBuf);
- assertEquals(-1, count);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException, NullPointerException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_LByteBuffer_SourceClosed() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- source.close();
- try {
- source.read(readBuf);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- readBuf.position(BUFFER_SIZE);
- try {
- // readBuf is full
- source.read(readBuf);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- ByteBuffer nullBuf = null;
- try {
- source.read(nullBuf);
- fail("should throw NullPointerException");
- } catch (ClosedChannelException e) {
- // expected on RI
- } catch (NullPointerException e) {
- // expected on Harmony/Android
- }
-
- ByteBuffer[] bufArray = null;
- try {
- source.read(bufArray);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArray = {nullBuf};
- try {
- source.read(nullBufArray);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_$LByteBuffer() throws IOException {
- ByteBuffer[] bufArray = { buffer, positionedBuffer };
- boolean[] sinkBlockingMode = { true, true, false, false };
- boolean[] sourceBlockingMode = { true, false, true, false };
- for (int i = 0; i < sinkBlockingMode.length; ++i) {
- // open new pipe everytime, will be closed in finally block
- pipe = Pipe.open();
- sink = pipe.sink();
- source = pipe.source();
- sink.configureBlocking(sinkBlockingMode[i]);
- source.configureBlocking(sourceBlockingMode[i]);
- buffer.position(0);
- positionedBuffer.position(BUFFER_SIZE);
- try {
- long writeCount = sink.write(bufArray);
- assertEquals(10, writeCount);
- // invoke close to ensure all data will be sent out
- sink.close();
- // read until EOF is meet or readBufArray is full.
- ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE),
- ByteBuffer.allocate(BUFFER_SIZE) };
- long totalCount = 0;
- do {
- long count = source.read(readBufArray);
- if (count < 0) {
- break;
- }
- if (0 == count && BUFFER_SIZE == readBufArray[1].position()) {
- // source.read returns 0 because readBufArray is full
- break;
- }
- totalCount += count;
- } while (totalCount <= 10);
- // assert read result
- for (ByteBuffer readBuf : readBufArray) {
- // RI may fail because of its bug implementation
- assertEquals(BUFFER_SIZE, readBuf.position());
- assertEquals("bytes",
- new String(readBuf.array(), ISO8859_1));
- }
- } finally {
- // close pipe everytime
- sink.close();
- source.close();
- }
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_$LByteBuffer_Exception() throws IOException {
- ByteBuffer[] nullBufArrayRef = null;
- try {
- source.read(nullBufArrayRef);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // ByteBuffer array contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray1 = { nullBuf };
- try {
- source.read(nullBufArray1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArray2 = { buffer, nullBuf };
- try {
- source.read(nullBufArray2);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_$LByteBuffer_SinkClosed() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- ByteBuffer[] readBufArray = { readBuf };
- sink.write(buffer);
- sink.close();
- long count = source.read(readBufArray);
- assertEquals(BUFFER_SIZE, count);
- // readBuf is full, read 0 byte expected
- count = source.read(readBufArray);
- assertEquals(0, count);
- // readBuf is not null, -1 is expected
- readBuf.position(0);
- assertTrue(readBuf.hasRemaining());
- count = source.read(readBufArray);
- assertEquals(-1, count);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException, NullPointerException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_$LByteBuffer_SourceClosed() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- ByteBuffer[] readBufArray = { readBuf };
- source.close();
- try {
- source.read(readBufArray);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- readBuf.position(BUFFER_SIZE);
- try {
- // readBuf is full
- source.read(readBufArray);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArrayRef = null;
- try {
- source.read(nullBufArrayRef);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // ByteBuffer array contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray1 = { nullBuf };
- try {
- source.read(nullBufArray1);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_read_$LByteBufferII() throws IOException {
- ByteBuffer[] bufArray = { buffer, positionedBuffer };
- boolean[] sinkBlockingMode = { true, true, false, false };
- boolean[] sourceBlockingMode = { true, false, true, false };
- for (int i = 0; i < sinkBlockingMode.length; ++i) {
- Pipe pipe = Pipe.open();
- sink = pipe.sink();
- source = pipe.source();
-
- sink.configureBlocking(sinkBlockingMode[i]);
- source.configureBlocking(sourceBlockingMode[i]);
-
- buffer.position(0);
- positionedBuffer.position(BUFFER_SIZE);
- try {
- sink.write(bufArray);
- // invoke close to ensure all data will be sent out
- sink.close();
- // read until EOF is meet or readBufArray is full.
- ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE),
- ByteBuffer.allocate(BUFFER_SIZE) };
- long totalCount = 0;
- do {
- long count = source.read(readBufArray, 0, 2);
- if (count < 0) {
- break;
- }
- if (0 == count && BUFFER_SIZE == readBufArray[1].position()) {
- // source.read returns 0 because readBufArray is full
- break;
- }
- totalCount += count;
- } while (totalCount != 10);
-
- // assert read result
- for (ByteBuffer readBuf : readBufArray) {
- // RI may fail because of its bug implementation
- assertEquals(BUFFER_SIZE, readBuf.position());
- assertEquals("bytes",
- new String(readBuf.array(), ISO8859_1));
- }
- } finally {
- sink.close();
- source.close();
- }
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException, IndexOutOfBoundsException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_read_$LByteBufferII_Exception() throws IOException {
-
- ByteBuffer[] nullBufArrayRef = null;
- try {
- source.read(nullBufArrayRef, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- source.read(nullBufArrayRef, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // ByteBuffer array contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray1 = { nullBuf };
- try {
- source.read(nullBufArray1, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- source.read(nullBufArray1, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- source.read(nullBufArray1, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- source.read(nullBufArray1, -1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArray2 = { buffer, nullBuf };
-
- try {
- source.read(nullBufArray1, 1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- source.read(nullBufArray2, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- source.read(nullBufArray2, 0, 2);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_read_$LByteBufferII_SinkClosed() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- ByteBuffer[] readBufArray = { readBuf };
- sink.write(buffer);
- sink.close();
- long count = source.read(readBufArray, 0, 1);
- assertEquals(BUFFER_SIZE, count);
- // readBuf is full, read 0 byte expected
- count = source.read(readBufArray);
- assertEquals(0, count);
- // readBuf is not null, -1 is expected
- readBuf.position(0);
- count = source.read(readBufArray, 0, 1);
- assertEquals(-1, count);
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException, ClosedChannelException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
- public void test_read_$LByteBufferII_SourceClosed() throws IOException {
- ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
- ByteBuffer[] readBufArray = { readBuf };
- source.close();
- try {
- source.read(readBufArray, 0, 1);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- readBuf.position(BUFFER_SIZE);
- try {
- // readBuf is full
- source.read(readBufArray, 0, 1);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArrayRef = null;
- try {
- source.read(nullBufArrayRef, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- source.read(nullBufArrayRef, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // ByteBuffer array contains null element
- ByteBuffer nullBuf = null;
- ByteBuffer[] nullBufArray1 = { nullBuf };
- try {
- source.read(nullBufArray1, 0, 1);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- try {
- source.read(nullBufArray1, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- source.read(nullBufArray1, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- source.read(nullBufArray1, -1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- ByteBuffer[] nullBufArray2 = { buffer, nullBuf };
-
- try {
- source.read(nullBufArray1, 1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- source.read(nullBufArray2, 0, 3);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- source.read(nullBufArray2, 0, 2);
- fail("should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#close()
- * @tests {@link java.nio.channels.Pipe.SourceChannel#isOpen()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- ),@TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
- })
- public void test_close() throws IOException {
- assertTrue(sink.isOpen());
- sink.close();
- assertFalse(sink.isOpen());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SourceChannel",
- args = {java.nio.channels.spi.SelectorProvider.class}
- )
- public void testConstructor() throws IOException {
- SourceChannel channel =
- SelectorProvider.provider().openPipe().source();
- assertNotNull(channel);
- assertSame(SelectorProvider.provider(),channel.provider());
- channel = Pipe.open().source();
- assertNotNull(channel);
- assertSame(SelectorProvider.provider(),channel.provider());
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedByInterruptException",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
- public void test_read_LByteBuffer_mutliThread_interrupt() throws Exception {
-
- source.configureBlocking(true);
-
- Thread thread = new Thread() {
- public void run() {
- try {
- source.read(ByteBuffer.allocate(10));
- fail("should have thrown a ClosedByInterruptException.");
- } catch (ClosedByInterruptException e) {
- // expected
- return;
- } catch (IOException e) {
- fail("should throw a ClosedByInterruptException but " +
- "threw " + e.getClass() + ": " + e.getMessage());
- }
- }
- };
-
- thread.start();
- Thread.currentThread().sleep(500);
- thread.interrupt();
-
- }
-
- /**
- * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
- */
- public void disabled_test_read_LByteBuffer_mutliThread_close() throws Exception {
-
- ByteBuffer sourceBuf = ByteBuffer.allocate(1000);
- source.configureBlocking(true);
-
- new Thread() {
- public void run() {
- try {
- Thread.currentThread().sleep(500);
- source.close();
- } catch (Exception e) {
- //ignore
- }
- }
- }.start();
- try {
- source.read(sourceBuf);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // ok
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
deleted file mode 100644
index d248509..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
+++ /dev/null
@@ -1,88 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.UnresolvedAddressException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for UnresolvedAddressException
- */
-@TestTargetClass(UnresolvedAddressException.class)
-public class UnresolvedAddressExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.UnresolvedAddressException#UnresolvedAddressException()}
- */
- public void test_Constructor() {
- UnresolvedAddressException e = new UnresolvedAddressException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "UnresolvedAddressException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new UnresolvedAddressException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "UnresolvedAddressException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new UnresolvedAddressException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
deleted file mode 100644
index ba5b41c..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
+++ /dev/null
@@ -1,89 +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.nio.tests.java.nio.channels;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.UnsupportedAddressTypeException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-/**
- * Tests for UnsupportedAddressTypeException
- */
-@TestTargetClass(UnsupportedAddressTypeException.class)
-public class UnsupportedAddressTypeExceptionTest extends TestCase {
-
- /**
- * @tests {@link java.nio.channels.UnsupportedAddressTypeException#UnsupportedAddressTypeException()}
- */
- public void test_Constructor() {
- UnsupportedAddressTypeException e = new UnsupportedAddressTypeException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "UnsupportedAddressTypeException",
- args = {}
- )
- })
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new UnsupportedAddressTypeException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "UnsupportedAddressTypeException",
- args = {}
- )
- })
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new UnsupportedAddressTypeException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
deleted file mode 100644
index 05fa362..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
+++ /dev/null
@@ -1,199 +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.nio.tests.java.nio.channels.spi;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.nio.channels.AsynchronousCloseException;
-import java.nio.channels.spi.AbstractInterruptibleChannel;
-
-import junit.framework.TestCase;
-@TestTargetClass(
- value = AbstractInterruptibleChannel.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "empty protected constructor",
- method = "AbstractInterruptibleChannel",
- args = {}
- )
- }
-)
-public class AbstractInterruptibleChannelTest extends TestCase {
-
- /**
- * @tests AbstractInterruptibleChannel#close()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
- })
- public void test_close() throws IOException {
- MockInterruptibleChannel testMiChannel = new MockInterruptibleChannel();
- assertTrue(testMiChannel.isOpen());
- testMiChannel.isImplCloseCalled = false;
- testMiChannel.close();
- assertTrue(testMiChannel.isImplCloseCalled);
- assertFalse(testMiChannel.isOpen());
- }
-
- /**
- * @tests AbstractInterruptibleChannel#begin/end()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "begin",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "end",
- args = {boolean.class}
- )
- })
- public void test_begin_end() throws IOException {
- boolean complete = false;
- MockInterruptibleChannel testChannel = new MockInterruptibleChannel();
- try {
- testChannel.superBegin();
- complete = true;
- } finally {
- testChannel.superEnd(complete);
- }
-
- try {
- testChannel.superBegin();
- complete = false;
- } finally {
- testChannel.superEnd(complete);
- }
-
- try {
- testChannel.superBegin();
- complete = true;
- } finally {
- testChannel.superEnd(complete);
- }
- testChannel.superEnd(complete);
-
- testChannel.superBegin();
- try {
- testChannel.superBegin();
- complete = true;
- } finally {
- testChannel.superEnd(complete);
- }
- assertTrue(testChannel.isOpen());
- testChannel.close();
- }
-
- /**
- * @tests AbstractInterruptibleChannel#close/begin/end()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "begin",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "end",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- })
- public void test_close_begin_end() throws IOException {
- boolean complete = false;
- MockInterruptibleChannel testChannel = new MockInterruptibleChannel();
- assertTrue(testChannel.isOpen());
- try {
- testChannel.superBegin();
- complete = true;
- } finally {
- testChannel.superEnd(complete);
- }
- assertTrue(testChannel.isOpen());
- testChannel.close();
- try {
- testChannel.superBegin();
- complete = false;
- } finally {
- try {
- testChannel.superEnd(complete);
- fail("should throw AsynchronousCloseException");
- } catch (AsynchronousCloseException e) {
- // expected
- }
- }
- assertFalse(testChannel.isOpen());
- try {
- testChannel.superBegin();
- complete = true;
- } finally {
- testChannel.superEnd(complete);
- }
- assertFalse(testChannel.isOpen());
- }
-
- private class MockInterruptibleChannel extends AbstractInterruptibleChannel {
-
- private boolean isImplCloseCalled = false;
-
- public MockInterruptibleChannel() {
- super();
- }
-
- protected void implCloseChannel() throws IOException {
- isImplCloseCalled = true;
- }
-
- // call super.begin() for test
- void superBegin() {
- super.begin();
- }
-
- // call super.end() for test
- void superEnd(boolean completed) throws AsynchronousCloseException {
- super.end(completed);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
deleted file mode 100644
index 67d66d6..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
+++ /dev/null
@@ -1,437 +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.nio.tests.java.nio.channels.spi;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.IllegalBlockingModeException;
-import java.nio.channels.IllegalSelectorException;
-import java.nio.channels.SelectableChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.AbstractSelectableChannel;
-import java.nio.channels.spi.SelectorProvider;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.nio.tests.java.nio.channels.spi.AbstractSelectorTest.MockSelectorProvider;
-
-/**
- * Tests for AbstractSelectableChannel
- */
-@TestTargetClass(AbstractSelectableChannel.class)
-public class AbstractSelectableChannelTest extends TestCase {
-
- private MockSelectableChannel testChannel;
-
- protected void setUp() throws Exception {
- super.setUp();
- testChannel = new MockSelectableChannel(SelectorProvider.provider());
- }
-
- protected void tearDown() throws Exception {
- if (testChannel.isOpen()) {
- testChannel.close();
- }
- }
-
- /**
- * @tests AbstractSelectableChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractSelectableChannel",
- args = {SelectorProvider.class}
- )
- public void test_Constructor_LSelectorProvider() throws Exception {
- assertSame(SelectorProvider.provider(), testChannel.provider());
- }
-
- /**
- * @tests AbstractSelectableChannel#implCloseChannel()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implCloseChannel",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implCloseSelectableChannel",
- args = {}
- )
- })
- public void test_implClose() throws IOException {
- testChannel.isImplCloseSelectableChannelCalled = false;
- testChannel.implCloseSelectableChannelCount = 0;
- testChannel.close();
- assertFalse(testChannel.isOpen());
- assertTrue(testChannel.isImplCloseSelectableChannelCalled);
- assertEquals(1, testChannel.implCloseSelectableChannelCount);
-
- testChannel = new MockSelectableChannel(SelectorProvider.provider());
- testChannel.isImplCloseSelectableChannelCalled = false;
- testChannel.implCloseSelectableChannelCount = 0;
- // close twice.
- // make sure implCloseSelectableChannelCount is called only once.
- testChannel.close();
- testChannel.close();
- assertFalse(testChannel.isOpen());
- assertTrue(testChannel.isImplCloseSelectableChannelCalled);
- assertEquals(1, testChannel.implCloseSelectableChannelCount);
- }
-
- /**
- * @tests AbstractSelectableChannel#provider()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "provider",
- args = {}
- )
- public void test_provider() {
- SelectorProvider provider = testChannel.provider();
- assertSame(SelectorProvider.provider(), provider);
- testChannel = new MockSelectableChannel(null);
- provider = testChannel.provider();
- assertNull(provider);
- }
-
- /**
- * @tests AbstractSelectableChannel#isBlocking()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isBlocking",
- args = {}
- )
- public void test_isBlocking() throws IOException {
- assertTrue(testChannel.isBlocking());
- testChannel.configureBlocking(false);
- assertFalse(testChannel.isBlocking());
- testChannel.configureBlocking(true);
- assertTrue(testChannel.isBlocking());
- }
-
- /**
- *
- * @tests AbstractSelectableChannel#blockingLock()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "blockingLock",
- args = {}
- )
- public void test_blockingLock() {
- Object gotObj = testChannel.blockingLock();
- assertNotNull(gotObj);
- }
-
- /**
- * @tests AbstractSelectableChannel#register(Selector, int, Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "register",
- args = {java.nio.channels.Selector.class, int.class, java.lang.Object.class}
- )
- public void test_register_LSelectorILObject() throws IOException {
- assertFalse(testChannel.isRegistered());
- Selector acceptSelector1 = SelectorProvider.provider().openSelector();
- Selector acceptSelector2 = new MockAbstractSelector(SelectorProvider
- .provider());
- SocketChannel sc = SocketChannel.open();
- sc.configureBlocking(false);
- SelectionKey acceptKey = sc.register(acceptSelector1,
- SelectionKey.OP_READ, null);
- assertNotNull(acceptKey);
- assertTrue(acceptKey.isValid());
- assertSame(sc, acceptKey.channel());
-
- //test that sc.register invokes Selector.register()
- acceptKey = sc.register(acceptSelector2, SelectionKey.OP_READ, null);
- assertTrue(((MockAbstractSelector)acceptSelector2).isRegisterCalled);
-
- // Regression test to ensure acceptance of a selector with empty
- // interest set.
- SocketChannel channel = SocketChannel.open();
- channel.configureBlocking(false);
- Selector selector = Selector.open();
- channel.register(selector, 0);
- selector.close();
- channel.close();
- }
-
- /**
- * @tests AbstractSelectableChannel#register(Selector, int, Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "register",
- args = {java.nio.channels.Selector.class, int.class, java.lang.Object.class}
- )
- public void test_register_LSelectorILObject_IllegalArgument()
- throws IOException {
- Selector acceptSelector = SelectorProvider.provider().openSelector();
- assertTrue(acceptSelector.isOpen());
- MockSelectableChannel msc = new MockSelectableChannel(SelectorProvider
- .provider());
- msc.configureBlocking(false);
- // in nonblocking mode
- try {
- //different SelectionKey with validOps
- msc.register(acceptSelector, SelectionKey.OP_READ, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- msc.register(null, 0, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- // in nonblocking mode, if selector closed
- acceptSelector.close();
- try {
- msc.register(acceptSelector, SelectionKey.OP_READ, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- msc.register(null, 0, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- msc.register(acceptSelector, 0, null);
- fail("Should throw IllegalSelectorException");
- } catch (IllegalSelectorException e) {
- // expected
- }
-
- acceptSelector = SelectorProvider.provider().openSelector();
- // test in blocking mode
- msc.configureBlocking(true);
- try {
- msc.register(acceptSelector, SelectionKey.OP_READ, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- msc.register(null, 0, null);
- fail("Should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- acceptSelector.close();
- // in blocking mode, if selector closed
- try {
- msc.register(acceptSelector, SelectionKey.OP_READ, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- msc.register(null, 0, null);
- fail("Should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
-
- // register with an object
- Object argObj = new Object();
- SocketChannel sc = SocketChannel.open();
- sc.configureBlocking(false);
- try {
- sc.register(null, SelectionKey.OP_READ, argObj);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // if channel closed
- msc.close();
- try {
- msc.register(acceptSelector, SelectionKey.OP_READ, null);
- fail("Should throw ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
-
- SelectorProvider prov1 = MockSelectorProvider.provider();
- SelectorProvider prov2 = MockSelectorProvider.provider();
-
- Selector sel = prov2.openSelector();
-
- sc = prov1.openSocketChannel();
- sc.configureBlocking(false);
- try {
- sc.register(sel, SelectionKey.OP_READ, null);
- } catch (IllegalSelectorException e) {
- // expected
- }
- }
-
- /**
- * @tests AbstractSelectableChannel#keyFor(Selector)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keyFor",
- args = {java.nio.channels.Selector.class}
- )
- public void test_keyfor_LSelector() throws Exception {
- SocketChannel sc = SocketChannel.open();
- Object argObj = new Object();
- sc.configureBlocking(false);
- Selector acceptSelector = SelectorProvider.provider().openSelector();
- Selector acceptSelectorOther = SelectorProvider.provider()
- .openSelector();
- SelectionKey acceptKey = sc.register(acceptSelector,
- SelectionKey.OP_READ, argObj);
- assertEquals(sc.keyFor(acceptSelector), acceptKey);
- SelectionKey acceptKeyObjNull = sc.register(acceptSelector,
- SelectionKey.OP_READ, null);
- assertSame(sc.keyFor(acceptSelector), acceptKeyObjNull);
- assertSame(acceptKeyObjNull, acceptKey);
- SelectionKey acceptKeyOther = sc.register(acceptSelectorOther,
- SelectionKey.OP_READ, null);
- assertSame(sc.keyFor(acceptSelectorOther), acceptKeyOther);
- }
-
- /**
- * @tests AbstractSelectableChannel#configureBlocking(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "configureBlocking",
- args = {boolean.class}
- )
- public void test_configureBlocking_Z_IllegalBlockingMode() throws Exception {
- SocketChannel sc = SocketChannel.open();
- sc.configureBlocking(false);
- Selector acceptSelector = SelectorProvider.provider().openSelector();
- SelectionKey acceptKey = sc.register(acceptSelector,
- SelectionKey.OP_READ, null);
- assertEquals(sc.keyFor(acceptSelector), acceptKey);
- SelectableChannel getChannel = sc.configureBlocking(false);
- assertEquals(getChannel, sc);
- try {
- sc.configureBlocking(true);
- fail("Should throw IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
- }
-
- /**
- * @tests AbstractSelectableChannel#configureBlocking(boolean)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "configureBlocking",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implConfigureBlocking",
- args = {boolean.class}
- )
- })
- public void test_configureBlocking_Z() throws Exception {
- testChannel = new MockSelectableChannel(SelectorProvider
- .provider());
- // default blocking mode is true. The implConfigureBlocking is only
- // invoked if the given mode is different with current one.
- testChannel.configureBlocking(true);
- assertFalse(testChannel.implConfigureBlockingCalled);
- testChannel.configureBlocking(false);
- assertTrue(testChannel.implConfigureBlockingCalled);
-
- AbstractSelectableChannel channel =
- SelectorProvider.provider().openDatagramChannel();
- channel.configureBlocking(false);
- channel.register(SelectorProvider.provider().openSelector(),
- SelectionKey.OP_READ);
- try {
- channel.configureBlocking(true);
- fail("Should have thrown IllegalBlockingModeException");
- } catch (IllegalBlockingModeException e) {
- // expected
- }
-
- testChannel.close();
- try {
- testChannel.configureBlocking(false);
- fail("Should have thrown ClosedChannelException");
- } catch (ClosedChannelException e) {
- // expected
- }
- }
-
- private class MockSelectableChannel extends AbstractSelectableChannel {
-
- private boolean isImplCloseSelectableChannelCalled = false;
-
- private int implCloseSelectableChannelCount = 0;
-
- private boolean implConfigureBlockingCalled = false;
-
- public MockSelectableChannel(SelectorProvider arg0) {
- super(arg0);
- }
-
- protected void implCloseSelectableChannel() throws IOException {
- isImplCloseSelectableChannelCalled = true;
- ++implCloseSelectableChannelCount;
- }
-
- protected void implConfigureBlocking(boolean arg0) throws IOException {
- implConfigureBlockingCalled = true;
- }
-
- public int validOps() {
- return SelectionKey.OP_ACCEPT;
- }
-
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
deleted file mode 100644
index 6393071..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
+++ /dev/null
@@ -1,104 +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.nio.tests.java.nio.channels.spi;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.nio.channels.SelectableChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.spi.AbstractSelectionKey;
-
-import junit.framework.TestCase;
-@TestTargetClass(
- value = AbstractSelectionKey.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "empty protected constructor",
- method = "AbstractSelectionKey",
- args = {}
- )
- }
-)
-public class AbstractSelectionKeyTest extends TestCase {
-
- /**
- * @tests AbstractSelectionKey#isValid() without selector
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- public void test_isValid() throws Exception {
- MockSelectionKey testKey = new MockSelectionKey();
- assertTrue(testKey.isValid());
- }
-
- /**
- * @tests AbstractSelectionKey#cancel
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cancel",
- args = {}
- )
- public void test_cancel() throws Exception {
- MockSelectionKey testKey = new MockSelectionKey();
- try {
- testKey.cancel();
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected: no selector available
- }
- assertFalse(testKey.isValid());
- }
-
- private class MockSelectionKey extends AbstractSelectionKey {
-
- MockSelectionKey() {
- super();
- }
-
- public SelectableChannel channel() {
- return null;
- }
-
- public Selector selector() {
- return null;
- }
-
- public int interestOps() {
- return 0;
- }
-
- public SelectionKey interestOps(int arg0) {
- return null;
- }
-
- public int readyOps() {
- return 0;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java
deleted file mode 100644
index 517dc46..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java
+++ /dev/null
@@ -1,281 +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.nio.tests.java.nio.channels.spi;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.nio.channels.DatagramChannel;
-import java.nio.channels.Pipe;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.spi.AbstractSelectableChannel;
-import java.nio.channels.spi.AbstractSelectionKey;
-import java.nio.channels.spi.SelectorProvider;
-import java.nio.channels.spi.AbstractSelector;
-import java.util.Set;
-
-import junit.framework.TestCase;
-@TestTargetClass(AbstractSelector.class)
-/**
- * Tests for AbstractSelector and register of its default implementation
- */
-public class AbstractSelectorTest extends TestCase {
-
- /**
- * @tests AbstractSelector#provider()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "provider",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "AbstractSelector",
- args = {SelectorProvider.class}
- )
- })
- public void test_provider() throws IOException {
- Selector mockSelector = new MockAbstractSelector(SelectorProvider
- .provider());
- assertTrue(mockSelector.isOpen());
- assertSame(SelectorProvider.provider(), mockSelector.provider());
- mockSelector = new MockAbstractSelector(null);
- assertNull(mockSelector.provider());
- }
-
- /**
- * @tests AbstractSelector#close()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implCloseSelector",
- args = {}
- )
- })
- public void test_close() throws IOException {
- MockAbstractSelector mockSelector = new MockAbstractSelector(
- SelectorProvider.provider());
- mockSelector.close();
- assertTrue(mockSelector.isImplCloseSelectorCalled);
- }
-
- /**
- *
- * @tests AbstractSelector#begin/end()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "begin",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "end",
- args = {}
- )
- })
- public void test_begin_end() throws IOException {
- MockAbstractSelector mockSelector = new MockAbstractSelector(
- SelectorProvider.provider());
- try {
- mockSelector.superBegin();
- } finally {
- mockSelector.superEnd();
- }
-
- mockSelector = new MockAbstractSelector(SelectorProvider.provider());
- try {
- mockSelector.superBegin();
- mockSelector.close();
- } finally {
- mockSelector.superEnd();
- }
-
- try {
- // begin twice
- mockSelector.superBegin();
- mockSelector.superBegin();
- } finally {
- mockSelector.superEnd();
- }
-
- try {
- mockSelector.superBegin();
- } finally {
- // end twice
- mockSelector.superEnd();
- mockSelector.superEnd();
- }
-
- mockSelector.close();
- try {
- mockSelector.superBegin();
- } finally {
- mockSelector.superEnd();
- }
- }
-
- /**
- * @tests AbstractSelector#isOpen()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
- public void test_isOpen() throws Exception {
- Selector acceptSelector = SelectorProvider.provider().openSelector();
- assertTrue(acceptSelector.isOpen());
- acceptSelector.close();
- assertFalse(acceptSelector.isOpen());
- }
-
- /**
- * @tests AbstractSelector()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "AbstractSelector",
- args = {SelectorProvider.class}
- )
- public void test_Constructor_LSelectorProvider() throws Exception {
- Selector acceptSelector = new MockAbstractSelector(
- SelectorProvider.provider());
- assertSame(SelectorProvider.provider(), acceptSelector.provider());
- }
-
- /**
- * @tests AbstractSelector#register(AbstractSelectableChannel,int,Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies register method from SelectableChannel class.",
- method = "register",
- args = {AbstractSelectableChannel.class, int.class, java.lang.Object.class}
- )
- public void test_register_LAbstractSelectableChannelIObject()
- throws Exception {
- Selector acceptSelector = new MockSelectorProvider().openSelector();
- ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.configureBlocking(false);
-
- assertFalse(ssc.isRegistered());
- ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
- assertTrue(ssc.isRegistered());
- assertTrue(((MockAbstractSelector)acceptSelector).isRegisterCalled);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cancelledKeys",
- args = {}
- )
- public void test_cancelledKeys() throws Exception {
- MockSelectorProvider prov = new MockSelectorProvider();
- Selector acceptSelector = prov.openSelector();
- SocketChannel sc = prov.openSocketChannel();
- sc.configureBlocking(false);
-
- SelectionKey acceptKey = sc.register(acceptSelector,
- SelectionKey.OP_READ, null);
- acceptKey.cancel();
- Set<SelectionKey> cKeys =
- ((MockAbstractSelector)acceptSelector).getCancelledKeys();
- assertTrue(cKeys.contains(acceptKey));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deregister",
- args = {AbstractSelectionKey.class}
- )
- public void test_deregister() throws Exception {
- MockSelectorProvider prov = new MockSelectorProvider();
- AbstractSelector acceptSelector = prov.openSelector();
- SocketChannel sc = prov.openSocketChannel();
- sc.configureBlocking(false);
-
- SelectionKey acceptKey = sc.register(acceptSelector,
- SelectionKey.OP_READ, null);
- assertTrue(sc.isRegistered());
- assertNotNull(acceptKey);
- ((MockAbstractSelector)acceptSelector).mockDeregister(
- (MockAbstractSelector.MockSelectionKey)acceptKey);
- assertFalse(sc.isRegistered());
- }
-
- static class MockSelectorProvider extends SelectorProvider {
-
- private MockSelectorProvider() {
- // do nothing
- }
-
- @Override
- public DatagramChannel openDatagramChannel() {
- return null;
- }
-
- @Override
- public Pipe openPipe() {
- return null;
- }
-
- @Override
- public AbstractSelector openSelector() {
- return new MockAbstractSelector(provider());
- }
-
- @Override
- public ServerSocketChannel openServerSocketChannel() {
- return null;
- }
-
- @Override
- public SocketChannel openSocketChannel() throws IOException {
- return SocketChannel.open();
- }
-
- public static SelectorProvider provider() {
- return new MockSelectorProvider();
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java
deleted file mode 100644
index 6175b60a..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/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.nio.tests.java.nio.channels.spi;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-public class AllTests {
-
- public static Test suite() {
- TestSuite suite = new TestSuite("Test for tests.api.java.nio.channels.spi");
- //$JUnit-BEGIN$
- suite.addTestSuite(AbstractInterruptibleChannelTest.class);
- suite.addTestSuite(AbstractSelectorTest.class);
- suite.addTestSuite(AbstractSelectableChannelTest.class);
- suite.addTestSuite(SelectorProviderTest.class);
- suite.addTestSuite(AbstractSelectionKeyTest.class);
- //$JUnit-END$
- return suite;
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java
deleted file mode 100644
index 59364c8..0000000
--- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java
+++ /dev/null
@@ -1,134 +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.nio.tests.java.nio.channels.spi;
-
-import java.io.IOException;
-import java.nio.channels.SelectableChannel;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.spi.AbstractSelectableChannel;
-import java.nio.channels.spi.AbstractSelectionKey;
-import java.nio.channels.spi.AbstractSelector;
-import java.nio.channels.spi.SelectorProvider;
-import java.util.HashSet;
-import java.util.Set;
-
-public class MockAbstractSelector extends AbstractSelector {
-
- class MockSelectionKey extends AbstractSelectionKey {
-
- boolean cancelled = false;
- Selector selector;
- SelectableChannel channel;
-
- MockSelectionKey(Selector sel, SelectableChannel chan) {
- selector = sel;
- channel = chan;
- }
-
- @Override
- public SelectableChannel channel() {
- return channel;
- }
-
- @Override
- public int interestOps() {
- return 0;
- }
-
- @Override
- public SelectionKey interestOps(int operations) {
- return null;
- }
-
- @Override
- public int readyOps() {
- return 0;
- }
-
- @Override
- public Selector selector() {
- return selector;
- }
- }
-
- public boolean isImplCloseSelectorCalled = false;
- private Set<SelectionKey> keys = new HashSet<SelectionKey>();
- public boolean isRegisterCalled = false;
-
- public MockAbstractSelector(SelectorProvider arg0) {
- super(arg0);
- }
-
- public static MockAbstractSelector openSelector() {
- return new MockAbstractSelector(SelectorProvider.provider());
- }
-
- public Set<SelectionKey> getCancelledKeys() {
- return super.cancelledKeys();
- }
-
- protected void implCloseSelector() throws IOException {
- isImplCloseSelectorCalled = true;
- }
-
- protected SelectionKey register(AbstractSelectableChannel arg0, int arg1,
- Object arg2) {
- isRegisterCalled = true;
-
- SelectionKey key = new MockSelectionKey(this, arg0);
- keys.add(key);
- return key;
- }
-
- public void superBegin() {
- super.begin();
- }
-
- public void superEnd() {
- super.end();
- }
-
- public void mockDeregister(AbstractSelectionKey key) {
- super.deregister(key);
- }
-
- public Set<SelectionKey> keys() {
- return keys;
- }
-
- public Set<SelectionKey> selectedKeys() {
- return null;
- }
-
- public int selectNow() throws IOException {
- return 0;
- }
-
- public int select(long arg0) throws IOException {
- return 0;
- }
-
- public int select() throws IOException {
- return 0;
- }
-
- public Selector wakeup() {
- return null;
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/xml/AllTests.java b/luni/src/test/java/org/apache/harmony/xml/ExpatPullParserTest.java
similarity index 67%
copy from luni/src/test/java/org/apache/harmony/xml/AllTests.java
copy to luni/src/test/java/org/apache/harmony/xml/ExpatPullParserTest.java
index c04c1b5..71e2671 100644
--- a/luni/src/test/java/org/apache/harmony/xml/AllTests.java
+++ b/luni/src/test/java/org/apache/harmony/xml/ExpatPullParserTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009 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.
@@ -16,14 +16,12 @@
package org.apache.harmony.xml;
-import junit.framework.Test;
-import junit.framework.TestSuite;
+import org.xmlpull.v1.XmlPullParser;
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite();
- suite.addTestSuite(ExpatParserTest.class);
- return suite;
+public final class ExpatPullParserTest extends PullParserTest {
+
+ @Override XmlPullParser newPullParser() {
+ ExpatPullParser parser = new ExpatPullParser();
+ return parser;
}
-
}
diff --git a/luni/src/test/java/org/apache/harmony/xml/ExpatParserTest.java b/luni/src/test/java/org/apache/harmony/xml/ExpatSaxParserTest.java
similarity index 81%
rename from luni/src/test/java/org/apache/harmony/xml/ExpatParserTest.java
rename to luni/src/test/java/org/apache/harmony/xml/ExpatSaxParserTest.java
index ff25ade..51804f2 100644
--- a/luni/src/test/java/org/apache/harmony/xml/ExpatParserTest.java
+++ b/luni/src/test/java/org/apache/harmony/xml/ExpatSaxParserTest.java
@@ -18,7 +18,6 @@
import junit.framework.Assert;
import junit.framework.TestCase;
-import org.kxml2.io.KXmlParser;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
@@ -27,8 +26,6 @@
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import org.xml.sax.helpers.DefaultHandler;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -44,7 +41,7 @@
import java.net.ServerSocket;
import java.net.Socket;
-public class ExpatParserTest extends TestCase {
+public class ExpatSaxParserTest extends TestCase {
private static final String SNIPPET = "<dagny dad=\"bob\">hello</dagny>";
@@ -157,163 +154,11 @@
}
}
- public void testPullParser() {
- try {
- XmlPullParser parser = newPullParser();
-
- // Test reader.
- parser.setInput(new StringReader(SNIPPET));
- validate(parser);
-
- // Test input stream.
- parser.setInput(new ByteArrayInputStream(SNIPPET.getBytes()),
- "UTF-8");
- validate(parser);
- } catch (XmlPullParserException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- static void validate(XmlPullParser parser)
- throws XmlPullParserException, IOException {
- assertEquals(XmlPullParser.START_DOCUMENT, parser.getEventType());
-
- assertEquals(0, parser.getDepth());
-
- assertEquals(XmlPullParser.START_TAG, parser.next());
-
- assertEquals(1, parser.getDepth());
-
- assertEquals("dagny", parser.getName());
- assertEquals(1, parser.getAttributeCount());
- assertEquals("dad", parser.getAttributeName(0));
- assertEquals("bob", parser.getAttributeValue(0));
- assertEquals("bob", parser.getAttributeValue(null, "dad"));
-
- assertEquals(XmlPullParser.TEXT, parser.next());
-
- assertEquals(1, parser.getDepth());
-
- assertEquals("hello", parser.getText());
-
- assertEquals(XmlPullParser.END_TAG, parser.next());
-
- assertEquals(1, parser.getDepth());
-
- assertEquals("dagny", parser.getName());
-
- assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
-
- assertEquals(0, parser.getDepth());
- }
-
static final String XML =
"<one xmlns='ns:default' xmlns:n1='ns:1' a='b'>\n"
+ " <n1:two c='d' n1:e='f' xmlns:n2='ns:2'>text</n1:two>\n"
+ "</one>";
- public void testExpatPullParserNamespaces() throws Exception {
- XmlPullParser pullParser = newPullParser();
- pullParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
- pullParser.setInput(new StringReader(XML));
- testPullParserNamespaces(pullParser);
- }
-
- public void testKxmlPullParserNamespaces() throws Exception {
- XmlPullParser pullParser = new KXmlParser();
- pullParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
- pullParser.setInput(new StringReader(XML));
- testPullParserNamespaces(pullParser);
- }
-
- private void testPullParserNamespaces(XmlPullParser parser) throws Exception {
- assertEquals(0, parser.getDepth());
- assertEquals(0, parser.getNamespaceCount(0));
-
- try {
- parser.getNamespaceCount(1);
- fail();
- } catch (IndexOutOfBoundsException e) { /* expected */ }
-
- // one
- assertEquals(XmlPullParser.START_TAG, parser.next());
- assertEquals(1, parser.getDepth());
-
- checkNamespacesInOne(parser);
-
- // n1:two
- assertEquals(XmlPullParser.START_TAG, parser.nextTag());
-
- assertEquals(2, parser.getDepth());
- checkNamespacesInTwo(parser);
-
- // Body of two.
- assertEquals(XmlPullParser.TEXT, parser.next());
-
- // End of two.
- assertEquals(XmlPullParser.END_TAG, parser.nextTag());
-
- // Depth should still be 2.
- assertEquals(2, parser.getDepth());
-
- // We should still be able to see the namespaces from two.
- checkNamespacesInTwo(parser);
-
- // End of one.
- assertEquals(XmlPullParser.END_TAG, parser.nextTag());
-
- // Depth should be back to 1.
- assertEquals(1, parser.getDepth());
-
- // We can still see the namespaces in one.
- checkNamespacesInOne(parser);
-
- // We shouldn't be able to see the namespaces in two anymore.
- try {
- parser.getNamespaceCount(2);
- fail();
- } catch (IndexOutOfBoundsException e) { /* expected */ }
-
- assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
-
- // We shouldn't be able to see the namespaces in one anymore.
- try {
- parser.getNamespaceCount(1);
- fail();
- } catch (IndexOutOfBoundsException e) { /* expected */ }
-
- assertEquals(0, parser.getNamespaceCount(0));
- }
-
- private void checkNamespacesInOne(XmlPullParser parser) throws XmlPullParserException {
- assertEquals(2, parser.getNamespaceCount(1));
-
- // Prefix for default namespace is null.
- assertNull(parser.getNamespacePrefix(0));
- assertEquals("ns:default", parser.getNamespaceUri(0));
-
- assertEquals("n1", parser.getNamespacePrefix(1));
- assertEquals("ns:1", parser.getNamespaceUri(1));
-
- assertEquals("ns:default", parser.getNamespace(null));
-
- // KXML returns null.
- // assertEquals("ns:default", parser.getNamespace(""));
- }
-
- private void checkNamespacesInTwo(XmlPullParser parser) throws XmlPullParserException {
- // These should still be valid.
- checkNamespacesInOne(parser);
-
- assertEquals(3, parser.getNamespaceCount(2));
-
- // Default ns should still be in the stack
- assertNull(parser.getNamespacePrefix(0));
- assertEquals("ns:default", parser.getNamespaceUri(0));
- }
-
public void testNamespaces() {
try {
NamespaceHandler handler = new NamespaceHandler();
@@ -880,13 +725,4 @@
this.expatName = expatName;
}
}
-
- /**
- * Creates a new pull parser with namespace support.
- */
- private static XmlPullParser newPullParser() {
- ExpatPullParser parser = new ExpatPullParser();
- parser.setNamespaceProcessingEnabled(true);
- return parser;
- }
}
diff --git a/luni/src/test/java/org/apache/harmony/xml/AllTests.java b/luni/src/test/java/org/apache/harmony/xml/KxmlPullParserTest.java
similarity index 67%
rename from luni/src/test/java/org/apache/harmony/xml/AllTests.java
rename to luni/src/test/java/org/apache/harmony/xml/KxmlPullParserTest.java
index c04c1b5..3603d89 100644
--- a/luni/src/test/java/org/apache/harmony/xml/AllTests.java
+++ b/luni/src/test/java/org/apache/harmony/xml/KxmlPullParserTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009 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.
@@ -16,14 +16,12 @@
package org.apache.harmony.xml;
-import junit.framework.Test;
-import junit.framework.TestSuite;
+import org.kxml2.io.KXmlParser;
+import org.xmlpull.v1.XmlPullParser;
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite();
- suite.addTestSuite(ExpatParserTest.class);
- return suite;
+public class KxmlPullParserTest extends PullParserTest {
+
+ @Override XmlPullParser newPullParser() {
+ return new KXmlParser();
}
-
}
diff --git a/luni/src/test/java/org/apache/harmony/xml/PullParserTest.java b/luni/src/test/java/org/apache/harmony/xml/PullParserTest.java
new file mode 100644
index 0000000..d6d5370
--- /dev/null
+++ b/luni/src/test/java/org/apache/harmony/xml/PullParserTest.java
@@ -0,0 +1,181 @@
+/*
+ * 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 org.apache.harmony.xml;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import junit.framework.TestCase;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+public abstract class PullParserTest extends TestCase {
+ private static final String SNIPPET = "<dagny dad=\"bob\">hello</dagny>";
+
+ public void testPullParser() {
+ try {
+ XmlPullParser parser = newPullParser();
+ parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
+
+ // Test reader.
+ parser.setInput(new StringReader(SNIPPET));
+ validate(parser);
+
+ // Test input stream.
+ parser.setInput(new ByteArrayInputStream(SNIPPET.getBytes()),
+ "UTF-8");
+ validate(parser);
+ } catch (XmlPullParserException e) {
+ throw new RuntimeException(e);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ static void validate(XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ assertEquals(XmlPullParser.START_DOCUMENT, parser.getEventType());
+
+ assertEquals(0, parser.getDepth());
+
+ assertEquals(XmlPullParser.START_TAG, parser.next());
+
+ assertEquals(1, parser.getDepth());
+
+ assertEquals("dagny", parser.getName());
+ assertEquals(1, parser.getAttributeCount());
+ assertEquals("dad", parser.getAttributeName(0));
+ assertEquals("bob", parser.getAttributeValue(0));
+ assertEquals("bob", parser.getAttributeValue(null, "dad"));
+
+ assertEquals(XmlPullParser.TEXT, parser.next());
+
+ assertEquals(1, parser.getDepth());
+
+ assertEquals("hello", parser.getText());
+
+ assertEquals(XmlPullParser.END_TAG, parser.next());
+
+ assertEquals(1, parser.getDepth());
+
+ assertEquals("dagny", parser.getName());
+
+ assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
+
+ assertEquals(0, parser.getDepth());
+ }
+
+ static final String XML =
+ "<one xmlns='ns:default' xmlns:n1='ns:1' a='b'>\n"
+ + " <n1:two c='d' n1:e='f' xmlns:n2='ns:2'>text</n1:two>\n"
+ + "</one>";
+
+ public void testExpatPullParserNamespaces() throws Exception {
+ XmlPullParser parser = newPullParser();
+ parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+ parser.setInput(new StringReader(XML));
+
+ assertEquals(0, parser.getDepth());
+ assertEquals(0, parser.getNamespaceCount(0));
+
+ try {
+ parser.getNamespaceCount(1);
+ fail();
+ } catch (IndexOutOfBoundsException e) { /* expected */ }
+
+ // one
+ assertEquals(XmlPullParser.START_TAG, parser.next());
+ assertEquals(1, parser.getDepth());
+
+ checkNamespacesInOne(parser);
+
+ // n1:two
+ assertEquals(XmlPullParser.START_TAG, parser.nextTag());
+
+ assertEquals(2, parser.getDepth());
+ checkNamespacesInTwo(parser);
+
+ // Body of two.
+ assertEquals(XmlPullParser.TEXT, parser.next());
+
+ // End of two.
+ assertEquals(XmlPullParser.END_TAG, parser.nextTag());
+
+ // Depth should still be 2.
+ assertEquals(2, parser.getDepth());
+
+ // We should still be able to see the namespaces from two.
+ checkNamespacesInTwo(parser);
+
+ // End of one.
+ assertEquals(XmlPullParser.END_TAG, parser.nextTag());
+
+ // Depth should be back to 1.
+ assertEquals(1, parser.getDepth());
+
+ // We can still see the namespaces in one.
+ checkNamespacesInOne(parser);
+
+ // We shouldn't be able to see the namespaces in two anymore.
+ try {
+ parser.getNamespaceCount(2);
+ fail();
+ } catch (IndexOutOfBoundsException e) { /* expected */ }
+
+ assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
+
+ // We shouldn't be able to see the namespaces in one anymore.
+ try {
+ parser.getNamespaceCount(1);
+ fail();
+ } catch (IndexOutOfBoundsException e) { /* expected */ }
+
+ assertEquals(0, parser.getNamespaceCount(0));
+ }
+
+ private void checkNamespacesInOne(XmlPullParser parser) throws XmlPullParserException {
+ assertEquals(2, parser.getNamespaceCount(1));
+
+ // Prefix for default namespace is null.
+ assertNull(parser.getNamespacePrefix(0));
+ assertEquals("ns:default", parser.getNamespaceUri(0));
+
+ assertEquals("n1", parser.getNamespacePrefix(1));
+ assertEquals("ns:1", parser.getNamespaceUri(1));
+
+ assertEquals("ns:default", parser.getNamespace(null));
+
+ // KXML returns null.
+ // assertEquals("ns:default", parser.getNamespace(""));
+ }
+
+ private void checkNamespacesInTwo(XmlPullParser parser) throws XmlPullParserException {
+ // These should still be valid.
+ checkNamespacesInOne(parser);
+
+ assertEquals(3, parser.getNamespaceCount(2));
+
+ // Default ns should still be in the stack
+ assertNull(parser.getNamespacePrefix(0));
+ assertEquals("ns:default", parser.getNamespaceUri(0));
+ }
+
+ /**
+ * Creates a new pull parser with namespace support.
+ */
+ abstract XmlPullParser newPullParser();
+}
diff --git a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java
index 1787fe6..fa56c6b 100644
--- a/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java
+++ b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/NativeCryptoTest.java
@@ -107,17 +107,13 @@
}
private static final PrivateKeyEntry SERVER_PRIVATE_KEY_ENTRY
- = TestKeyStore.privateKey(TestKeyStore.getServer().keyStore,
- TestKeyStore.getServer().keyPassword,
- "RSA");
+ = TestKeyStore.getServer().getPrivateKey("RSA");
private static final byte[] SERVER_PRIVATE_KEY
= SERVER_PRIVATE_KEY_ENTRY.getPrivateKey().getEncoded();
private static final byte[][] SERVER_CERTIFICATES;
private static final PrivateKeyEntry CLIENT_PRIVATE_KEY_ENTRY
- = TestKeyStore.privateKey(TestKeyStore.getClientCertificate().keyStore,
- TestKeyStore.getClientCertificate().keyPassword,
- "RSA");
+ = TestKeyStore.getClientCertificate().getPrivateKey("RSA");
private static final byte[] CLIENT_PRIVATE_KEY
= CLIENT_PRIVATE_KEY_ENTRY.getPrivateKey().getEncoded();
private static final byte[][] CLIENT_CERTIFICATES;
diff --git a/luni/src/test/java/tests/AllTests.java b/luni/src/test/java/tests/AllTests.java
index be91bd0..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());
@@ -42,7 +41,6 @@
suite.addTest(tests.luni.AllTestsNet.suite());
suite.addTest(tests.luni.AllTestsUtil.suite());
suite.addTest(tests.math.AllTests.suite());
- suite.addTest(tests.nio.AllTests.suite());
suite.addTest(tests.nio_char.AllTests.suite());
suite.addTest(tests.prefs.AllTests.suite());
suite.addTest(tests.regex.AllTests.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/nio/charset/AbstractCharsetDecoderTestCase.java b/luni/src/test/java/tests/api/java/nio/charset/AbstractCharsetDecoderTestCase.java
deleted file mode 100644
index acae58d..0000000
--- a/luni/src/test/java/tests/api/java/nio/charset/AbstractCharsetDecoderTestCase.java
+++ /dev/null
@@ -1,762 +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.nio.charset;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.CodingErrorAction;
-import java.nio.charset.MalformedInputException;
-import java.nio.charset.UnmappableCharacterException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(CharsetDecoder.class)
-
-/**
- * Super class for concrete charset test suites.
- */
-public class AbstractCharsetDecoderTestCase extends TestCase {
-
- Charset cs;
-
- // Target decoder (tobj):
- protected static CharsetDecoder decoder;
-
- static final String unistr = " buffer";// \u8000\u8001\u00a5\u3000\r\n";
-
- byte[] unibytes;
-
- String bom = "";
-
-
- protected void setUp() throws Exception {
- super.setUp();
- decoder = cs.newDecoder();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "charset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "detectedCharset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isCharsetDetected",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isAutoDetecting",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "malformedInputAction",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "unmappableCharacterAction",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "replacement",
- args = {}
- )
- })
- public void testDefaultValues() {
- assertSame(cs, decoder.charset());
- try {
- decoder.detectedCharset();
- fail("should unsupported");
- } catch (UnsupportedOperationException e) {
- }
- try {
- assertTrue(decoder.isCharsetDetected());
- fail("should unsupported");
- } catch (UnsupportedOperationException e) {
- }
- assertFalse(decoder.isAutoDetecting());
- assertSame(CodingErrorAction.REPORT, decoder.malformedInputAction());
- assertSame(CodingErrorAction.REPORT, decoder
- .unmappableCharacterAction());
- assertEquals(decoder.replacement(), "\ufffd");
- }
-
-
-
- /*
- * test onMalformedInput
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "malformedInputAction",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "onMalformedInput",
- args = {java.nio.charset.CodingErrorAction.class}
- )
- })
- public void testOnMalformedInput() {
- assertSame(CodingErrorAction.REPORT, decoder.malformedInputAction());
- try {
- decoder.onMalformedInput(null);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- decoder.onMalformedInput(CodingErrorAction.IGNORE);
- assertSame(CodingErrorAction.IGNORE, decoder.malformedInputAction());
- }
-
- /*
- * test unmappableCharacter
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "unmappableCharacterAction",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "onUnmappableCharacter",
- args = {java.nio.charset.CodingErrorAction.class}
- )
- })
- public void testOnUnmappableCharacter() {
- assertSame(CodingErrorAction.REPORT, decoder
- .unmappableCharacterAction());
- try {
- decoder.onUnmappableCharacter(null);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
- assertSame(CodingErrorAction.IGNORE, decoder
- .unmappableCharacterAction());
- }
-
- /*
- * test replaceWith
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "replaceWith",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "replacement",
- args = {}
- )
- })
- public void testReplaceWith() {
- try {
- decoder.replaceWith(null);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- try {
- decoder.replaceWith("");
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- try {
- decoder.replaceWith("testReplaceWith");
- fail("should throw illegal argument exception");
- } catch (IllegalArgumentException e) {
- }
-
- decoder.replaceWith("a");
- assertSame("a", decoder.replacement());
- }
-
- /*
- * Class under test for CharBuffer decode(ByteBuffer)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testDecodeByteBuffer() throws CharacterCodingException {
- implTestDecodeByteBuffer();
- }
-
- void implTestDecodeByteBuffer() throws CharacterCodingException {
- // Null pointer
- try {
- decoder.decode(null);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
-
- // empty input buffer
- CharBuffer out = decoder.decode(ByteBuffer.allocate(0));
- assertCharBufferValue(out, "");
-
- // normal case
- ByteBuffer in = ByteBuffer.wrap(getUnibytes());
- out = decoder.decode(in);
- assertEquals(out.position(), 0);
- assertEquals(out.limit(), unistr.length());
- assertEquals(out.remaining(), unistr.length());
- assertEquals(new String(out.array(), 0, out.limit()), unistr);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class}
- )
- public void testDecodeByteBufferException()
- throws CharacterCodingException, UnsupportedEncodingException {
- CharBuffer out;
- ByteBuffer in;
- String replaceStr = decoder.replacement() + " buffer";
-
- // MalformedException:
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- in = getMalformByteBuffer();
- if (in != null) {
- try {
- CharBuffer buffer = decoder.decode(in);
- assertTrue(buffer.remaining() > 0);
- fail("should throw MalformedInputException");
- } catch (MalformedInputException e) {
- }
-
- decoder.reset();
- in.rewind();
- decoder.onMalformedInput(CodingErrorAction.IGNORE);
- out = decoder.decode(in);
- assertCharBufferValue(out, " buffer");
-
- decoder.reset();
- in.rewind();
- decoder.onMalformedInput(CodingErrorAction.REPLACE);
- out = decoder.decode(in);
- assertCharBufferValue(out, replaceStr);
- }
-
- // Unmapped Exception:
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- in = getUnmappedByteBuffer();
- if (in != null) {
- try {
- decoder.decode(in);
- fail("should throw UnmappableCharacterException");
- } catch (UnmappableCharacterException e) {
- }
-
- decoder.reset();
- in.rewind();
- decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
- out = decoder.decode(in);
- assertCharBufferValue(out, " buffer");
-
- decoder.reset();
- in.rewind();
- decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
- out = decoder.decode(in);
- assertCharBufferValue(out, replaceStr);
- }
-
- // RuntimeException
- try {
- decoder.decode(getExceptionByteArray());
- fail("should throw runtime exception");
- } catch (RuntimeException e) {
- }
- }
-
- /*
- * Class under test for CoderResult decode(ByteBuffer, CharBuffer, boolean)
- */
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class, java.nio.CharBuffer.class, boolean.class}
- )
- public void testDecodeByteBufferCharBufferboolean() {
- implTestDecodeByteBufferCharBufferboolean();
- }
-
- void implTestDecodeByteBufferCharBufferboolean() {
- byte[] gb = getUnibytes();
- ByteBuffer in = ByteBuffer.wrap(gb);
- CharBuffer out = CharBuffer.allocate(100);
-
- // Null pointer
- try {
- decoder.decode(null, out, true);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
- try {
- decoder.decode(in, null, true);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
-
- // normal case, one complete operation
- decoder.reset();
- in.rewind();
- out.rewind();
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, true));
- assertEquals(out.limit(), 100);
- assertEquals(out.position(), unistr.length());
- assertEquals(out.remaining(), 100 - unistr.length());
- assertEquals(out.capacity(), 100);
- assertCharBufferValue(out, unistr);
- decoder.flush(out);
-
- // normal case, one complete operation, but call twice, first time set
- // endOfInput to false
- decoder.reset();
- in.rewind();
- out.clear();
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false));
- assertEquals(out.limit(), 100);
- assertEquals(out.position(), unistr.length());
- assertEquals(out.remaining(), 100 - unistr.length());
- assertEquals(out.capacity(), 100);
- assertCharBufferValue(out, unistr);
-
- decoder.reset();
- in.rewind();
- out.clear();
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false));
- in = ByteBuffer.wrap(unibytes);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false));
- in.rewind();
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, true));
- assertEquals(out.limit(), 100);
- assertTrue(out.position() > 0);
- assertEquals(out.remaining(), out.capacity() - out.position());
- assertEquals(out.capacity(), 100);
- assertCharBufferValue(out, unistr + unistr + unistr);
-
- // overflow
- out = CharBuffer.allocate(4);
- decoder.reset();
- in = ByteBuffer.wrap(getUnibytes());
- out.rewind();
- assertSame(CoderResult.OVERFLOW, decoder.decode(in, out, false));
-
- assertEquals(new String(out.array()), unistr.substring(0, 4));
- out = CharBuffer.allocate(100);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, false));
- assertCharBufferValue(out, unistr.substring(4));
- in.rewind();
- out = CharBuffer.allocate(100);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out, true));
- assertCharBufferValue(out, bom + unistr);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class, java.nio.CharBuffer.class, boolean.class}
- )
- public void testDecodeCharBufferByteBufferbooleanExceptionTrue()
- throws CharacterCodingException, UnsupportedEncodingException {
- implTestDecodeCharBufferByteBufferbooleanException(true);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class, java.nio.CharBuffer.class, boolean.class}
- )
- public void testDecodeCharBufferByteBufferbooleanExceptionFalse()
- throws CharacterCodingException, UnsupportedEncodingException {
- implTestDecodeCharBufferByteBufferbooleanException(false);
- }
-
- void implTestDecodeCharBufferByteBufferbooleanException(boolean endOfInput)
- throws CharacterCodingException, UnsupportedEncodingException {
- CharBuffer out;
- ByteBuffer in;
-
- // Unmapped Exception:
- in = getUnmappedByteBuffer();
- out = CharBuffer.allocate(50);
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- if (null != in) {
- decoder.reset();
- decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- CoderResult result = decoder.decode(in, out, endOfInput);
- assertTrue(result.isUnmappable());
-
- decoder.reset();
- out.clear();
- in.rewind();
- decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out,
- endOfInput));
- assertCharBufferValue(out, " buffer");
-
- decoder.reset();
- out.clear();
- in.rewind();
- decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out,
- endOfInput));
- assertCharBufferValue(out, decoder.replacement() + " buffer");
- } else if (endOfInput) {
- // System.err.println("Cannot find unmappable byte array for "
- // + cs.name());
- }
-
- // MalformedException:
- in = getMalformByteBuffer();
- out = CharBuffer.allocate(50);
- decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- if (null != in) {
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- CoderResult result = decoder.decode(in, out, endOfInput);
- assertTrue(result.isMalformed());
-
- decoder.reset();
- out.clear();
- in.rewind();
- decoder.onMalformedInput(CodingErrorAction.IGNORE);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out,
- endOfInput));
- assertCharBufferValue(out, " buffer");
-
- decoder.reset();
- out.clear();
- in.rewind();
- decoder.onMalformedInput(CodingErrorAction.REPLACE);
- assertSame(CoderResult.UNDERFLOW, decoder.decode(in, out,
- endOfInput));
- assertCharBufferValue(out, decoder.replacement() + " buffer");
- } else if (endOfInput) {
- // System.err.println("Cannot find malform byte array for "
- // + cs.name());
- }
-
- // RuntimeException
- in = getExceptionByteArray();
- try {
- decoder.decode(in, out, endOfInput);
- fail("should throw runtime exception");
- } catch (RuntimeException e) {
- }
- }
-
- ByteBuffer getExceptionByteArray() throws UnsupportedEncodingException {
- // "runtime"
- return ByteBuffer
- .wrap(new byte[] { 114, 117, 110, 116, 105, 109, 101 });
- }
-
- ByteBuffer getUnmappedByteBuffer() throws UnsupportedEncodingException {
- // "unmap buffer"
- byte[] ba = new byte[] { 117, 110, 109, 97, 112, 32, 98, 117, 102, 102,
- 101, 114 };
- return ByteBuffer.wrap(ba);
- }
-
- ByteBuffer getMalformByteBuffer() throws UnsupportedEncodingException {
- // "malform buffer"
- byte[] ba = new byte[] { 109, 97, 108, 102, 111, 114, 109, 32, 98, 117,
- 102, 102, 101, 114 };
- return ByteBuffer.wrap(ba);
- }
-
- void assertCharBufferValue(CharBuffer out, String expected) {
- if (out.position() != 0) {
- out.flip();
- }
- assertEquals(new String(out.array(), 0, out.limit()), expected);
- }
-
- /*
- * test flush
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.CharBuffer.class}
- )
- public void testFlush() throws CharacterCodingException {
- CharBuffer out = CharBuffer.allocate(10);
- ByteBuffer in = ByteBuffer.wrap(new byte[] { 12, 12 });
- decoder.decode(in, out, true);
- assertSame(CoderResult.UNDERFLOW, decoder.flush(out));
-
- decoder.reset();
- decoder.decode((ByteBuffer) in.rewind(), (CharBuffer) out.rewind(),
- true);
- assertSame(CoderResult.UNDERFLOW, decoder
- .flush(CharBuffer.allocate(10)));
- }
-
-
- /*
- * ---------------------------------- methods to test illegal state
- * -----------------------------------
- */
-
- // Normal case: just after reset, and it also means reset can be done
- // anywhere
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- )
- public void testResetIllegalState() throws CharacterCodingException {
- byte[] gb = getUnibytes();
- decoder.reset();
- decoder.decode(ByteBuffer.wrap(gb));
- decoder.reset();
- decoder.decode(ByteBuffer.wrap(gb), CharBuffer.allocate(3), false);
- decoder.reset();
- decoder.decode(ByteBuffer.wrap(gb), CharBuffer.allocate(3), true);
- decoder.reset();
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.CharBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- )
- })
- public void testFlushIllegalState() throws CharacterCodingException {
- ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 });
- CharBuffer out = CharBuffer.allocate(5);
- // Normal case: after decode with endOfInput is true
- decoder.reset();
- decoder.decode(in, out, true);
- out.rewind();
- CoderResult result = decoder.flush(out);
- assertSame(result, CoderResult.UNDERFLOW);
-
- // Illegal state: flush twice
- try {
- decoder.flush(out);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- }
-
- // Illegal state: flush after decode with endOfInput is false
- decoder.reset();
- decoder.decode(in, out, false);
- try {
- decoder.flush(out);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- }
- }
-
- byte[] getUnibytes() {
- return unibytes;
- }
-
- // test illegal states for decode facade
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class, java.nio.CharBuffer.class, boolean.class}
- )
- })
- public void testDecodeFacadeIllegalState() throws CharacterCodingException {
- // decode facade can be execute in anywhere
- byte[] gb = getUnibytes();
- ByteBuffer in = ByteBuffer.wrap(gb);
- // Normal case: just created
- decoder.decode(in);
- in.rewind();
-
- // Normal case: just after decode facade
- decoder.decode(in);
- in.rewind();
-
- // Normal case: just after decode with that endOfInput is true
- decoder.reset();
- decoder.decode(ByteBuffer.wrap(gb), CharBuffer.allocate(30), true);
- decoder.decode(in);
- in.rewind();
-
- // Normal case:just after decode with that endOfInput is false
- decoder.reset();
- decoder.decode(ByteBuffer.wrap(gb), CharBuffer.allocate(30), false);
- decoder.decode(in);
- in.rewind();
-
- // Normal case: just after flush
- decoder.reset();
- decoder.decode(ByteBuffer.wrap(gb), CharBuffer.allocate(30), true);
- decoder.flush(CharBuffer.allocate(10));
- decoder.decode(in);
- in.rewind();
- }
-
- // test illegal states for two decode method with endOfInput is true
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class, java.nio.CharBuffer.class, boolean.class}
- )
- public void testDecodeTrueIllegalState() throws CharacterCodingException {
- ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 });
- CharBuffer out = CharBuffer.allocate(100);
- // Normal case: just created
- decoder.decode(in, out, true);
- in.rewind();
- out.rewind();
-
- // Normal case: just after decode with that endOfInput is true
- decoder.reset();
- decoder.decode(in, CharBuffer.allocate(30), true);
- in.rewind();
- decoder.decode(in, out, true);
- in.rewind();
- out.rewind();
-
- // Normal case:just after decode with that endOfInput is false
- decoder.reset();
- decoder.decode(in, CharBuffer.allocate(30), false);
- in.rewind();
- decoder.decode(in, out, true);
- in.rewind();
- out.rewind();
-
- // Illegal state: just after flush
- decoder.reset();
- decoder.decode(in, CharBuffer.allocate(30), true);
- decoder.flush(CharBuffer.allocate(10));
- in.rewind();
- try {
- decoder.decode(in, out, true);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
- in.rewind();
- out.rewind();
-
- }
-
- // test illegal states for two decode method with endOfInput is false
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "decode",
- args = {java.nio.ByteBuffer.class, java.nio.CharBuffer.class, boolean.class}
- )
- public void testDecodeFalseIllegalState() throws CharacterCodingException {
- ByteBuffer in = ByteBuffer.wrap(new byte[] { 98, 98 });
- CharBuffer out = CharBuffer.allocate(5);
- // Normal case: just created
- decoder.decode(in, out, false);
- in.rewind();
- out.rewind();
-
- // Illegal state: just after decode facade
- decoder.reset();
- decoder.decode(in);
- in.rewind();
- try {
- decoder.decode(in, out, false);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
- in.rewind();
- out.rewind();
-
- // Illegal state: just after decode with that endOfInput is true
- decoder.reset();
- decoder.decode(in, CharBuffer.allocate(30), true);
- in.rewind();
- try {
- decoder.decode(in, out, false);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
- in.rewind();
- out.rewind();
-
- // Normal case:just after decode with that endOfInput is false
- decoder.reset();
- decoder.decode(in, CharBuffer.allocate(30), false);
- in.rewind();
- decoder.decode(in, out, false);
- in.rewind();
- out.rewind();
-
- // Illegal state: just after flush
- decoder.reset();
- decoder.decode(in, CharBuffer.allocate(30), true);
- in.rewind();
- decoder.flush(CharBuffer.allocate(10));
- try {
- decoder.decode(in, out, false);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
- }
-
- /*
- * --------------------------------- illegal state test end
- * ---------------------------------
- */
-
-}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/AbstractCharsetEncoderTestCase.java b/luni/src/test/java/tests/api/java/nio/charset/AbstractCharsetEncoderTestCase.java
deleted file mode 100644
index 32fa2fe..0000000
--- a/luni/src/test/java/tests/api/java/nio/charset/AbstractCharsetEncoderTestCase.java
+++ /dev/null
@@ -1,1048 +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.nio.charset;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.CodingErrorAction;
-import java.nio.charset.MalformedInputException;
-import java.nio.charset.UnmappableCharacterException;
-import java.nio.charset.UnsupportedCharsetException;
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(CharsetEncoder.class)
-
-/**
- * Super class for concrete charset test suites.
- */
-public class AbstractCharsetEncoderTestCase extends TestCase {
-
- Charset cs;
-
- // Target encoder (tobj):
- CharsetEncoder encoder;
-
- static final String unistr = " buffer";// \u8000\u8001\u00a5\u3000\r\n";
-
- byte[] unibytes = new byte[] { 32, 98, 117, 102, 102, 101, 114 };
-
-
- // default for Charset abstract class
- byte[] defaultReplacement = new byte[] { 63 };
-
- // specific for Charset implementation subclass
- byte[] specifiedReplacement = new byte[] { 26 };
-
- byte[] unibytesWithRep = null;
-
- byte[] surrogate = new byte[0];
-
-
- protected void setUp() throws Exception {
- super.setUp();
- encoder = cs.newEncoder();
- if (null == unibytesWithRep) {
- byte[] replacement = encoder.replacement();
- unibytesWithRep = new byte[replacement.length + unibytes.length];
- System.arraycopy(replacement, 0, unibytesWithRep, 0,
- replacement.length);
- System.arraycopy(unibytes, 0, unibytesWithRep, replacement.length,
- unibytes.length);
- }
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
-
- /*
- * Class under test for boolean canEncode(char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {char.class}
- )
- public void testCanEncodechar() throws CharacterCodingException {
- // for non-mapped char
- assertTrue(encoder.canEncode('\uc2c0'));
- // surrogate char for unicode
- // 1st byte: d800-dbff
- // 2nd byte: dc00-dfff
- assertTrue(encoder.canEncode('\ud800'));
- // valid surrogate pair
- assertTrue(encoder.canEncode('\udc00'));
- }
-
- /*-----------------------------------------
- * Class under test for illegal state case
- * methods which can change internal states are two encode, flush, two canEncode, reset
- * -----------------------------------------
- */
-
- // Normal case: just after reset, and it also means reset can be done
- // anywhere
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- )
- })
- public void testResetIllegalState() throws CharacterCodingException {
- assertSame(encoder, encoder.reset());
- encoder.canEncode('\ud901');
- assertSame(encoder, encoder.reset());
- encoder.canEncode("\ud901\udc00");
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("aaa"));
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("aaa"), ByteBuffer.allocate(3), false);
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("aaa"), ByteBuffer.allocate(3), true);
- assertSame(encoder, encoder.reset());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testFlushIllegalState() throws CharacterCodingException {
- CharBuffer in = CharBuffer.wrap("aaa");
- ByteBuffer out = ByteBuffer.allocate(5);
-
- // Normal case: after encode with endOfInput is true
- assertSame(encoder, encoder.reset());
- encoder.encode(in, out, true);
- out.rewind();
- CoderResult result = encoder.flush(out);
-
- // Illegal state: flush twice
- try {
- encoder.flush(out);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- }
-
- // Illegal state: flush after encode with endOfInput is false
- assertSame(encoder, encoder.reset());
- encoder.encode(in, out, false);
- try {
- encoder.flush(out);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- }
- }
-
- // test illegal states for encode facade
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testEncodeFacadeIllegalState() throws CharacterCodingException {
- // encode facade can be execute in anywhere
- CharBuffer in = CharBuffer.wrap("aaa");
- // Normal case: just created
- encoder.encode(in);
- in.rewind();
-
- // Normal case: just after encode facade
- encoder.encode(in);
- in.rewind();
-
- // Normal case: just after canEncode
- assertSame(encoder, encoder.reset());
- encoder.canEncode("\ud902\udc00");
- encoder.encode(in);
- in.rewind();
- assertSame(encoder, encoder.reset());
- encoder.canEncode('\ud902');
- encoder.encode(in);
- in.rewind();
-
- // Normal case: just after encode with that endOfInput is true
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
- ByteBuffer.allocate(30), true);
- encoder.encode(in);
- in.rewind();
-
- // Normal case:just after encode with that endOfInput is false
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
- ByteBuffer.allocate(30), false);
- encoder.encode(in);
- in.rewind();
-
- // Normal case: just after flush
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
- ByteBuffer.allocate(30), true);
- encoder.flush(ByteBuffer.allocate(10));
- encoder.encode(in);
- in.rewind();
- }
-
- // test illegal states for two encode method with endOfInput is true
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testEncodeTrueIllegalState() throws CharacterCodingException {
- CharBuffer in = CharBuffer.wrap("aaa");
- ByteBuffer out = ByteBuffer.allocate(5);
- // Normal case: just created
- encoder.encode(in, out, true);
- in.rewind();
- out.rewind();
-
- in.rewind();
- out.rewind();
-
- // Normal case: just after encode with that endOfInput is true
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
- ByteBuffer.allocate(30), true);
- encoder.encode(in, out, true);
- in.rewind();
- out.rewind();
-
- // Normal case:just after encode with that endOfInput is false
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
- ByteBuffer.allocate(30), false);
- encoder.encode(in, out, true);
- in.rewind();
- out.rewind();
-
- // Illegal state: just after flush
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
- ByteBuffer.allocate(30), true);
- encoder.flush(ByteBuffer.allocate(10));
- try {
- encoder.encode(in, out, true);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
-
- // Normal case: after canEncode
- assertSame(encoder, encoder.reset());
- encoder.canEncode("\ud906\udc00");
- encoder.encode(in, out, true);
- in.rewind();
- out.rewind();
- assertSame(encoder, encoder.reset());
- encoder.canEncode('\ud905');
- encoder.encode(in, out, true);
- }
-
- // test illegal states for two encode method with endOfInput is false
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testEncodeFalseIllegalState() throws CharacterCodingException {
- CharBuffer in = CharBuffer.wrap("aaa");
- ByteBuffer out = ByteBuffer.allocate(5);
- // Normal case: just created
- encoder.encode(in, out, false);
- in.rewind();
- out.rewind();
-
- // Illegal state: just after encode facade
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState1"));
- try {
- encoder.encode(in, out, false);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
-
- // Illegal state: just after encode with that endOfInput is true
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
- ByteBuffer.allocate(30), true);
- try {
- encoder.encode(in, out, false);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
-
- // Normal case:just after encode with that endOfInput is false
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
- ByteBuffer.allocate(30), false);
- encoder.encode(in, out, false);
- in.rewind();
- out.rewind();
-
- // Illegal state: just after flush
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
- ByteBuffer.allocate(30), true);
- encoder.flush(ByteBuffer.allocate(10));
- try {
- encoder.encode(in, out, false);
- fail("should illegal state");
- } catch (IllegalStateException e) {
- }
-
- // Normal case: after canEncode
- assertSame(encoder, encoder.reset());
- encoder.canEncode("\ud906\udc00");
- encoder.encode(in, out, false);
- in.rewind();
- out.rewind();
- assertSame(encoder, encoder.reset());
- encoder.canEncode('\ud905');
- encoder.encode(in, out, false);
- }
-
- // test illegal states for two canEncode methods
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {java.lang.CharSequence.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "reset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "flush",
- args = {java.nio.ByteBuffer.class}
- )
- })
- public void testCanEncodeIllegalState() throws CharacterCodingException {
- // Normal case: just created
- encoder.canEncode("\ud900\udc00");
- encoder.canEncode('\ud900');
-
- // Illegal state: just after encode with that endOfInput is true
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState2"),
- ByteBuffer.allocate(30), true);
- try {
- encoder.canEncode("\ud903\udc00");
- fail("should throw illegal state exception");
- } catch (IllegalStateException e) {
- }
-
- // Illegal state:just after encode with that endOfInput is false
- assertSame(encoder, encoder.reset());
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState3"),
- ByteBuffer.allocate(30), false);
- try {
- encoder.canEncode("\ud904\udc00");
- fail("should throw illegal state exception");
- } catch (IllegalStateException e) {
- }
-
- // Normal case: just after flush
- encoder.encode(CharBuffer.wrap("testCanEncodeIllegalState4"),
- ByteBuffer.allocate(30), true);
- encoder.flush(ByteBuffer.allocate(10));
- encoder.canEncode("\ud905\udc00");
- encoder.canEncode('\ud906');
-
- // Normal case: after reset again
- assertSame(encoder, encoder.reset());
- encoder.canEncode("\ud906\udc00");
- encoder.canEncode('\ud905');
- }
-
- /*
- * --------------------------------- illegal state test end
- * ---------------------------------
- */
-
- /*
- * Class under test for boolean canEncode(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canEncode",
- args = {java.lang.CharSequence.class}
- )
- public void testCanEncodeCharSequence() {
- // for non-mapped char
- assertTrue(encoder.canEncode("\uc2c0"));
- // surrogate char for unicode
- // 1st byte: d800-dbff
- // 2nd byte: dc00-dfff
- assertTrue(encoder.canEncode("\ud800"));
- // valid surrogate pair
- assertTrue(encoder.canEncode("\ud800\udc00"));
- // invalid surrogate pair
- assertTrue(encoder.canEncode("\ud800\udb00"));
- }
-
-
-
- /*
- * Class under test for ByteBuffer encode(CharBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class}
- )
- public void testEncodeCharBuffer() throws CharacterCodingException {
- // Null pointer
- try {
- encoder.encode(null);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
-
- // empty input buffer
- ByteBuffer out = encoder.encode(CharBuffer.wrap(""));
- assertEquals(out.position(), 0);
- assertByteArray(out, new byte[0]);
- // assertByteArray(out, surrogate);
-
- // normal case
- out = encoder.encode(CharBuffer.wrap(unistr));
- assertEquals(out.position(), 0);
- assertByteArray(out, addSurrogate(unibytes));
-
- // Regression test for harmony-3378
- Charset cs = Charset.forName("UTF-8");
- CharsetEncoder encoder = cs.newEncoder();
- encoder.onMalformedInput(CodingErrorAction.REPLACE);
- encoder = encoder.replaceWith(new byte[] { (byte) 0xef, (byte) 0xbf,
- (byte) 0xbd, });
- CharBuffer in = CharBuffer.wrap("\ud800");
- out = encoder.encode(in);
- assertNotNull(out);
- }
-
- private byte[] addSurrogate(byte[] expected) {
- if (surrogate.length > 0) {
- byte[] temp = new byte[surrogate.length + expected.length];
- System.arraycopy(surrogate, 0, temp, 0, surrogate.length);
- System.arraycopy(expected, 0, temp, surrogate.length,
- expected.length);
- expected = temp;
- }
- return expected;
- }
-
- /**
- * @return
- */
- protected byte[] getEmptyByteArray() {
- return new byte[0];
- }
-
- CharBuffer getMalformedCharBuffer() {
- return CharBuffer.wrap("malform buffer");
- }
-
- CharBuffer getUnmapCharBuffer() {
- return CharBuffer.wrap("unmap buffer");
- }
-
- CharBuffer getExceptionCharBuffer() {
- return CharBuffer.wrap("runtime buffer");
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class}
- )
- public void testEncodeCharBufferException() throws CharacterCodingException {
- ByteBuffer out;
- CharBuffer in;
- // MalformedException:
- in = getMalformedCharBuffer();
- encoder.onMalformedInput(CodingErrorAction.REPORT);
- encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- if (in != null) {
- try {
- // regression test for Harmony-1379
- encoder.encode(in);
- fail("should throw MalformedInputException");
- } catch (MalformedInputException e) {
- }
-
- encoder.reset();
- in.rewind();
- encoder.onMalformedInput(CodingErrorAction.IGNORE);
- out = encoder.encode(in);
- assertByteArray(out, addSurrogate(unibytes));
-
- encoder.reset();
- in.rewind();
- encoder.onMalformedInput(CodingErrorAction.REPLACE);
- out = encoder.encode(in);
- assertByteArray(out, addSurrogate(unibytesWithRep));
- }
-
- // Unmapped Exception:
- in = getUnmapCharBuffer();
- encoder.onMalformedInput(CodingErrorAction.REPORT);
- encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- if (in != null) {
- encoder.reset();
- try {
- encoder.encode(in);
- fail("should throw UnmappableCharacterException");
- } catch (UnmappableCharacterException e) {
- }
-
- encoder.reset();
- in.rewind();
- encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
- out = encoder.encode(in);
- assertByteArray(out, unibytes);
-
- encoder.reset();
- in.rewind();
- encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
- out = encoder.encode(in);
- assertByteArray(out, unibytesWithRep);
- }
-
- // RuntimeException
- try {
- encoder.encode(getExceptionCharBuffer());
- fail("should throw runtime exception");
- } catch (RuntimeException e) {
- }
- }
-
- /*
- * utility method, extract given bytebuffer to a string and compare with
- * give string
- */
- void assertByteArray(ByteBuffer out, byte[] expected) {
- out = out.duplicate();
- if (out.position() != 0) {
- out.flip();
- }
- byte[] ba = new byte[out.limit() - out.position()];
- out.get(ba);
- // byte[] ba = out.array();
- assertTrue(Arrays.equals(ba, expected));
- }
-
- /*
- * Class under test for CoderResult encode(CharBuffer, ByteBuffer, boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- )
- public void testEncodeCharBufferByteBufferboolean()
- throws CharacterCodingException {
- ByteBuffer out = ByteBuffer.allocate(200);
- CharBuffer in = CharBuffer.wrap(unistr);
- // Null pointer
- try {
- encoder.encode(null, out, true);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
- try {
- encoder.encode(in, null, true);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
-
- // normal case, one complete operation
- assertSame(encoder, encoder.reset());
- in.rewind();
- out.rewind();
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
- assertEquals(out.limit(), 200);
- assertTrue(out.position() > 0);
- assertTrue(out.remaining() > 0);
- assertEquals(out.capacity(), 200);
- assertByteArray(out, addSurrogate(unibytes));
- in.rewind();
-
- encoder.flush(out);
-
- // normal case, one complete operation, but call twice, first time set
- // endOfInput to false
- assertSame(encoder, encoder.reset());
- in.rewind();
- out = ByteBuffer.allocate(200);
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false));
- assertEquals(out.limit(), 200);
- assertTrue(out.position() > 0);
- assertTrue(out.remaining() > 0);
- assertEquals(out.capacity(), 200);
- assertByteArray(out, addSurrogate(unibytes));
-
- in.rewind();
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false));
- in.rewind();
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
- assertEquals(out.limit(), 200);
- assertTrue(out.position() > 0);
- assertTrue(out.remaining() > 0);
- assertEquals(out.capacity(), 200);
-
- assertByteArray(out, addSurrogate(duplicateByteArray(unibytes, 3)));
-
- // overflow
- out = ByteBuffer.allocate(4);
- assertSame(encoder, encoder.reset());
- in.rewind();
- out.rewind();
- assertSame(CoderResult.OVERFLOW, encoder.encode(in, out, true));
- assertEquals(out.limit(), 4);
- assertEquals(out.position(), 4);
- assertEquals(out.remaining(), 0);
- assertEquals(out.capacity(), 4);
- ByteBuffer temp = ByteBuffer.allocate(200);
- out.flip();
- temp.put(out);
- out = temp;
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
- assertEquals(out.limit(), 200);
- assertTrue(out.position() > 0);
- assertTrue(out.remaining() > 0);
- assertEquals(out.capacity(), 200);
- assertByteArray(out, addSurrogate(unibytes));
-
- assertSame(encoder, encoder.reset());
- in.rewind();
- out = ByteBuffer.allocate(4);
- assertSame(CoderResult.OVERFLOW, encoder.encode(in, out, false));
- assertEquals(out.limit(), 4);
- assertEquals(out.position(), 4);
- assertEquals(out.remaining(), 0);
- assertEquals(out.capacity(), 4);
- temp = ByteBuffer.allocate(200);
- out.flip();
- temp.put(out);
- out = temp;
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, false));
- assertEquals(out.limit(), 200);
- assertTrue(out.position() > 0);
- assertTrue(out.remaining() > 0);
- assertEquals(out.capacity(), 200);
- assertByteArray(out, addSurrogate(unibytes));
- }
-
- void printByteBuffer(ByteBuffer buffer) {
- System.out.println("print buffer");
- if (buffer.position() != 0) {
- buffer.flip();
- }
- byte[] ba = buffer.array();
- for (int i = 0; i < ba.length; i++) {
- System.out.println(Integer.toHexString(ba[i]));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- )
- public void testEncodeCharBufferByteBufferbooleanExceptionFalse()
- throws CharacterCodingException {
- implTestEncodeCharBufferByteBufferbooleanException(false);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- )
- public void testEncodeCharBufferByteBufferbooleanExceptionTrue()
- throws CharacterCodingException {
- implTestEncodeCharBufferByteBufferbooleanException(true);
- }
-
- private byte[] duplicateByteArray(byte[] ba, int times) {
- byte[] result = new byte[ba.length * times];
- for (int i = 0; i < times; i++) {
- System.arraycopy(ba, 0, result, i * ba.length, ba.length);
- }
- return result;
- }
-
- protected void implTestEncodeCharBufferByteBufferbooleanException(
- boolean endOfInput) throws CharacterCodingException {
- ByteBuffer out = ByteBuffer.allocate(100);
-
- // MalformedException:
- CharBuffer in = getMalformedCharBuffer();
- encoder.onMalformedInput(CodingErrorAction.REPORT);
- encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- if (in != null) {
- encoder.reset();
- CoderResult r = encoder.encode(in, out, endOfInput);
- assertTrue(r.isMalformed());
-
- encoder.reset();
- out.clear();
- in.rewind();
- encoder.onMalformedInput(CodingErrorAction.IGNORE);
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
- endOfInput));
- assertCodingErrorAction(endOfInput, out, in, unibytes);
-
- encoder.reset();
- out.clear();
- in.rewind();
- encoder.onMalformedInput(CodingErrorAction.REPLACE);
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
- endOfInput));
- assertCodingErrorAction(endOfInput, out, in, unibytesWithRep);
- } else {
- // System.out.println("Cannot find malformed char buffer for "
- // + cs.name());
- }
-
- // Unmapped Exception:
- in = getUnmapCharBuffer();
- encoder.onMalformedInput(CodingErrorAction.REPORT);
- encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
- if (in != null) {
- encoder.reset();
- out.clear();
- assertTrue(encoder.encode(in, out, endOfInput).isUnmappable());
-
- encoder.reset();
- out.clear();
- in.rewind();
- encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
- endOfInput));
- assertCodingErrorAction(endOfInput, out, in, unibytes);
-
- encoder.reset();
- out.clear();
- in.rewind();
- encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
- endOfInput));
- assertCodingErrorAction(endOfInput, out, in, unibytesWithRep);
- } else {
- // System.out.println("Cannot find unmapped char buffer for "
- // + cs.name());
- }
-
- // RuntimeException
- try {
- encoder.encode(getExceptionCharBuffer());
- fail("should throw runtime exception");
- } catch (RuntimeException e) {
- }
- }
-
- private void assertCodingErrorAction(boolean endOfInput, ByteBuffer out,
- CharBuffer in, byte[] expect) {
- if (endOfInput) {
- assertByteArray(out, addSurrogate(expect));
- } else {
- in.rewind();
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out,
- endOfInput));
- in.rewind();
- assertSame(CoderResult.UNDERFLOW, encoder.encode(in, out, true));
- assertByteArray(out, addSurrogate(duplicateByteArray(expect, 3)));
- }
- }
-
- /*
- * Class under test for CoderResult flush(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "encode",
- args = {java.nio.CharBuffer.class, java.nio.ByteBuffer.class, boolean.class}
- )
- public void testFlush() throws CharacterCodingException {
- ByteBuffer out = ByteBuffer.allocate(6);
- CharBuffer in = CharBuffer.wrap("aaa");
- assertEquals(in.remaining(), 3);
-
- // by encode facade, so that internal state will be wrong
- encoder.encode(CharBuffer.wrap("testFlush"), ByteBuffer.allocate(20),
- true);
- assertSame(CoderResult.UNDERFLOW, encoder
- .flush(ByteBuffer.allocate(50)));
- }
-
- /*
- * test isLegalReplacement(byte[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isLegalReplacement",
- args = {byte[].class}
- )
- public void testIsLegalReplacement() {
- try {
- encoder.isLegalReplacement(null);
- fail("should throw null pointer exception");
- } catch (NullPointerException e) {
- }
- assertTrue(encoder.isLegalReplacement(specifiedReplacement));
-
- assertTrue(encoder.isLegalReplacement(new byte[200]));
- byte[] ba = getIllegalByteArray();
- if (ba != null) {
- assertFalse(encoder.isLegalReplacement(ba));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isLegalReplacement",
- args = {byte[].class}
- )
- public void testIsLegalReplacementEmptyArray() {
- // ISO, ASC, GB, UTF8 encoder will throw exception in RI
- // others will pass
- // try {
- assertTrue(encoder.isLegalReplacement(new byte[0]));
- // fail("should throw ArrayIndexOutOfBoundsException");
- // } catch (ArrayIndexOutOfBoundsException e) {
- // }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onMalformedInput",
- args = {java.nio.charset.CodingErrorAction.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "malformedInputAction",
- args = {}
- )
- })
- public void testOnMalformedInput() {
- assertSame(CodingErrorAction.REPORT, encoder.malformedInputAction());
- try {
- encoder.onMalformedInput(null);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- encoder.onMalformedInput(CodingErrorAction.IGNORE);
- assertSame(CodingErrorAction.IGNORE, encoder.malformedInputAction());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "onUnmappableCharacter",
- args = {java.nio.charset.CodingErrorAction.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "unmappableCharacterAction",
- args = {}
- )
- })
- public void testOnUnmappableCharacter() {
- assertSame(CodingErrorAction.REPORT, encoder
- .unmappableCharacterAction());
- try {
- encoder.onUnmappableCharacter(null);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
- assertSame(CodingErrorAction.IGNORE, encoder
- .unmappableCharacterAction());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "replaceWith",
- args = {byte[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "replacement",
- args = {}
- )
- })
- public void testReplacement() {
- try {
- encoder.replaceWith(null);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- try {
- encoder.replaceWith(new byte[0]);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- try {
- encoder.replaceWith(new byte[100]);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
-
- byte[] nr = getLegalByteArray();
- assertSame(encoder, encoder.replaceWith(nr));
- assertSame(nr, encoder.replacement());
-
- nr = getIllegalByteArray();
- try {
- encoder.replaceWith(new byte[100]);
- fail("should throw null pointer exception");
- } catch (IllegalArgumentException e) {
- }
- }
-
- protected byte[] getLegalByteArray() {
- return new byte[] { 'a' };
- }
-
- protected byte[] getIllegalByteArray() {
- return new byte[155];
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/AllTests.java b/luni/src/test/java/tests/api/java/nio/charset/AllTests.java
deleted file mode 100644
index d965612..0000000
--- a/luni/src/test/java/tests/api/java/nio/charset/AllTests.java
+++ /dev/null
@@ -1,85 +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.
- */
-
-package tests.api.java.nio.charset;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All tests for package tests.api.java.nio.charset;");
-
- suite.addTestSuite(Charset_MultiByte_EUC_KR.class);
- suite.addTestSuite(Charset_MultiByte_UTF_8.class);
- suite.addTestSuite(Charset_MultiByte_UTF_16BE.class);
- suite.addTestSuite(Charset_MultiByte_UTF_16LE.class);
-
-// suite.addTestSuite(Charset_MultiByte_UTF_16.class);
- suite.addTestSuite(Charset_MultiByte_UTF_16_Android.class);
-// suite.addTestSuite(Charset_MultiByte_EUC_JP.class);
- suite.addTestSuite(Charset_MultiByte_EUC_JP_Android.class);
- suite.addTestSuite(Charset_MultiByte_ISO_2022_JP.class); // IS HIDDENLY MAPPED TO ASCII OR WHAT?!?
-// suite.addTestSuite(Charset_MultiByte_ISO_2022_JP_Android.class); // IS HIDDENLY MAPPED TO ASCII OR WHAT?!?
-
-// suite.addTestSuite(Charset_MultiByte_Big5.class);
- suite.addTestSuite(Charset_MultiByte_Big5_Android.class);
- suite.addTestSuite(Charset_MultiByte_x_windows_950.class); // IS MAPPED TO Big5!!!
-// suite.addTestSuite(Charset_MultiByte_x_windows_950_Android.class); // IS MAPPED TO Big5!!!
-
-// suite.addTestSuite(Charset_MultiByte_GBK.class);
- suite.addTestSuite(Charset_MultiByte_GBK_Android.class);
- suite.addTestSuite(Charset_MultiByte_GB2312.class); // IS HIDDENLY MAPPED TO ASCII OR WHAT?!?
-// suite.addTestSuite(Charset_MultiByte_GB2312_Android.class); // IS MAPPED TO GBK!!!
-
- suite.addTestSuite(Charset_SingleByte_US_ASCII.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_1.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_2.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_3.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_4.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_5.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_6.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_7.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_8.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_9.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_11.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_13.class);
- suite.addTestSuite(Charset_SingleByte_ISO_8859_15.class);
- suite.addTestSuite(Charset_SingleByte_IBM864.class);
- suite.addTestSuite(Charset_SingleByte_x_IBM874.class);
- suite.addTestSuite(Charset_SingleByte_windows_1250.class);
- suite.addTestSuite(Charset_SingleByte_windows_1251.class);
- suite.addTestSuite(Charset_SingleByte_windows_1252.class);
- suite.addTestSuite(Charset_SingleByte_windows_1253.class);
- suite.addTestSuite(Charset_SingleByte_windows_1254.class);
- suite.addTestSuite(Charset_SingleByte_windows_1255.class);
- suite.addTestSuite(Charset_SingleByte_windows_1256.class);
- suite.addTestSuite(Charset_SingleByte_windows_1257.class);
- suite.addTestSuite(Charset_SingleByte_windows_1258.class);
- suite.addTestSuite(Charset_SingleByte_KOI8_R.class);
-
- // NOT SUPPORTED BY RI:
- suite.addTestSuite(Charset_ISO_8859_10.class);
- suite.addTestSuite(Charset_ISO_8859_14.class);
- suite.addTestSuite(Charset_ISO_8859_16.class);
- suite.addTestSuite(Charset_macintosh.class);
- suite.addTestSuite(Charset_GSM0338.class);
-
- suite.addTestSuite(CharsetEncoderDecoderBufferTest.class);
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_.java b/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_.java
deleted file mode 100644
index fc002f4..0000000
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_MultiByte_.java
+++ /dev/null
@@ -1,52 +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.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_MultiByte_ extends Charset_AbstractTest {
-
- @Override
- protected void setUp() throws Exception {
- charsetName = "";
-
- testChars = theseChars(new int[]{
-
- });
-
- testBytes = theseBytes(new int[]{
-
- });
-
-//testChars = new char[0];
-//testBytes = new byte[0];
-
- super.setUp();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_.java b/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_.java
deleted file mode 100644
index f4e82d8..0000000
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_SingleByte_.java
+++ /dev/null
@@ -1,41 +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.nio.charset;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CodingErrorAction;
-
-public class Charset_SingleByte_ extends Charset_SingleByteAbstractTest {
-
- protected void setUp() throws Exception {
- charsetName = "";
- allChars = theseChars(new int[]{
- });
- super.setUp();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/nio/charset/Charset_TestGenerator_Res.java b/luni/src/test/java/tests/api/java/nio/charset/Charset_TestGenerator_Res.java
deleted file mode 100644
index 1974a62..0000000
--- a/luni/src/test/java/tests/api/java/nio/charset/Charset_TestGenerator_Res.java
+++ /dev/null
@@ -1,2672 +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.nio.charset;
-
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-
-/**
- * Super class for concrete charset test suites.
- */
-public class Charset_TestGenerator_Res {
-
- Charset charset;
- CharsetDecoder decoder;
- CharsetEncoder encoder;
-
- // List of encodings currently required for Android.
- static String[] charsetNames = new String[] {
- // Encoding required by Java specification.
- "US-ASCII",
- "UTF-8",
- "UTF-16",
- "UTF-16BE",
- "UTF-16LE",
- "ISO-8859-1",
-
- // Additional encodings included in standard ICU
- "ISO-8859-2",
- "ISO-8859-3",
- "ISO-8859-4",
- "ISO-8859-5",
- "ISO-8859-6",
- "ISO-8859-7",
- "ISO-8859-8",
-//jdk NoSup "ISO-8859-8-I",
- "ISO-8859-9",
-//jdk NoSup "ISO-8859-10",
- "ISO-8859-11", //jdk x-...
- "ISO-8859-13",
-//jdk NoSup "ISO-8859-14",
- "ISO-8859-15",
-//jdk NoSup "ISO-8859-16",
- "ISO-2022-JP",
- "Windows-950", //jdk x-...
- "Windows-1250", //jdk x-...
- "Windows-1251",
- "Windows-1252",
- "Windows-1253",
- "Windows-1254",
- "Windows-1255",
- "Windows-1256",
- "Windows-1257",
- "Windows-1258",
- "Big5",
- "CP864",
- "CP874",
- "EUC-CN",
- "EUC-JP",
- "KOI8-R",
-//jdk NoSup "Macintosh",
- "GBK",
- "GB2312",
- "EUC-KR"};
-
- static final short[] codes = {
- 9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
- 89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 170, 181, 186, 192, 195, 198,
- 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246,
- 249, 252, 255, 258, 261, 264, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294,
- 297, 300, 303, 306, 309, 312, 315, 318, 321, 324, 327, 330, 333, 336, 339, 342,
- 345, 348, 351, 354, 357, 360, 363, 366, 369, 372, 375, 378, 381, 384, 387, 390,
- 393, 396, 399, 402, 405, 408, 411, 414, 417, 420, 423, 426, 429, 432, 435, 438,
- 441, 444, 447, 450, 453, 456, 459, 462, 465, 468, 471, 474, 477, 480, 483, 486,
- 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 528, 531, 534,
- 537, 540, 543, 546, 549, 552, 555, 558, 561, 564, 592, 595, 598, 601, 604, 607,
- 610, 613, 616, 619, 622, 625, 628, 631, 634, 637, 640, 643, 646, 649, 652, 655,
- 658, 661, 664, 667, 670, 673, 676, 679, 682, 685, 688, 691, 694, 697, 700, 703,
- 710, 713, 716, 719, 736, 739, 750, 890, 902, 905, 908, 911, 914, 917, 920, 923,
- 926, 929, 932, 935, 938, 941, 944, 947, 950, 953, 956, 959, 962, 965, 968, 971,
- 974, 977, 980, 983, 986, 989, 992, 995, 998, 1001, 1004, 1007, 1010, 1013, 1016, 1019,
- 1024, 1027, 1060, 1093, 1126, 1162, 1195, 1228, 1261, 1294, 1329, 1362, 1395, 1488, 1521, 1569,
- 1602, 1635, 1668, 1701, 1734, 1774, 1808, 1869, 1920, 1953, 2308, 2341, 2384, 2437, 2470, 2524,
- 2565, 2598, 2649, 2693, 2726, 2768, 2821, 2854, 2908, 2947, 2980, 3047, 3080, 3114, 3168, 3205,
- 3238, 3294, 3333, 3366, 3424, 3461, 3494, 3585, 3618, 3651, 3713, 3746, 3779, 3840, 3873, 3906,
- 3939, 3976, 4096, 4129, 4162, 4256, 4289, 4322, 4355, 4388, 4421, 4454, 4487, 4520, 4553, 4586,
- 4619, 4652, 4685, 4718, 4752, 4786, 4819, 4852, 4885, 4918, 4951, 5024, 5057, 5090, 5123, 5156,
- 5189, 5222, 5255, 5288, 5321, 5354, 5387, 5420, 5453, 5486, 5519, 5552, 5585, 5618, 5651, 5684,
- 5717, 5750, 5783, 5816, 5849, 5888, 5921, 5954, 5987, 6020, 6053, 6103, 6158, 6191, 6224, 6257,
- 6290, 6400, 6470, 6503, 7424, 7457, 7490, 7523, 7680, 7713, 7746, 7779, 7812, 7845, 7878, 7911,
- 7944, 7977, 8010, 8043, 8076, 8109, 8144, 8178, 8232, 8287, 8450, 8484, 8517, 12288, 12337, 12370,
- 12403, 12436, 12469, 12502, 12535, 12568, 12601, 12634, 12667, 12704, 12784, 13312, 13345, 13378, 13411, 13444,
- 13477, 13510, 13543, 13576, 13609, 13642, 13675, 13708, 13741, 13774, 13807, 13840, 13873, 13906, 13939, 13972,
- 14005, 14038, 14071, 14104, 14137, 14170, 14203, 14236, 14269, 14302, 14335, 14368, 14401, 14434, 14467, 14500,
- 14533, 14566, 14599, 14632, 14665, 14698, 14731, 14764, 14797, 14830, 14863, 14896, 14929, 14962, 14995, 15028,
- 15061, 15094, 15127, 15160, 15193, 15226, 15259, 15292, 15325, 15358, 15391, 15424, 15457, 15490, 15523, 15556,
- 15589, 15622, 15655, 15688, 15721, 15754, 15787, 15820, 15853, 15886, 15919, 15952, 15985, 16018, 16051, 16084,
- 16117, 16150, 16183, 16216, 16249, 16282, 16315, 16348, 16381, 16414, 16447, 16480, 16513, 16546, 16579, 16612,
- 16645, 16678, 16711, 16744, 16777, 16810, 16843, 16876, 16909, 16942, 16975, 17008, 17041, 17074, 17107, 17140,
- 17173, 17206, 17239, 17272, 17305, 17338, 17371, 17404, 17437, 17470, 17503, 17536, 17569, 17602, 17635, 17668,
- 17701, 17734, 17767, 17800, 17833, 17866, 17899, 17932, 17965, 17998, 18031, 18064, 18097, 18130, 18163, 18196,
- 18229, 18262, 18295, 18328, 18361, 18394, 18427, 18460, 18493, 18526, 18559, 18592, 18625, 18658, 18691, 18724,
- 18757, 18790, 18823, 18856, 18889, 18922, 18955, 18988, 19021, 19054, 19087, 19120, 19153, 19186, 19219, 19252,
- 19285, 19318, 19351, 19384, 19417, 19450, 19483, 19516, 19549, 19582, 19615, 19648, 19681, 19714, 19747, 19780,
- 19813, 19846, 19879, 19968, 20001, 20034, 20067, 20100, 20133, 20166, 20199, 20232, 20265, 20298, 20331, 20364,
- 20397, 20430, 20463, 20496, 20529, 20562, 20595, 20628, 20661, 20694, 20727, 20760, 20793, 20826, 20859, 20892,
- 20925, 20958, 20991, 21024, 21057, 21090, 21123, 21156, 21189, 21222, 21255, 21288, 21321, 21354, 21387, 21420,
- 21453, 21486, 21519, 21552, 21585, 21618, 21651, 21684, 21717, 21750, 21783, 21816, 21849, 21882, 21915, 21948,
- 21981, 22014, 22047, 22080, 22113, 22146, 22179, 22212, 22245, 22278, 22311, 22344, 22377, 22410, 22443, 22476,
- 22509, 22542, 22575, 22608, 22641, 22674, 22707, 22740, 22773, 22806, 22839, 22872, 22905, 22938, 22971, 23004,
- 23037, 23070, 23103, 23136, 23169, 23202, 23235, 23268, 23301, 23334, 23367, 23400, 23433, 23466, 23499, 23532,
- 23565, 23598, 23631, 23664, 23697, 23730, 23763, 23796, 23829, 23862, 23895, 23928, 23961, 23994, 24027, 24060,
- 24093, 24126, 24159, 24192, 24225, 24258, 24291, 24324, 24357, 24390, 24423, 24456, 24489, 24522, 24555, 24588,
- 24621, 24654, 24687, 24720, 24753, 24786, 24819, 24852, 24885, 24918, 24951, 24984, 25017, 25050, 25083, 25116,
- 25149, 25182, 25215, 25248, 25281, 25314, 25347, 25380, 25413, 25446, 25479, 25512, 25545, 25578, 25611, 25644,
- 25677, 25710, 25743, 25776, 25809, 25842, 25875, 25908, 25941, 25974, 26007, 26040, 26073, 26106, 26139, 26172,
- 26205, 26238, 26271, 26304, 26337, 26370, 26403, 26436, 26469, 26502, 26535, 26568, 26601, 26634, 26667, 26700,
- 26733, 26766, 26799, 26832, 26865, 26898, 26931, 26964, 26997, 27030, 27063, 27096, 27129, 27162, 27195, 27228,
- 27261, 27294, 27327, 27360, 27393, 27426, 27459, 27492, 27525, 27558, 27591, 27624, 27657, 27690, 27723, 27756,
- 27789, 27822, 27855, 27888, 27921, 27954, 27987, 28020, 28053, 28086, 28119, 28152, 28185, 28218, 28251, 28284,
- 28317, 28350, 28383, 28416, 28449, 28482, 28515, 28548, 28581, 28614, 28647, 28680, 28713, 28746, 28779, 28812,
- 28845, 28878, 28911, 28944, 28977, 29010, 29043, 29076, 29109, 29142, 29175, 29208, 29241, 29274, 29307, 29340,
- 29373, 29406, 29439, 29472, 29505, 29538, 29571, 29604, 29637, 29670, 29703, 29736, 29769, 29802, 29835, 29868,
- 29901, 29934, 29967, 30000, 30033, 30066, 30099, 30132, 30165, 30198, 30231, 30264, 30297, 30330, 30363, 30396,
- 30429, 30462, 30495, 30528, 30561, 30594, 30627, 30660, 30693, 30726, 30759, 30792, 30825, 30858, 30891, 30924,
- 30957, 30990, 31023, 31056, 31089, 31122, 31155, 31188, 31221, 31254, 31287, 31320, 31353, 31386, 31419, 31452,
- 31485, 31518, 31551, 31584, 31617, 31650, 31683, 31716, 31749, 31782, 31815, 31848, 31881, 31914, 31947, 31980,
- 32013, 32046, 32079, 32112, 32145, 32178, 32211, 32244, 32277, 32310, 32343, 32376, 32409, 32442, 32475, 32508,
- 32541, 32574, 32607, 32640, 32673, 32706, 32739
- };
- static final char[] chars = new char[codes.length]; // Is filled with contents of codes.
-
-// {
-// System.out.println("TEST");
-//// System.arraycopy(codes, 0, chars, 0, codes.length); // Na super! Der Compiler nimmt's, aber Runtime gibt's ArrayStoreException.
-// for (int i = 0; i < codes.length; i++) chars[i] = (char) codes[i];
-// }
-
-
-
-/*
-US-ASCII
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
- */
-
-/*
-UTF-8
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -62, -86, -62, -75, -62, -70,
--61, -128, -61, -125, -61, -122, -61, -119, -61, -116, -61, -113, -61, -110, -61, -107,
--61, -104, -61, -101, -61, -98, -61, -95, -61, -92, -61, -89, -61, -86, -61, -83,
--61, -80, -61, -77, -61, -74, -61, -71, -61, -68, -61, -65, -60, -126, -60, -123,
--60, -120, -60, -117, -60, -114, -60, -111, -60, -108, -60, -105, -60, -102, -60, -99,
--60, -96, -60, -93, -60, -90, -60, -87, -60, -84, -60, -81, -60, -78, -60, -75,
--60, -72, -60, -69, -60, -66, -59, -127, -59, -124, -59, -121, -59, -118, -59, -115,
--59, -112, -59, -109, -59, -106, -59, -103, -59, -100, -59, -97, -59, -94, -59, -91,
--59, -88, -59, -85, -59, -82, -59, -79, -59, -76, -59, -73, -59, -70, -59, -67,
--58, -128, -58, -125, -58, -122, -58, -119, -58, -116, -58, -113, -58, -110, -58, -107,
--58, -104, -58, -101, -58, -98, -58, -95, -58, -92, -58, -89, -58, -86, -58, -83,
--58, -80, -58, -77, -58, -74, -58, -71, -58, -68, -58, -65, -57, -126, -57, -123,
--57, -120, -57, -117, -57, -114, -57, -111, -57, -108, -57, -105, -57, -102, -57, -99,
--57, -96, -57, -93, -57, -90, -57, -87, -57, -84, -57, -81, -57, -78, -57, -75,
--57, -72, -57, -69, -57, -66, -56, -127, -56, -124, -56, -121, -56, -118, -56, -115,
--56, -112, -56, -109, -56, -106, -56, -103, -56, -100, -56, -97, -56, -94, -56, -91,
--56, -88, -56, -85, -56, -82, -56, -79, -56, -76, -55, -112, -55, -109, -55, -106,
--55, -103, -55, -100, -55, -97, -55, -94, -55, -91, -55, -88, -55, -85, -55, -82,
--55, -79, -55, -76, -55, -73, -55, -70, -55, -67, -54, -128, -54, -125, -54, -122,
--54, -119, -54, -116, -54, -113, -54, -110, -54, -107, -54, -104, -54, -101, -54, -98,
--54, -95, -54, -92, -54, -89, -54, -86, -54, -83, -54, -80, -54, -77, -54, -74,
--54, -71, -54, -68, -54, -65, -53, -122, -53, -119, -53, -116, -53, -113, -53, -96,
--53, -93, -53, -82, -51, -70, -50, -122, -50, -119, -50, -116, -50, -113, -50, -110,
--50, -107, -50, -104, -50, -101, -50, -98, -50, -95, -50, -92, -50, -89, -50, -86,
--50, -83, -50, -80, -50, -77, -50, -74, -50, -71, -50, -68, -50, -65, -49, -126,
--49, -123, -49, -120, -49, -117, -49, -114, -49, -111, -49, -108, -49, -105, -49, -102,
--49, -99, -49, -96, -49, -93, -49, -90, -49, -87, -49, -84, -49, -81, -49, -78,
--49, -75, -49, -72, -49, -69, -48, -128, -48, -125, -48, -92, -47, -123, -47, -90,
--46, -118, -46, -85, -45, -116, -45, -83, -44, -114, -44, -79, -43, -110, -43, -77,
--41, -112, -41, -79, -40, -95, -39, -126, -39, -93, -38, -124, -38, -91, -37, -122,
--37, -82, -36, -112, -35, -115, -34, -128, -34, -95, -32, -92, -124, -32, -92, -91,
--32, -91, -112, -32, -90, -123, -32, -90, -90, -32, -89, -100, -32, -88, -123, -32,
--88, -90, -32, -87, -103, -32, -86, -123, -32, -86, -90, -32, -85, -112, -32, -84,
--123, -32, -84, -90, -32, -83, -100, -32, -82, -125, -32, -82, -92, -32, -81, -89,
--32, -80, -120, -32, -80, -86, -32, -79, -96, -32, -78, -123, -32, -78, -90, -32,
--77, -98, -32, -76, -123, -32, -76, -90, -32, -75, -96, -32, -74, -123, -32, -74,
--90, -32, -72, -127, -32, -72, -94, -32, -71, -125, -32, -70, -127, -32, -70, -94,
--32, -69, -125, -32, -68, -128, -32, -68, -95, -32, -67, -126, -32, -67, -93, -32,
--66, -120, -31, -128, -128, -31, -128, -95, -31, -127, -126, -31, -126, -96, -31, -125,
--127, -31, -125, -94, -31, -124, -125, -31, -124, -92, -31, -123, -123, -31, -123, -90,
--31, -122, -121, -31, -122, -88, -31, -121, -119, -31, -121, -86, -31, -120, -117, -31,
--120, -84, -31, -119, -115, -31, -119, -82, -31, -118, -112, -31, -118, -78, -31, -117,
--109, -31, -117, -76, -31, -116, -107, -31, -116, -74, -31, -115, -105, -31, -114, -96,
--31, -113, -127, -31, -113, -94, -31, -112, -125, -31, -112, -92, -31, -111, -123, -31,
--111, -90, -31, -110, -121, -31, -110, -88, -31, -109, -119, -31, -109, -86, -31, -108,
--117, -31, -108, -84, -31, -107, -115, -31, -107, -82, -31, -106, -113, -31, -106, -80,
--31, -105, -111, -31, -105, -78, -31, -104, -109, -31, -104, -76, -31, -103, -107, -31,
--103, -74, -31, -102, -105, -31, -102, -72, -31, -101, -103, -31, -100, -128, -31, -100,
--95, -31, -99, -126, -31, -99, -93, -31, -98, -124, -31, -98, -91, -31, -97, -105,
--31, -96, -114, -31, -96, -81, -31, -95, -112, -31, -95, -79, -31, -94, -110, -31,
--92, -128, -31, -91, -122, -31, -91, -89, -31, -76, -128, -31, -76, -95, -31, -75,
--126, -31, -75, -93, -31, -72, -128, -31, -72, -95, -31, -71, -126, -31, -71, -93,
--31, -70, -124, -31, -70, -91, -31, -69, -122, -31, -69, -89, -31, -68, -120, -31,
--68, -87, -31, -67, -118, -31, -67, -85, -31, -66, -116, -31, -66, -83, -31, -65,
--112, -31, -65, -78, -30, -128, -88, -30, -127, -97, -30, -124, -126, -30, -124, -92,
--30, -123, -123, -29, -128, -128, -29, -128, -79, -29, -127, -110, -29, -127, -77, -29,
--126, -108, -29, -126, -75, -29, -125, -106, -29, -125, -73, -29, -124, -104, -29, -124,
--71, -29, -123, -102, -29, -123, -69, -29, -122, -96, -29, -121, -80, -29, -112, -128,
--29, -112, -95, -29, -111, -126, -29, -111, -93, -29, -110, -124, -29, -110, -91, -29,
--109, -122, -29, -109, -89, -29, -108, -120, -29, -108, -87, -29, -107, -118, -29, -107,
--85, -29, -106, -116, -29, -106, -83, -29, -105, -114, -29, -105, -81, -29, -104, -112,
--29, -104, -79, -29, -103, -110, -29, -103, -77, -29, -102, -108, -29, -102, -75, -29,
--101, -106, -29, -101, -73, -29, -100, -104, -29, -100, -71, -29, -99, -102, -29, -99,
--69, -29, -98, -100, -29, -98, -67, -29, -97, -98, -29, -97, -65, -29, -96, -96,
--29, -95, -127, -29, -95, -94, -29, -94, -125, -29, -94, -92, -29, -93, -123, -29,
--93, -90, -29, -92, -121, -29, -92, -88, -29, -91, -119, -29, -91, -86, -29, -90,
--117, -29, -90, -84, -29, -89, -115, -29, -89, -82, -29, -88, -113, -29, -88, -80,
--29, -87, -111, -29, -87, -78, -29, -86, -109, -29, -86, -76, -29, -85, -107, -29,
--85, -74, -29, -84, -105, -29, -84, -72, -29, -83, -103, -29, -83, -70, -29, -82,
--101, -29, -82, -68, -29, -81, -99, -29, -81, -66, -29, -80, -97, -29, -79, -128,
--29, -79, -95, -29, -78, -126, -29, -78, -93, -29, -77, -124, -29, -77, -91, -29,
--76, -122, -29, -76, -89, -29, -75, -120, -29, -75, -87, -29, -74, -118, -29, -74,
--85, -29, -73, -116, -29, -73, -83, -29, -72, -114, -29, -72, -81, -29, -71, -112,
--29, -71, -79, -29, -70, -110, -29, -70, -77, -29, -69, -108, -29, -69, -75, -29,
--68, -106, -29, -68, -73, -29, -67, -104, -29, -67, -71, -29, -66, -102, -29, -66,
--69, -29, -65, -100, -29, -65, -67, -28, -128, -98, -28, -128, -65, -28, -127, -96,
--28, -126, -127, -28, -126, -94, -28, -125, -125, -28, -125, -92, -28, -124, -123, -28,
--124, -90, -28, -123, -121, -28, -123, -88, -28, -122, -119, -28, -122, -86, -28, -121,
--117, -28, -121, -84, -28, -120, -115, -28, -120, -82, -28, -119, -113, -28, -119, -80,
--28, -118, -111, -28, -118, -78, -28, -117, -109, -28, -117, -76, -28, -116, -107, -28,
--116, -74, -28, -115, -105, -28, -115, -72, -28, -114, -103, -28, -114, -70, -28, -113,
--101, -28, -113, -68, -28, -112, -99, -28, -112, -66, -28, -111, -97, -28, -110, -128,
--28, -110, -95, -28, -109, -126, -28, -109, -93, -28, -108, -124, -28, -108, -91, -28,
--107, -122, -28, -107, -89, -28, -106, -120, -28, -106, -87, -28, -105, -118, -28, -105,
--85, -28, -104, -116, -28, -104, -83, -28, -103, -114, -28, -103, -81, -28, -102, -112,
--28, -102, -79, -28, -101, -110, -28, -101, -77, -28, -100, -108, -28, -100, -75, -28,
--99, -106, -28, -99, -73, -28, -98, -104, -28, -98, -71, -28, -97, -102, -28, -97,
--69, -28, -96, -100, -28, -96, -67, -28, -95, -98, -28, -95, -65, -28, -94, -96,
--28, -93, -127, -28, -93, -94, -28, -92, -125, -28, -92, -92, -28, -91, -123, -28,
--91, -90, -28, -90, -121, -28, -90, -88, -28, -89, -119, -28, -89, -86, -28, -88,
--117, -28, -88, -84, -28, -87, -115, -28, -87, -82, -28, -86, -113, -28, -86, -80,
--28, -85, -111, -28, -85, -78, -28, -84, -109, -28, -84, -76, -28, -83, -107, -28,
--83, -74, -28, -82, -105, -28, -82, -72, -28, -81, -103, -28, -81, -70, -28, -80,
--101, -28, -80, -68, -28, -79, -99, -28, -79, -66, -28, -78, -97, -28, -77, -128,
--28, -77, -95, -28, -76, -126, -28, -76, -93, -28, -75, -124, -28, -75, -91, -28,
--74, -122, -28, -74, -89, -28, -72, -128, -28, -72, -95, -28, -71, -126, -28, -71,
--93, -28, -70, -124, -28, -70, -91, -28, -69, -122, -28, -69, -89, -28, -68, -120,
--28, -68, -87, -28, -67, -118, -28, -67, -85, -28, -66, -116, -28, -66, -83, -28,
--65, -114, -28, -65, -81, -27, -128, -112, -27, -128, -79, -27, -127, -110, -27, -127,
--77, -27, -126, -108, -27, -126, -75, -27, -125, -106, -27, -125, -73, -27, -124, -104,
--27, -124, -71, -27, -123, -102, -27, -123, -69, -27, -122, -100, -27, -122, -67, -27,
--121, -98, -27, -121, -65, -27, -120, -96, -27, -119, -127, -27, -119, -94, -27, -118,
--125, -27, -118, -92, -27, -117, -123, -27, -117, -90, -27, -116, -121, -27, -116, -88,
--27, -115, -119, -27, -115, -86, -27, -114, -117, -27, -114, -84, -27, -113, -115, -27,
--113, -82, -27, -112, -113, -27, -112, -80, -27, -111, -111, -27, -111, -78, -27, -110,
--109, -27, -110, -76, -27, -109, -107, -27, -109, -74, -27, -108, -105, -27, -108, -72,
--27, -107, -103, -27, -107, -70, -27, -106, -101, -27, -106, -68, -27, -105, -99, -27,
--105, -66, -27, -104, -97, -27, -103, -128, -27, -103, -95, -27, -102, -126, -27, -102,
--93, -27, -101, -124, -27, -101, -91, -27, -100, -122, -27, -100, -89, -27, -99, -120,
--27, -99, -87, -27, -98, -118, -27, -98, -85, -27, -97, -116, -27, -97, -83, -27,
--96, -114, -27, -96, -81, -27, -95, -112, -27, -95, -79, -27, -94, -110, -27, -94,
--77, -27, -93, -108, -27, -93, -75, -27, -92, -106, -27, -92, -73, -27, -91, -104,
--27, -91, -71, -27, -90, -102, -27, -90, -69, -27, -89, -100, -27, -89, -67, -27,
--88, -98, -27, -88, -65, -27, -87, -96, -27, -86, -127, -27, -86, -94, -27, -85,
--125, -27, -85, -92, -27, -84, -123, -27, -84, -90, -27, -83, -121, -27, -83, -88,
--27, -82, -119, -27, -82, -86, -27, -81, -117, -27, -81, -84, -27, -80, -115, -27,
--80, -82, -27, -79, -113, -27, -79, -80, -27, -78, -111, -27, -78, -78, -27, -77,
--109, -27, -77, -76, -27, -76, -107, -27, -76, -74, -27, -75, -105, -27, -75, -72,
--27, -74, -103, -27, -74, -70, -27, -73, -101, -27, -73, -68, -27, -72, -99, -27,
--72, -66, -27, -71, -97, -27, -70, -128, -27, -70, -95, -27, -69, -126, -27, -69,
--93, -27, -68, -124, -27, -68, -91, -27, -67, -122, -27, -67, -89, -27, -66, -120,
--27, -66, -87, -27, -65, -118, -27, -65, -85, -26, -128, -116, -26, -128, -83, -26,
--127, -114, -26, -127, -81, -26, -126, -112, -26, -126, -79, -26, -125, -110, -26, -125,
--77, -26, -124, -108, -26, -124, -75, -26, -123, -106, -26, -123, -73, -26, -122, -104,
--26, -122, -71, -26, -121, -102, -26, -121, -69, -26, -120, -100, -26, -120, -67, -26,
--119, -98, -26, -119, -65, -26, -118, -96, -26, -117, -127, -26, -117, -94, -26, -116,
--125, -26, -116, -92, -26, -115, -123, -26, -115, -90, -26, -114, -121, -26, -114, -88,
--26, -113, -119, -26, -113, -86, -26, -112, -117, -26, -112, -84, -26, -111, -115, -26,
--111, -82, -26, -110, -113, -26, -110, -80, -26, -109, -111, -26, -109, -78, -26, -108,
--109, -26, -108, -76, -26, -107, -107, -26, -107, -74, -26, -106, -105, -26, -106, -72,
--26, -105, -103, -26, -105, -70, -26, -104, -101, -26, -104, -68, -26, -103, -99, -26,
--103, -66, -26, -102, -97, -26, -101, -128, -26, -101, -95, -26, -100, -126, -26, -100,
--93, -26, -99, -124, -26, -99, -91, -26, -98, -122, -26, -98, -89, -26, -97, -120,
--26, -97, -87, -26, -96, -118, -26, -96, -85, -26, -95, -116, -26, -95, -83, -26,
--94, -114, -26, -94, -81, -26, -93, -112, -26, -93, -79, -26, -92, -110, -26, -92,
--77, -26, -91, -108, -26, -91, -75, -26, -90, -106, -26, -90, -73, -26, -89, -104,
--26, -89, -71, -26, -88, -102, -26, -88, -69, -26, -87, -100, -26, -87, -67, -26,
--86, -98, -26, -86, -65, -26, -85, -96, -26, -84, -127, -26, -84, -94, -26, -83,
--125, -26, -83, -92, -26, -82, -123, -26, -82, -90, -26, -81, -121, -26, -81, -88,
--26, -80, -119, -26, -80, -86, -26, -79, -117, -26, -79, -84, -26, -78, -115, -26,
--78, -82, -26, -77, -113, -26, -77, -80, -26, -76, -111, -26, -76, -78, -26, -75,
--109, -26, -75, -76, -26, -74, -107, -26, -74, -74, -26, -73, -105, -26, -73, -72,
--26, -72, -103, -26, -72, -70, -26, -71, -101, -26, -71, -68, -26, -70, -99, -26,
--70, -66, -26, -69, -97, -26, -68, -128, -26, -68, -95, -26, -67, -126, -26, -67,
--93, -26, -66, -124, -26, -66, -91, -26, -65, -122, -26, -65, -89, -25, -128, -120,
--25, -128, -87, -25, -127, -118, -25, -127, -85, -25, -126, -116, -25, -126, -83, -25,
--125, -114, -25, -125, -81, -25, -124, -112, -25, -124, -79, -25, -123, -110, -25, -123,
--77, -25, -122, -108, -25, -122, -75, -25, -121, -106, -25, -121, -73, -25, -120, -104,
--25, -120, -71, -25, -119, -102, -25, -119, -69, -25, -118, -100, -25, -118, -67, -25,
--117, -98, -25, -117, -65, -25, -116, -96, -25, -115, -127, -25, -115, -94, -25, -114,
--125, -25, -114, -92, -25, -113, -123, -25, -113, -90, -25, -112, -121, -25, -112, -88,
--25, -111, -119, -25, -111, -86, -25, -110, -117, -25, -110, -84, -25, -109, -115, -25,
--109, -82, -25, -108, -113, -25, -108, -80, -25, -107, -111, -25, -107, -78, -25, -106,
--109, -25, -106, -76, -25, -105, -107, -25, -105, -74, -25, -104, -105, -25, -104, -72,
--25, -103, -103, -25, -103, -70, -25, -102, -101, -25, -102, -68, -25, -101, -99, -25,
--101, -66, -25, -100, -97, -25, -99, -128, -25, -99, -95, -25, -98, -126, -25, -98,
--93, -25, -97, -124, -25, -97, -91, -25, -96, -122, -25, -96, -89, -25, -95, -120,
--25, -95, -87, -25, -94, -118, -25, -94, -85, -25, -93, -116, -25, -93, -83, -25,
--92, -114, -25, -92, -81, -25, -91, -112, -25, -91, -79, -25, -90, -110, -25, -90,
--77, -25, -89, -108, -25, -89, -75, -25, -88, -106, -25, -88, -73, -25, -87, -104,
--25, -87, -71, -25, -86, -102, -25, -86, -69, -25, -85, -100, -25, -85, -67, -25,
--84, -98, -25, -84, -65, -25, -83, -96, -25, -82, -127, -25, -82, -94, -25, -81,
--125, -25, -81, -92, -25, -80, -123, -25, -80, -90, -25, -79, -121, -25, -79, -88,
--25, -78, -119, -25, -78, -86, -25, -77, -117, -25, -77, -84, -25, -76, -115, -25,
--76, -82, -25, -75, -113, -25, -75, -80, -25, -74, -111, -25, -74, -78, -25, -73,
--109, -25, -73, -76, -25, -72, -107, -25, -72, -74, -25, -71, -105, -25, -71, -72,
--25, -70, -103, -25, -70, -70, -25, -69, -101, -25, -69, -68, -25, -68, -99, -25,
--68, -66, -25, -67, -97, -25, -66, -128, -25, -66, -95, -25, -65, -126, -25, -65,
--93,
- */
-
-/*
-UTF-16
--2, -1, 0, 9, 0, 12, 0, 28, 0, 31, 0, 48, 0, 51, 0, 54,
-0, 57, 0, 65, 0, 68, 0, 71, 0, 74, 0, 77, 0, 80, 0, 83,
-0, 86, 0, 89, 0, 97, 0, 100, 0, 103, 0, 106, 0, 109, 0, 112,
-0, 115, 0, 118, 0, 121, 0, -86, 0, -75, 0, -70, 0, -64, 0, -61,
-0, -58, 0, -55, 0, -52, 0, -49, 0, -46, 0, -43, 0, -40, 0, -37,
-0, -34, 0, -31, 0, -28, 0, -25, 0, -22, 0, -19, 0, -16, 0, -13,
-0, -10, 0, -7, 0, -4, 0, -1, 1, 2, 1, 5, 1, 8, 1, 11,
-1, 14, 1, 17, 1, 20, 1, 23, 1, 26, 1, 29, 1, 32, 1, 35,
-1, 38, 1, 41, 1, 44, 1, 47, 1, 50, 1, 53, 1, 56, 1, 59,
-1, 62, 1, 65, 1, 68, 1, 71, 1, 74, 1, 77, 1, 80, 1, 83,
-1, 86, 1, 89, 1, 92, 1, 95, 1, 98, 1, 101, 1, 104, 1, 107,
-1, 110, 1, 113, 1, 116, 1, 119, 1, 122, 1, 125, 1, -128, 1, -125,
-1, -122, 1, -119, 1, -116, 1, -113, 1, -110, 1, -107, 1, -104, 1, -101,
-1, -98, 1, -95, 1, -92, 1, -89, 1, -86, 1, -83, 1, -80, 1, -77,
-1, -74, 1, -71, 1, -68, 1, -65, 1, -62, 1, -59, 1, -56, 1, -53,
-1, -50, 1, -47, 1, -44, 1, -41, 1, -38, 1, -35, 1, -32, 1, -29,
-1, -26, 1, -23, 1, -20, 1, -17, 1, -14, 1, -11, 1, -8, 1, -5,
-1, -2, 2, 1, 2, 4, 2, 7, 2, 10, 2, 13, 2, 16, 2, 19,
-2, 22, 2, 25, 2, 28, 2, 31, 2, 34, 2, 37, 2, 40, 2, 43,
-2, 46, 2, 49, 2, 52, 2, 80, 2, 83, 2, 86, 2, 89, 2, 92,
-2, 95, 2, 98, 2, 101, 2, 104, 2, 107, 2, 110, 2, 113, 2, 116,
-2, 119, 2, 122, 2, 125, 2, -128, 2, -125, 2, -122, 2, -119, 2, -116,
-2, -113, 2, -110, 2, -107, 2, -104, 2, -101, 2, -98, 2, -95, 2, -92,
-2, -89, 2, -86, 2, -83, 2, -80, 2, -77, 2, -74, 2, -71, 2, -68,
-2, -65, 2, -58, 2, -55, 2, -52, 2, -49, 2, -32, 2, -29, 2, -18,
-3, 122, 3, -122, 3, -119, 3, -116, 3, -113, 3, -110, 3, -107, 3, -104,
-3, -101, 3, -98, 3, -95, 3, -92, 3, -89, 3, -86, 3, -83, 3, -80,
-3, -77, 3, -74, 3, -71, 3, -68, 3, -65, 3, -62, 3, -59, 3, -56,
-3, -53, 3, -50, 3, -47, 3, -44, 3, -41, 3, -38, 3, -35, 3, -32,
-3, -29, 3, -26, 3, -23, 3, -20, 3, -17, 3, -14, 3, -11, 3, -8,
-3, -5, 4, 0, 4, 3, 4, 36, 4, 69, 4, 102, 4, -118, 4, -85,
-4, -52, 4, -19, 5, 14, 5, 49, 5, 82, 5, 115, 5, -48, 5, -15,
-6, 33, 6, 66, 6, 99, 6, -124, 6, -91, 6, -58, 6, -18, 7, 16,
-7, 77, 7, -128, 7, -95, 9, 4, 9, 37, 9, 80, 9, -123, 9, -90,
-9, -36, 10, 5, 10, 38, 10, 89, 10, -123, 10, -90, 10, -48, 11, 5,
-11, 38, 11, 92, 11, -125, 11, -92, 11, -25, 12, 8, 12, 42, 12, 96,
-12, -123, 12, -90, 12, -34, 13, 5, 13, 38, 13, 96, 13, -123, 13, -90,
-14, 1, 14, 34, 14, 67, 14, -127, 14, -94, 14, -61, 15, 0, 15, 33,
-15, 66, 15, 99, 15, -120, 16, 0, 16, 33, 16, 66, 16, -96, 16, -63,
-16, -30, 17, 3, 17, 36, 17, 69, 17, 102, 17, -121, 17, -88, 17, -55,
-17, -22, 18, 11, 18, 44, 18, 77, 18, 110, 18, -112, 18, -78, 18, -45,
-18, -12, 19, 21, 19, 54, 19, 87, 19, -96, 19, -63, 19, -30, 20, 3,
-20, 36, 20, 69, 20, 102, 20, -121, 20, -88, 20, -55, 20, -22, 21, 11,
-21, 44, 21, 77, 21, 110, 21, -113, 21, -80, 21, -47, 21, -14, 22, 19,
-22, 52, 22, 85, 22, 118, 22, -105, 22, -72, 22, -39, 23, 0, 23, 33,
-23, 66, 23, 99, 23, -124, 23, -91, 23, -41, 24, 14, 24, 47, 24, 80,
-24, 113, 24, -110, 25, 0, 25, 70, 25, 103, 29, 0, 29, 33, 29, 66,
-29, 99, 30, 0, 30, 33, 30, 66, 30, 99, 30, -124, 30, -91, 30, -58,
-30, -25, 31, 8, 31, 41, 31, 74, 31, 107, 31, -116, 31, -83, 31, -48,
-31, -14, 32, 40, 32, 95, 33, 2, 33, 36, 33, 69, 48, 0, 48, 49,
-48, 82, 48, 115, 48, -108, 48, -75, 48, -42, 48, -9, 49, 24, 49, 57,
-49, 90, 49, 123, 49, -96, 49, -16, 52, 0, 52, 33, 52, 66, 52, 99,
-52, -124, 52, -91, 52, -58, 52, -25, 53, 8, 53, 41, 53, 74, 53, 107,
-53, -116, 53, -83, 53, -50, 53, -17, 54, 16, 54, 49, 54, 82, 54, 115,
-54, -108, 54, -75, 54, -42, 54, -9, 55, 24, 55, 57, 55, 90, 55, 123,
-55, -100, 55, -67, 55, -34, 55, -1, 56, 32, 56, 65, 56, 98, 56, -125,
-56, -92, 56, -59, 56, -26, 57, 7, 57, 40, 57, 73, 57, 106, 57, -117,
-57, -84, 57, -51, 57, -18, 58, 15, 58, 48, 58, 81, 58, 114, 58, -109,
-58, -76, 58, -43, 58, -10, 59, 23, 59, 56, 59, 89, 59, 122, 59, -101,
-59, -68, 59, -35, 59, -2, 60, 31, 60, 64, 60, 97, 60, -126, 60, -93,
-60, -60, 60, -27, 61, 6, 61, 39, 61, 72, 61, 105, 61, -118, 61, -85,
-61, -52, 61, -19, 62, 14, 62, 47, 62, 80, 62, 113, 62, -110, 62, -77,
-62, -44, 62, -11, 63, 22, 63, 55, 63, 88, 63, 121, 63, -102, 63, -69,
-63, -36, 63, -3, 64, 30, 64, 63, 64, 96, 64, -127, 64, -94, 64, -61,
-64, -28, 65, 5, 65, 38, 65, 71, 65, 104, 65, -119, 65, -86, 65, -53,
-65, -20, 66, 13, 66, 46, 66, 79, 66, 112, 66, -111, 66, -78, 66, -45,
-66, -12, 67, 21, 67, 54, 67, 87, 67, 120, 67, -103, 67, -70, 67, -37,
-67, -4, 68, 29, 68, 62, 68, 95, 68, -128, 68, -95, 68, -62, 68, -29,
-69, 4, 69, 37, 69, 70, 69, 103, 69, -120, 69, -87, 69, -54, 69, -21,
-70, 12, 70, 45, 70, 78, 70, 111, 70, -112, 70, -79, 70, -46, 70, -13,
-71, 20, 71, 53, 71, 86, 71, 119, 71, -104, 71, -71, 71, -38, 71, -5,
-72, 28, 72, 61, 72, 94, 72, 127, 72, -96, 72, -63, 72, -30, 73, 3,
-73, 36, 73, 69, 73, 102, 73, -121, 73, -88, 73, -55, 73, -22, 74, 11,
-74, 44, 74, 77, 74, 110, 74, -113, 74, -80, 74, -47, 74, -14, 75, 19,
-75, 52, 75, 85, 75, 118, 75, -105, 75, -72, 75, -39, 75, -6, 76, 27,
-76, 60, 76, 93, 76, 126, 76, -97, 76, -64, 76, -31, 77, 2, 77, 35,
-77, 68, 77, 101, 77, -122, 77, -89, 78, 0, 78, 33, 78, 66, 78, 99,
-78, -124, 78, -91, 78, -58, 78, -25, 79, 8, 79, 41, 79, 74, 79, 107,
-79, -116, 79, -83, 79, -50, 79, -17, 80, 16, 80, 49, 80, 82, 80, 115,
-80, -108, 80, -75, 80, -42, 80, -9, 81, 24, 81, 57, 81, 90, 81, 123,
-81, -100, 81, -67, 81, -34, 81, -1, 82, 32, 82, 65, 82, 98, 82, -125,
-82, -92, 82, -59, 82, -26, 83, 7, 83, 40, 83, 73, 83, 106, 83, -117,
-83, -84, 83, -51, 83, -18, 84, 15, 84, 48, 84, 81, 84, 114, 84, -109,
-84, -76, 84, -43, 84, -10, 85, 23, 85, 56, 85, 89, 85, 122, 85, -101,
-85, -68, 85, -35, 85, -2, 86, 31, 86, 64, 86, 97, 86, -126, 86, -93,
-86, -60, 86, -27, 87, 6, 87, 39, 87, 72, 87, 105, 87, -118, 87, -85,
-87, -52, 87, -19, 88, 14, 88, 47, 88, 80, 88, 113, 88, -110, 88, -77,
-88, -44, 88, -11, 89, 22, 89, 55, 89, 88, 89, 121, 89, -102, 89, -69,
-89, -36, 89, -3, 90, 30, 90, 63, 90, 96, 90, -127, 90, -94, 90, -61,
-90, -28, 91, 5, 91, 38, 91, 71, 91, 104, 91, -119, 91, -86, 91, -53,
-91, -20, 92, 13, 92, 46, 92, 79, 92, 112, 92, -111, 92, -78, 92, -45,
-92, -12, 93, 21, 93, 54, 93, 87, 93, 120, 93, -103, 93, -70, 93, -37,
-93, -4, 94, 29, 94, 62, 94, 95, 94, -128, 94, -95, 94, -62, 94, -29,
-95, 4, 95, 37, 95, 70, 95, 103, 95, -120, 95, -87, 95, -54, 95, -21,
-96, 12, 96, 45, 96, 78, 96, 111, 96, -112, 96, -79, 96, -46, 96, -13,
-97, 20, 97, 53, 97, 86, 97, 119, 97, -104, 97, -71, 97, -38, 97, -5,
-98, 28, 98, 61, 98, 94, 98, 127, 98, -96, 98, -63, 98, -30, 99, 3,
-99, 36, 99, 69, 99, 102, 99, -121, 99, -88, 99, -55, 99, -22, 100, 11,
-100, 44, 100, 77, 100, 110, 100, -113, 100, -80, 100, -47, 100, -14, 101, 19,
-101, 52, 101, 85, 101, 118, 101, -105, 101, -72, 101, -39, 101, -6, 102, 27,
-102, 60, 102, 93, 102, 126, 102, -97, 102, -64, 102, -31, 103, 2, 103, 35,
-103, 68, 103, 101, 103, -122, 103, -89, 103, -56, 103, -23, 104, 10, 104, 43,
-104, 76, 104, 109, 104, -114, 104, -81, 104, -48, 104, -15, 105, 18, 105, 51,
-105, 84, 105, 117, 105, -106, 105, -73, 105, -40, 105, -7, 106, 26, 106, 59,
-106, 92, 106, 125, 106, -98, 106, -65, 106, -32, 107, 1, 107, 34, 107, 67,
-107, 100, 107, -123, 107, -90, 107, -57, 107, -24, 108, 9, 108, 42, 108, 75,
-108, 108, 108, -115, 108, -82, 108, -49, 108, -16, 109, 17, 109, 50, 109, 83,
-109, 116, 109, -107, 109, -74, 109, -41, 109, -8, 110, 25, 110, 58, 110, 91,
-110, 124, 110, -99, 110, -66, 110, -33, 111, 0, 111, 33, 111, 66, 111, 99,
-111, -124, 111, -91, 111, -58, 111, -25, 112, 8, 112, 41, 112, 74, 112, 107,
-112, -116, 112, -83, 112, -50, 112, -17, 113, 16, 113, 49, 113, 82, 113, 115,
-113, -108, 113, -75, 113, -42, 113, -9, 114, 24, 114, 57, 114, 90, 114, 123,
-114, -100, 114, -67, 114, -34, 114, -1, 115, 32, 115, 65, 115, 98, 115, -125,
-115, -92, 115, -59, 115, -26, 116, 7, 116, 40, 116, 73, 116, 106, 116, -117,
-116, -84, 116, -51, 116, -18, 117, 15, 117, 48, 117, 81, 117, 114, 117, -109,
-117, -76, 117, -43, 117, -10, 118, 23, 118, 56, 118, 89, 118, 122, 118, -101,
-118, -68, 118, -35, 118, -2, 119, 31, 119, 64, 119, 97, 119, -126, 119, -93,
-119, -60, 119, -27, 120, 6, 120, 39, 120, 72, 120, 105, 120, -118, 120, -85,
-120, -52, 120, -19, 121, 14, 121, 47, 121, 80, 121, 113, 121, -110, 121, -77,
-121, -44, 121, -11, 122, 22, 122, 55, 122, 88, 122, 121, 122, -102, 122, -69,
-122, -36, 122, -3, 123, 30, 123, 63, 123, 96, 123, -127, 123, -94, 123, -61,
-123, -28, 124, 5, 124, 38, 124, 71, 124, 104, 124, -119, 124, -86, 124, -53,
-124, -20, 125, 13, 125, 46, 125, 79, 125, 112, 125, -111, 125, -78, 125, -45,
-125, -12, 126, 21, 126, 54, 126, 87, 126, 120, 126, -103, 126, -70, 126, -37,
-126, -4, 127, 29, 127, 62, 127, 95, 127, -128, 127, -95, 127, -62, 127, -29,
- */
-
-/*
-UTF-16BE
-0, 9, 0, 12, 0, 28, 0, 31, 0, 48, 0, 51, 0, 54, 0, 57,
-0, 65, 0, 68, 0, 71, 0, 74, 0, 77, 0, 80, 0, 83, 0, 86,
-0, 89, 0, 97, 0, 100, 0, 103, 0, 106, 0, 109, 0, 112, 0, 115,
-0, 118, 0, 121, 0, -86, 0, -75, 0, -70, 0, -64, 0, -61, 0, -58,
-0, -55, 0, -52, 0, -49, 0, -46, 0, -43, 0, -40, 0, -37, 0, -34,
-0, -31, 0, -28, 0, -25, 0, -22, 0, -19, 0, -16, 0, -13, 0, -10,
-0, -7, 0, -4, 0, -1, 1, 2, 1, 5, 1, 8, 1, 11, 1, 14,
-1, 17, 1, 20, 1, 23, 1, 26, 1, 29, 1, 32, 1, 35, 1, 38,
-1, 41, 1, 44, 1, 47, 1, 50, 1, 53, 1, 56, 1, 59, 1, 62,
-1, 65, 1, 68, 1, 71, 1, 74, 1, 77, 1, 80, 1, 83, 1, 86,
-1, 89, 1, 92, 1, 95, 1, 98, 1, 101, 1, 104, 1, 107, 1, 110,
-1, 113, 1, 116, 1, 119, 1, 122, 1, 125, 1, -128, 1, -125, 1, -122,
-1, -119, 1, -116, 1, -113, 1, -110, 1, -107, 1, -104, 1, -101, 1, -98,
-1, -95, 1, -92, 1, -89, 1, -86, 1, -83, 1, -80, 1, -77, 1, -74,
-1, -71, 1, -68, 1, -65, 1, -62, 1, -59, 1, -56, 1, -53, 1, -50,
-1, -47, 1, -44, 1, -41, 1, -38, 1, -35, 1, -32, 1, -29, 1, -26,
-1, -23, 1, -20, 1, -17, 1, -14, 1, -11, 1, -8, 1, -5, 1, -2,
-2, 1, 2, 4, 2, 7, 2, 10, 2, 13, 2, 16, 2, 19, 2, 22,
-2, 25, 2, 28, 2, 31, 2, 34, 2, 37, 2, 40, 2, 43, 2, 46,
-2, 49, 2, 52, 2, 80, 2, 83, 2, 86, 2, 89, 2, 92, 2, 95,
-2, 98, 2, 101, 2, 104, 2, 107, 2, 110, 2, 113, 2, 116, 2, 119,
-2, 122, 2, 125, 2, -128, 2, -125, 2, -122, 2, -119, 2, -116, 2, -113,
-2, -110, 2, -107, 2, -104, 2, -101, 2, -98, 2, -95, 2, -92, 2, -89,
-2, -86, 2, -83, 2, -80, 2, -77, 2, -74, 2, -71, 2, -68, 2, -65,
-2, -58, 2, -55, 2, -52, 2, -49, 2, -32, 2, -29, 2, -18, 3, 122,
-3, -122, 3, -119, 3, -116, 3, -113, 3, -110, 3, -107, 3, -104, 3, -101,
-3, -98, 3, -95, 3, -92, 3, -89, 3, -86, 3, -83, 3, -80, 3, -77,
-3, -74, 3, -71, 3, -68, 3, -65, 3, -62, 3, -59, 3, -56, 3, -53,
-3, -50, 3, -47, 3, -44, 3, -41, 3, -38, 3, -35, 3, -32, 3, -29,
-3, -26, 3, -23, 3, -20, 3, -17, 3, -14, 3, -11, 3, -8, 3, -5,
-4, 0, 4, 3, 4, 36, 4, 69, 4, 102, 4, -118, 4, -85, 4, -52,
-4, -19, 5, 14, 5, 49, 5, 82, 5, 115, 5, -48, 5, -15, 6, 33,
-6, 66, 6, 99, 6, -124, 6, -91, 6, -58, 6, -18, 7, 16, 7, 77,
-7, -128, 7, -95, 9, 4, 9, 37, 9, 80, 9, -123, 9, -90, 9, -36,
-10, 5, 10, 38, 10, 89, 10, -123, 10, -90, 10, -48, 11, 5, 11, 38,
-11, 92, 11, -125, 11, -92, 11, -25, 12, 8, 12, 42, 12, 96, 12, -123,
-12, -90, 12, -34, 13, 5, 13, 38, 13, 96, 13, -123, 13, -90, 14, 1,
-14, 34, 14, 67, 14, -127, 14, -94, 14, -61, 15, 0, 15, 33, 15, 66,
-15, 99, 15, -120, 16, 0, 16, 33, 16, 66, 16, -96, 16, -63, 16, -30,
-17, 3, 17, 36, 17, 69, 17, 102, 17, -121, 17, -88, 17, -55, 17, -22,
-18, 11, 18, 44, 18, 77, 18, 110, 18, -112, 18, -78, 18, -45, 18, -12,
-19, 21, 19, 54, 19, 87, 19, -96, 19, -63, 19, -30, 20, 3, 20, 36,
-20, 69, 20, 102, 20, -121, 20, -88, 20, -55, 20, -22, 21, 11, 21, 44,
-21, 77, 21, 110, 21, -113, 21, -80, 21, -47, 21, -14, 22, 19, 22, 52,
-22, 85, 22, 118, 22, -105, 22, -72, 22, -39, 23, 0, 23, 33, 23, 66,
-23, 99, 23, -124, 23, -91, 23, -41, 24, 14, 24, 47, 24, 80, 24, 113,
-24, -110, 25, 0, 25, 70, 25, 103, 29, 0, 29, 33, 29, 66, 29, 99,
-30, 0, 30, 33, 30, 66, 30, 99, 30, -124, 30, -91, 30, -58, 30, -25,
-31, 8, 31, 41, 31, 74, 31, 107, 31, -116, 31, -83, 31, -48, 31, -14,
-32, 40, 32, 95, 33, 2, 33, 36, 33, 69, 48, 0, 48, 49, 48, 82,
-48, 115, 48, -108, 48, -75, 48, -42, 48, -9, 49, 24, 49, 57, 49, 90,
-49, 123, 49, -96, 49, -16, 52, 0, 52, 33, 52, 66, 52, 99, 52, -124,
-52, -91, 52, -58, 52, -25, 53, 8, 53, 41, 53, 74, 53, 107, 53, -116,
-53, -83, 53, -50, 53, -17, 54, 16, 54, 49, 54, 82, 54, 115, 54, -108,
-54, -75, 54, -42, 54, -9, 55, 24, 55, 57, 55, 90, 55, 123, 55, -100,
-55, -67, 55, -34, 55, -1, 56, 32, 56, 65, 56, 98, 56, -125, 56, -92,
-56, -59, 56, -26, 57, 7, 57, 40, 57, 73, 57, 106, 57, -117, 57, -84,
-57, -51, 57, -18, 58, 15, 58, 48, 58, 81, 58, 114, 58, -109, 58, -76,
-58, -43, 58, -10, 59, 23, 59, 56, 59, 89, 59, 122, 59, -101, 59, -68,
-59, -35, 59, -2, 60, 31, 60, 64, 60, 97, 60, -126, 60, -93, 60, -60,
-60, -27, 61, 6, 61, 39, 61, 72, 61, 105, 61, -118, 61, -85, 61, -52,
-61, -19, 62, 14, 62, 47, 62, 80, 62, 113, 62, -110, 62, -77, 62, -44,
-62, -11, 63, 22, 63, 55, 63, 88, 63, 121, 63, -102, 63, -69, 63, -36,
-63, -3, 64, 30, 64, 63, 64, 96, 64, -127, 64, -94, 64, -61, 64, -28,
-65, 5, 65, 38, 65, 71, 65, 104, 65, -119, 65, -86, 65, -53, 65, -20,
-66, 13, 66, 46, 66, 79, 66, 112, 66, -111, 66, -78, 66, -45, 66, -12,
-67, 21, 67, 54, 67, 87, 67, 120, 67, -103, 67, -70, 67, -37, 67, -4,
-68, 29, 68, 62, 68, 95, 68, -128, 68, -95, 68, -62, 68, -29, 69, 4,
-69, 37, 69, 70, 69, 103, 69, -120, 69, -87, 69, -54, 69, -21, 70, 12,
-70, 45, 70, 78, 70, 111, 70, -112, 70, -79, 70, -46, 70, -13, 71, 20,
-71, 53, 71, 86, 71, 119, 71, -104, 71, -71, 71, -38, 71, -5, 72, 28,
-72, 61, 72, 94, 72, 127, 72, -96, 72, -63, 72, -30, 73, 3, 73, 36,
-73, 69, 73, 102, 73, -121, 73, -88, 73, -55, 73, -22, 74, 11, 74, 44,
-74, 77, 74, 110, 74, -113, 74, -80, 74, -47, 74, -14, 75, 19, 75, 52,
-75, 85, 75, 118, 75, -105, 75, -72, 75, -39, 75, -6, 76, 27, 76, 60,
-76, 93, 76, 126, 76, -97, 76, -64, 76, -31, 77, 2, 77, 35, 77, 68,
-77, 101, 77, -122, 77, -89, 78, 0, 78, 33, 78, 66, 78, 99, 78, -124,
-78, -91, 78, -58, 78, -25, 79, 8, 79, 41, 79, 74, 79, 107, 79, -116,
-79, -83, 79, -50, 79, -17, 80, 16, 80, 49, 80, 82, 80, 115, 80, -108,
-80, -75, 80, -42, 80, -9, 81, 24, 81, 57, 81, 90, 81, 123, 81, -100,
-81, -67, 81, -34, 81, -1, 82, 32, 82, 65, 82, 98, 82, -125, 82, -92,
-82, -59, 82, -26, 83, 7, 83, 40, 83, 73, 83, 106, 83, -117, 83, -84,
-83, -51, 83, -18, 84, 15, 84, 48, 84, 81, 84, 114, 84, -109, 84, -76,
-84, -43, 84, -10, 85, 23, 85, 56, 85, 89, 85, 122, 85, -101, 85, -68,
-85, -35, 85, -2, 86, 31, 86, 64, 86, 97, 86, -126, 86, -93, 86, -60,
-86, -27, 87, 6, 87, 39, 87, 72, 87, 105, 87, -118, 87, -85, 87, -52,
-87, -19, 88, 14, 88, 47, 88, 80, 88, 113, 88, -110, 88, -77, 88, -44,
-88, -11, 89, 22, 89, 55, 89, 88, 89, 121, 89, -102, 89, -69, 89, -36,
-89, -3, 90, 30, 90, 63, 90, 96, 90, -127, 90, -94, 90, -61, 90, -28,
-91, 5, 91, 38, 91, 71, 91, 104, 91, -119, 91, -86, 91, -53, 91, -20,
-92, 13, 92, 46, 92, 79, 92, 112, 92, -111, 92, -78, 92, -45, 92, -12,
-93, 21, 93, 54, 93, 87, 93, 120, 93, -103, 93, -70, 93, -37, 93, -4,
-94, 29, 94, 62, 94, 95, 94, -128, 94, -95, 94, -62, 94, -29, 95, 4,
-95, 37, 95, 70, 95, 103, 95, -120, 95, -87, 95, -54, 95, -21, 96, 12,
-96, 45, 96, 78, 96, 111, 96, -112, 96, -79, 96, -46, 96, -13, 97, 20,
-97, 53, 97, 86, 97, 119, 97, -104, 97, -71, 97, -38, 97, -5, 98, 28,
-98, 61, 98, 94, 98, 127, 98, -96, 98, -63, 98, -30, 99, 3, 99, 36,
-99, 69, 99, 102, 99, -121, 99, -88, 99, -55, 99, -22, 100, 11, 100, 44,
-100, 77, 100, 110, 100, -113, 100, -80, 100, -47, 100, -14, 101, 19, 101, 52,
-101, 85, 101, 118, 101, -105, 101, -72, 101, -39, 101, -6, 102, 27, 102, 60,
-102, 93, 102, 126, 102, -97, 102, -64, 102, -31, 103, 2, 103, 35, 103, 68,
-103, 101, 103, -122, 103, -89, 103, -56, 103, -23, 104, 10, 104, 43, 104, 76,
-104, 109, 104, -114, 104, -81, 104, -48, 104, -15, 105, 18, 105, 51, 105, 84,
-105, 117, 105, -106, 105, -73, 105, -40, 105, -7, 106, 26, 106, 59, 106, 92,
-106, 125, 106, -98, 106, -65, 106, -32, 107, 1, 107, 34, 107, 67, 107, 100,
-107, -123, 107, -90, 107, -57, 107, -24, 108, 9, 108, 42, 108, 75, 108, 108,
-108, -115, 108, -82, 108, -49, 108, -16, 109, 17, 109, 50, 109, 83, 109, 116,
-109, -107, 109, -74, 109, -41, 109, -8, 110, 25, 110, 58, 110, 91, 110, 124,
-110, -99, 110, -66, 110, -33, 111, 0, 111, 33, 111, 66, 111, 99, 111, -124,
-111, -91, 111, -58, 111, -25, 112, 8, 112, 41, 112, 74, 112, 107, 112, -116,
-112, -83, 112, -50, 112, -17, 113, 16, 113, 49, 113, 82, 113, 115, 113, -108,
-113, -75, 113, -42, 113, -9, 114, 24, 114, 57, 114, 90, 114, 123, 114, -100,
-114, -67, 114, -34, 114, -1, 115, 32, 115, 65, 115, 98, 115, -125, 115, -92,
-115, -59, 115, -26, 116, 7, 116, 40, 116, 73, 116, 106, 116, -117, 116, -84,
-116, -51, 116, -18, 117, 15, 117, 48, 117, 81, 117, 114, 117, -109, 117, -76,
-117, -43, 117, -10, 118, 23, 118, 56, 118, 89, 118, 122, 118, -101, 118, -68,
-118, -35, 118, -2, 119, 31, 119, 64, 119, 97, 119, -126, 119, -93, 119, -60,
-119, -27, 120, 6, 120, 39, 120, 72, 120, 105, 120, -118, 120, -85, 120, -52,
-120, -19, 121, 14, 121, 47, 121, 80, 121, 113, 121, -110, 121, -77, 121, -44,
-121, -11, 122, 22, 122, 55, 122, 88, 122, 121, 122, -102, 122, -69, 122, -36,
-122, -3, 123, 30, 123, 63, 123, 96, 123, -127, 123, -94, 123, -61, 123, -28,
-124, 5, 124, 38, 124, 71, 124, 104, 124, -119, 124, -86, 124, -53, 124, -20,
-125, 13, 125, 46, 125, 79, 125, 112, 125, -111, 125, -78, 125, -45, 125, -12,
-126, 21, 126, 54, 126, 87, 126, 120, 126, -103, 126, -70, 126, -37, 126, -4,
-127, 29, 127, 62, 127, 95, 127, -128, 127, -95, 127, -62, 127, -29, */
-
-/*
-UTF-16LE
-9, 0, 12, 0, 28, 0, 31, 0, 48, 0, 51, 0, 54, 0, 57, 0,
-65, 0, 68, 0, 71, 0, 74, 0, 77, 0, 80, 0, 83, 0, 86, 0,
-89, 0, 97, 0, 100, 0, 103, 0, 106, 0, 109, 0, 112, 0, 115, 0,
-118, 0, 121, 0, -86, 0, -75, 0, -70, 0, -64, 0, -61, 0, -58, 0,
--55, 0, -52, 0, -49, 0, -46, 0, -43, 0, -40, 0, -37, 0, -34, 0,
--31, 0, -28, 0, -25, 0, -22, 0, -19, 0, -16, 0, -13, 0, -10, 0,
--7, 0, -4, 0, -1, 0, 2, 1, 5, 1, 8, 1, 11, 1, 14, 1,
-17, 1, 20, 1, 23, 1, 26, 1, 29, 1, 32, 1, 35, 1, 38, 1,
-41, 1, 44, 1, 47, 1, 50, 1, 53, 1, 56, 1, 59, 1, 62, 1,
-65, 1, 68, 1, 71, 1, 74, 1, 77, 1, 80, 1, 83, 1, 86, 1,
-89, 1, 92, 1, 95, 1, 98, 1, 101, 1, 104, 1, 107, 1, 110, 1,
-113, 1, 116, 1, 119, 1, 122, 1, 125, 1, -128, 1, -125, 1, -122, 1,
--119, 1, -116, 1, -113, 1, -110, 1, -107, 1, -104, 1, -101, 1, -98, 1,
--95, 1, -92, 1, -89, 1, -86, 1, -83, 1, -80, 1, -77, 1, -74, 1,
--71, 1, -68, 1, -65, 1, -62, 1, -59, 1, -56, 1, -53, 1, -50, 1,
--47, 1, -44, 1, -41, 1, -38, 1, -35, 1, -32, 1, -29, 1, -26, 1,
--23, 1, -20, 1, -17, 1, -14, 1, -11, 1, -8, 1, -5, 1, -2, 1,
-1, 2, 4, 2, 7, 2, 10, 2, 13, 2, 16, 2, 19, 2, 22, 2,
-25, 2, 28, 2, 31, 2, 34, 2, 37, 2, 40, 2, 43, 2, 46, 2,
-49, 2, 52, 2, 80, 2, 83, 2, 86, 2, 89, 2, 92, 2, 95, 2,
-98, 2, 101, 2, 104, 2, 107, 2, 110, 2, 113, 2, 116, 2, 119, 2,
-122, 2, 125, 2, -128, 2, -125, 2, -122, 2, -119, 2, -116, 2, -113, 2,
--110, 2, -107, 2, -104, 2, -101, 2, -98, 2, -95, 2, -92, 2, -89, 2,
--86, 2, -83, 2, -80, 2, -77, 2, -74, 2, -71, 2, -68, 2, -65, 2,
--58, 2, -55, 2, -52, 2, -49, 2, -32, 2, -29, 2, -18, 2, 122, 3,
--122, 3, -119, 3, -116, 3, -113, 3, -110, 3, -107, 3, -104, 3, -101, 3,
--98, 3, -95, 3, -92, 3, -89, 3, -86, 3, -83, 3, -80, 3, -77, 3,
--74, 3, -71, 3, -68, 3, -65, 3, -62, 3, -59, 3, -56, 3, -53, 3,
--50, 3, -47, 3, -44, 3, -41, 3, -38, 3, -35, 3, -32, 3, -29, 3,
--26, 3, -23, 3, -20, 3, -17, 3, -14, 3, -11, 3, -8, 3, -5, 3,
-0, 4, 3, 4, 36, 4, 69, 4, 102, 4, -118, 4, -85, 4, -52, 4,
--19, 4, 14, 5, 49, 5, 82, 5, 115, 5, -48, 5, -15, 5, 33, 6,
-66, 6, 99, 6, -124, 6, -91, 6, -58, 6, -18, 6, 16, 7, 77, 7,
--128, 7, -95, 7, 4, 9, 37, 9, 80, 9, -123, 9, -90, 9, -36, 9,
-5, 10, 38, 10, 89, 10, -123, 10, -90, 10, -48, 10, 5, 11, 38, 11,
-92, 11, -125, 11, -92, 11, -25, 11, 8, 12, 42, 12, 96, 12, -123, 12,
--90, 12, -34, 12, 5, 13, 38, 13, 96, 13, -123, 13, -90, 13, 1, 14,
-34, 14, 67, 14, -127, 14, -94, 14, -61, 14, 0, 15, 33, 15, 66, 15,
-99, 15, -120, 15, 0, 16, 33, 16, 66, 16, -96, 16, -63, 16, -30, 16,
-3, 17, 36, 17, 69, 17, 102, 17, -121, 17, -88, 17, -55, 17, -22, 17,
-11, 18, 44, 18, 77, 18, 110, 18, -112, 18, -78, 18, -45, 18, -12, 18,
-21, 19, 54, 19, 87, 19, -96, 19, -63, 19, -30, 19, 3, 20, 36, 20,
-69, 20, 102, 20, -121, 20, -88, 20, -55, 20, -22, 20, 11, 21, 44, 21,
-77, 21, 110, 21, -113, 21, -80, 21, -47, 21, -14, 21, 19, 22, 52, 22,
-85, 22, 118, 22, -105, 22, -72, 22, -39, 22, 0, 23, 33, 23, 66, 23,
-99, 23, -124, 23, -91, 23, -41, 23, 14, 24, 47, 24, 80, 24, 113, 24,
--110, 24, 0, 25, 70, 25, 103, 25, 0, 29, 33, 29, 66, 29, 99, 29,
-0, 30, 33, 30, 66, 30, 99, 30, -124, 30, -91, 30, -58, 30, -25, 30,
-8, 31, 41, 31, 74, 31, 107, 31, -116, 31, -83, 31, -48, 31, -14, 31,
-40, 32, 95, 32, 2, 33, 36, 33, 69, 33, 0, 48, 49, 48, 82, 48,
-115, 48, -108, 48, -75, 48, -42, 48, -9, 48, 24, 49, 57, 49, 90, 49,
-123, 49, -96, 49, -16, 49, 0, 52, 33, 52, 66, 52, 99, 52, -124, 52,
--91, 52, -58, 52, -25, 52, 8, 53, 41, 53, 74, 53, 107, 53, -116, 53,
--83, 53, -50, 53, -17, 53, 16, 54, 49, 54, 82, 54, 115, 54, -108, 54,
--75, 54, -42, 54, -9, 54, 24, 55, 57, 55, 90, 55, 123, 55, -100, 55,
--67, 55, -34, 55, -1, 55, 32, 56, 65, 56, 98, 56, -125, 56, -92, 56,
--59, 56, -26, 56, 7, 57, 40, 57, 73, 57, 106, 57, -117, 57, -84, 57,
--51, 57, -18, 57, 15, 58, 48, 58, 81, 58, 114, 58, -109, 58, -76, 58,
--43, 58, -10, 58, 23, 59, 56, 59, 89, 59, 122, 59, -101, 59, -68, 59,
--35, 59, -2, 59, 31, 60, 64, 60, 97, 60, -126, 60, -93, 60, -60, 60,
--27, 60, 6, 61, 39, 61, 72, 61, 105, 61, -118, 61, -85, 61, -52, 61,
--19, 61, 14, 62, 47, 62, 80, 62, 113, 62, -110, 62, -77, 62, -44, 62,
--11, 62, 22, 63, 55, 63, 88, 63, 121, 63, -102, 63, -69, 63, -36, 63,
--3, 63, 30, 64, 63, 64, 96, 64, -127, 64, -94, 64, -61, 64, -28, 64,
-5, 65, 38, 65, 71, 65, 104, 65, -119, 65, -86, 65, -53, 65, -20, 65,
-13, 66, 46, 66, 79, 66, 112, 66, -111, 66, -78, 66, -45, 66, -12, 66,
-21, 67, 54, 67, 87, 67, 120, 67, -103, 67, -70, 67, -37, 67, -4, 67,
-29, 68, 62, 68, 95, 68, -128, 68, -95, 68, -62, 68, -29, 68, 4, 69,
-37, 69, 70, 69, 103, 69, -120, 69, -87, 69, -54, 69, -21, 69, 12, 70,
-45, 70, 78, 70, 111, 70, -112, 70, -79, 70, -46, 70, -13, 70, 20, 71,
-53, 71, 86, 71, 119, 71, -104, 71, -71, 71, -38, 71, -5, 71, 28, 72,
-61, 72, 94, 72, 127, 72, -96, 72, -63, 72, -30, 72, 3, 73, 36, 73,
-69, 73, 102, 73, -121, 73, -88, 73, -55, 73, -22, 73, 11, 74, 44, 74,
-77, 74, 110, 74, -113, 74, -80, 74, -47, 74, -14, 74, 19, 75, 52, 75,
-85, 75, 118, 75, -105, 75, -72, 75, -39, 75, -6, 75, 27, 76, 60, 76,
-93, 76, 126, 76, -97, 76, -64, 76, -31, 76, 2, 77, 35, 77, 68, 77,
-101, 77, -122, 77, -89, 77, 0, 78, 33, 78, 66, 78, 99, 78, -124, 78,
--91, 78, -58, 78, -25, 78, 8, 79, 41, 79, 74, 79, 107, 79, -116, 79,
--83, 79, -50, 79, -17, 79, 16, 80, 49, 80, 82, 80, 115, 80, -108, 80,
--75, 80, -42, 80, -9, 80, 24, 81, 57, 81, 90, 81, 123, 81, -100, 81,
--67, 81, -34, 81, -1, 81, 32, 82, 65, 82, 98, 82, -125, 82, -92, 82,
--59, 82, -26, 82, 7, 83, 40, 83, 73, 83, 106, 83, -117, 83, -84, 83,
--51, 83, -18, 83, 15, 84, 48, 84, 81, 84, 114, 84, -109, 84, -76, 84,
--43, 84, -10, 84, 23, 85, 56, 85, 89, 85, 122, 85, -101, 85, -68, 85,
--35, 85, -2, 85, 31, 86, 64, 86, 97, 86, -126, 86, -93, 86, -60, 86,
--27, 86, 6, 87, 39, 87, 72, 87, 105, 87, -118, 87, -85, 87, -52, 87,
--19, 87, 14, 88, 47, 88, 80, 88, 113, 88, -110, 88, -77, 88, -44, 88,
--11, 88, 22, 89, 55, 89, 88, 89, 121, 89, -102, 89, -69, 89, -36, 89,
--3, 89, 30, 90, 63, 90, 96, 90, -127, 90, -94, 90, -61, 90, -28, 90,
-5, 91, 38, 91, 71, 91, 104, 91, -119, 91, -86, 91, -53, 91, -20, 91,
-13, 92, 46, 92, 79, 92, 112, 92, -111, 92, -78, 92, -45, 92, -12, 92,
-21, 93, 54, 93, 87, 93, 120, 93, -103, 93, -70, 93, -37, 93, -4, 93,
-29, 94, 62, 94, 95, 94, -128, 94, -95, 94, -62, 94, -29, 94, 4, 95,
-37, 95, 70, 95, 103, 95, -120, 95, -87, 95, -54, 95, -21, 95, 12, 96,
-45, 96, 78, 96, 111, 96, -112, 96, -79, 96, -46, 96, -13, 96, 20, 97,
-53, 97, 86, 97, 119, 97, -104, 97, -71, 97, -38, 97, -5, 97, 28, 98,
-61, 98, 94, 98, 127, 98, -96, 98, -63, 98, -30, 98, 3, 99, 36, 99,
-69, 99, 102, 99, -121, 99, -88, 99, -55, 99, -22, 99, 11, 100, 44, 100,
-77, 100, 110, 100, -113, 100, -80, 100, -47, 100, -14, 100, 19, 101, 52, 101,
-85, 101, 118, 101, -105, 101, -72, 101, -39, 101, -6, 101, 27, 102, 60, 102,
-93, 102, 126, 102, -97, 102, -64, 102, -31, 102, 2, 103, 35, 103, 68, 103,
-101, 103, -122, 103, -89, 103, -56, 103, -23, 103, 10, 104, 43, 104, 76, 104,
-109, 104, -114, 104, -81, 104, -48, 104, -15, 104, 18, 105, 51, 105, 84, 105,
-117, 105, -106, 105, -73, 105, -40, 105, -7, 105, 26, 106, 59, 106, 92, 106,
-125, 106, -98, 106, -65, 106, -32, 106, 1, 107, 34, 107, 67, 107, 100, 107,
--123, 107, -90, 107, -57, 107, -24, 107, 9, 108, 42, 108, 75, 108, 108, 108,
--115, 108, -82, 108, -49, 108, -16, 108, 17, 109, 50, 109, 83, 109, 116, 109,
--107, 109, -74, 109, -41, 109, -8, 109, 25, 110, 58, 110, 91, 110, 124, 110,
--99, 110, -66, 110, -33, 110, 0, 111, 33, 111, 66, 111, 99, 111, -124, 111,
--91, 111, -58, 111, -25, 111, 8, 112, 41, 112, 74, 112, 107, 112, -116, 112,
--83, 112, -50, 112, -17, 112, 16, 113, 49, 113, 82, 113, 115, 113, -108, 113,
--75, 113, -42, 113, -9, 113, 24, 114, 57, 114, 90, 114, 123, 114, -100, 114,
--67, 114, -34, 114, -1, 114, 32, 115, 65, 115, 98, 115, -125, 115, -92, 115,
--59, 115, -26, 115, 7, 116, 40, 116, 73, 116, 106, 116, -117, 116, -84, 116,
--51, 116, -18, 116, 15, 117, 48, 117, 81, 117, 114, 117, -109, 117, -76, 117,
--43, 117, -10, 117, 23, 118, 56, 118, 89, 118, 122, 118, -101, 118, -68, 118,
--35, 118, -2, 118, 31, 119, 64, 119, 97, 119, -126, 119, -93, 119, -60, 119,
--27, 119, 6, 120, 39, 120, 72, 120, 105, 120, -118, 120, -85, 120, -52, 120,
--19, 120, 14, 121, 47, 121, 80, 121, 113, 121, -110, 121, -77, 121, -44, 121,
--11, 121, 22, 122, 55, 122, 88, 122, 121, 122, -102, 122, -69, 122, -36, 122,
--3, 122, 30, 123, 63, 123, 96, 123, -127, 123, -94, 123, -61, 123, -28, 123,
-5, 124, 38, 124, 71, 124, 104, 124, -119, 124, -86, 124, -53, 124, -20, 124,
-13, 125, 46, 125, 79, 125, 112, 125, -111, 125, -78, 125, -45, 125, -12, 125,
-21, 126, 54, 126, 87, 126, 120, 126, -103, 126, -70, 126, -37, 126, -4, 126,
-29, 127, 62, 127, 95, 127, -128, 127, -95, 127, -62, 127, -29, 127, */
-
-/* 1-BYTE:
-US-ASCII
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-1
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -86, -75, -70, -64, -61, -58,
--55, -52, -49, -46, -43, -40, -37, -34, -31, -28, -25, -22, -19, -16, -13, -10,
--7, -4, -1, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-2
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
--55, 63, 63, 63, 63, 63, 63, 63, -31, -28, -25, 63, -19, 63, -13, -10,
-63, -4, 63, -61, -79, 63, 63, -49, -16, 63, 63, -52, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -75, -93, -15, -46, 63, 63, -43, 63, 63,
--8, 63, -70, -34, -69, 63, 63, -39, -5, 63, 63, -68, -82, 63, 63, 63,
-
-ISO-8859-3
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, -64, 63, 63,
--55, -52, -49, -46, 63, 63, -37, 63, -31, -28, -25, -22, -19, 63, -13, -10,
--7, -4, 63, 63, 63, -58, -27, 63, 63, 63, 63, 63, -8, -43, 63, -95,
-63, 63, 63, 63, -68, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, -34, -70, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-4
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, -61, -58,
--55, 63, 63, 63, -43, -40, -37, 63, -31, -28, 63, 63, -19, 63, 63, -10,
-63, -4, 63, 63, -79, 63, 63, 63, -16, 63, -20, 63, 63, 63, -69, 63,
--75, 63, -25, 63, 63, -94, -90, 63, 63, 63, 63, -67, -14, 63, 63, -93,
-63, 63, 63, 63, 63, -35, -2, 63, 63, 63, 63, 63, -82, 63, 63, 63,
-
-ISO-8859-5
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, -93, -60, -27, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-6
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -63,
--30, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-7
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -74, -71, -68, -65, -62, -59, -56, -53,
--50, -47, -44, -41, -38, -35, -32, -29, -26, -23, -20, -17, -14, -11, -8, -5,
--2, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-8
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -32, 63, 63,
-
-ISO-8859-9
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -86, -75, -70, -64, -61, -58,
--55, -52, -49, -46, -43, -40, -37, 63, -31, -28, -25, -22, -19, 63, -13, -10,
--7, -4, -1, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-x-iso-8859-11
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -95, -62, -29, 63, 63, 63, 63, 63, 63,
-
-ISO-8859-13
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, -81,
--55, 63, 63, 63, -43, -88, 63, 63, 63, -28, 63, 63, 63, 63, -13, -10,
-63, -4, 63, 63, -32, 63, 63, 63, 63, 63, -21, 63, 63, 63, -20, 63,
-63, 63, -31, 63, 63, 63, -49, 63, -39, -15, 63, 63, -12, 63, 63, -86,
-63, 63, 63, 63, 63, 63, -5, 63, 63, 63, 63, -22, -34, 63, 63, 63,
-
-ISO-8859-15
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -86, -75, -70, -64, -61, -58,
--55, -52, -49, -46, -43, -40, -37, -34, -31, -28, -25, -22, -19, -16, -13, -10,
--7, -4, -1, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -67, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -76, 63, 63, 63,
-
- */
-
-/*
-ISO-2022-JP // MaxBytes = 8 !!!
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 27, 36, 66, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 38, 34, 38, 37, 38, 40, 38, 43, 38, 46, 38, 49, 38, 51, 38,
-54, 33, 41, 33, 41, 33, 41, 38, 67, 38, 70, 38, 73, 38, 76, 38,
-79, 33, 41, 38, 84, 38, 87, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 39, 54, 39,
-103, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 33, 33, 41, 36, 50, 36, 83, 33, 41, 37, 53, 37,
-86, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 48,
-108, 78, 62, 80, 41, 33, 41, 33, 41, 48, 103, 80, 61, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 75, 121, 80, 89, 80, 109, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 58, 68, 81, 37, 33, 41, 80,
-86, 33, 41, 69, 94, 33, 41, 33, 41, 81, 88, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 51, 68, 33, 41, 68, 60, 82, 43, 33, 41, 33,
-41, 82, 67, 33, 41, 33, 41, 33, 41, 72, 63, 82, 90, 77, 121, 33,
-41, 70, 93, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 83,
-57, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 83, 85, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 48, 53, 33,
-41, 84, 48, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 116, 33, 33,
-41, 33, 41, 33, 41, 74, 47, 33, 41, 33, 41, 51, 48, 48, 80, 84,
-121, 33, 41, 33, 41, 58, 74, 85, 42, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 48, 66, 33, 41, 33, 41, 33, 41, 85, 116, 33, 41, 86, 34, 33,
-41, 86, 42, 33, 41, 33, 41, 33, 41, 86, 61, 33, 41, 33, 41, 33,
-41, 33, 41, 78, 102, 86, 95, 33, 41, 68, 107, 33, 41, 86, 112, 33,
-41, 33, 41, 86, 123, 87, 34, 79, 46, 76, 111, 33, 41, 33, 41, 87,
-76, 73, 124, 33, 41, 50, 119, 33, 41, 33, 41, 33, 41, 66, 41, 33,
-41, 33, 41, 33, 41, 65, 91, 33, 41, 33, 41, 33, 41, 88, 77, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 89, 42, 62, 53, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 63,
-100, 89, 102, 33, 41, 33, 41, 72, 66, 33, 41, 33, 41, 33, 41, 64,
-113, 33, 41, 90, 51, 33, 41, 90, 61, 90, 69, 33, 41, 69, 77, 33,
-41, 90, 90, 50, 34, 33, 41, 67, 107, 90, 108, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 77, 104, 33, 41, 33, 41, 33,
-41, 91, 77, 33, 41, 91, 97, 33, 41, 33, 41, 33, 41, 68, 116, 33,
-41, 33, 41, 92, 37, 33, 41, 92, 56, 54, 75, 33, 41, 33, 41, 77,
-77, 92, 95, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 93, 61, 58, 33, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 93, 108, 93, 124, 33, 41, 66,
-89, 33, 41, 61, 39, 33, 41, 77, 97, 94, 56, 33, 41, 33, 41, 33,
-41, 94, 82, 94, 93, 67, 57, 33, 41, 57, 66, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 64, 33, 33, 41, 95, 57, 33, 41, 33,
-41, 33, 41, 33, 41, 50, 80, 33, 41, 67, 58, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 77, 80, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 96, 117, 96, 120, 33, 41, 33, 41, 97, 37, 33, 41, 69,
-68, 72, 42, 33, 41, 33, 41, 33, 41, 58, 47, 33, 41, 33, 41, 33,
-41, 33, 41, 72, 47, 33, 41, 33, 41, 33, 41, 61, 98, 63, 63, 67,
-101, 63, 103, 33, 41, 33, 41, 33, 41, 67, 78, 33, 41, 53, 78, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 65, 67, 33, 41, 77,
-52, 33, 41, 33, 41, 99, 58, 33, 41, 33, 41, 33, 41, 99, 77, 33,
-41, 99, 86, 33, 41, 33, 41, 78, 53, 33, 41, 99, 122, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 70, 70, 33, 41, 33, 41, 33, 41, 33,
-41, 74, 52, 33, 41, 33, 41, 33, 41, 71, 60, 101, 39, 101, 50, 33,
-41, 33, 41, 76, 86, 33, 41, 78, 125, 33, 41, 33, 41, 33, 41, 33,
-41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 33, 41, 102, 42, 33,
-41, 33, 41, 33, 41, 33, 41, */
-
-/*
-x-windows-950
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, -93, -68, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -93, 69, -93,
-72, -93, 75, -93, 78, -93, 81, -93, 84, -93, 86, -93, 89, 63, 63, 63,
--93, 94, -93, 97, -93, 100, -93, 103, -93, 106, 63, -93, 111, -93, 114, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, 64, 63,
-63, 63, 63, 63, 63, 63, -93, -87, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, -92, 64, 63, -55, 64, 63, -36, -78, -91, -24, -92,
--78, 63, -55, -77, 63, 63, -53, -53, 63, 63, -85, 91, -83, -63, 63, -48,
--36, 63, -44, 101, -40, 83, -74, -59, -71, -81, 63, -66, -88, -11, -63, -48,
--34, 63, 63, -88, -26, -24, -7, 63, 63, -88, -17, -48, -20, -71, -70, 63,
-63, -74, -45, 63, 63, -91, 99, 63, 63, -31, 70, -92, -49, -91, 109, -90,
-79, -54, 118, 63, -50, 77, 63, 63, 63, 63, -48, -14, -80, -31, 63, 63,
-63, 63, -36, -48, -71, -66, -71, -54, -27, 65, 63, -20, -57, 63, 63, -54,
--87, 63, 63, 63, -87, 88, 63, 63, -47, 74, -44, -76, -44, -62, -77, -13,
-63, -36, -15, 63, -68, 88, -20, -53, 63, -91, 126, -90, 105, -82, 78, -90,
-111, 63, -87, 100, -85, -72, -50, 105, -47, 99, 63, -44, -50, 63, -40, -71,
-63, 63, -27, 95, -20, -44, -11, -56, 63, -90, 119, 63, -40, -46, -68, 101,
--71, -17, 63, -85, -52, 63, -89, -62, 63, -50, -89, -82, 115, 63, -40, -17,
-63, 63, -27, 98, -64, -83, 63, 63, -85, -46, -43, 69, -68, 109, -55, 121,
-63, -76, 91, -68, 115, -89, -53, 63, -71, -5, -47, 123, -85, -36, -76, 95,
-63, -89, -42, -52, -82, -52, 122, 63, -82, -89, -43, 82, -43, 94, 63, -73,
-81, -40, -2, 63, -31, -43, -70, 66, 63, 63, 63, -14, 65, 63, -52, -78,
--55, -28, -87, -45, 63, 63, 63, -50, -39, 63, -47, -74, 63, -43, 115, -79,
--64, -76, 124, -76, -86, -35, -74, -73, 104, -31, -38, -27, -83, -27, -76, -68,
--74, 63, -62, 89, -12, 78, 63, -79, -43, -27, -67, -92, -26, -8, -16, 63,
--87, -12, 63, 63, -79, -34, -76, -67, -31, -8, -23, -75, 63, 63, -23, -67,
-63, 63, -52, -38, 63, -50, -3, -84, 94, 63, -47, -27, -82, -32, -43, -76,
-63, -79, -24, -39, -58, -39, -79, -76, -44, -35, -37, -73, -92, -73, -91, -30,
-66, -70, 101, 63, 63, 63, -23, -52, 63, 63, -20, -5, 63, -14, 77, 63,
-63, -35, -9, -90, -71, 63, -27, -12, -23, -27, -46, 64, -19, 77, -43, -33,
--55, -2, 63, -88, 91, -86, 113, -51, 77, -82, -11, -49, 123, -84, 119, 63,
--81, 68, -82, -9, 63, -42, 68, 63, -75, 65, -76, -7, -76, -17, 63, -73,
--66, -34, 90, 63, -26, 83, -30, -71, 63, -26, 94, -68, -31, -23, -9, -27,
--3, -19, 85, 63, -14, 100, -11, -43, -92, -11, 63, -84, -76, -46, 123, -78,
-109, -42, 81, -38, 93, -34, 109, 63, -70, -78, -26, 105, -22, 75, 63, 63,
--81, 82, -38, 103, -42, 93, 63, -53, 98, 63, -42, 103, 63, 63, -26, -95,
--9, -23, -51, 102, -49, -54, 63, -42, 113, -75, 98, 63, -70, -65, -68, -3,
-63, 63, -49, -40, -19, 114, -91, -48, 63, 63, 63, 63, -78, -86, -34, -47,
-63, -65, 97, -16, 76, 63, -26, -69, 63, -34, -41, -84, -34, -81, 117, 63,
--70, -50, -30, -27, -22, 124, -14, 123, -86, -66, -49, -22, -81, 122, -42, -77,
--38, -50, 63, -30, -15, -26, -61, -22, -85, -62, -90, -11, -29, -81, -89, 63,
--29, 66, -59, -95, 63, 63, 63, -67, 94, -19, -76, -86, -58, 63, 63, 63,
--84, -14, -78, -57, 63, -72, 97, 63, 63, 63, -65, 119, -19, -70, -16, 104,
--12, -87, 63, -81, -69, 63, -26, -30, -14, -83, -81, -57, -78, -49, -38, -14,
--75, -69, -72, 105, -70, -12, 63, -67, 109, -22, -43, -19, -34, -16, 118, -14,
--79, -7, 66, 63, 63, 63, 63, -38, -4, -81, -53, 63, -37, 67, -45, 100,
--29, 124, */
-
-/* 1-BYTE:
-windows-1250
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, 63,
--55, 63, 63, 63, 63, 63, 63, 63, -31, -28, -25, 63, -19, 63, -13, -10,
-63, -4, 63, -61, -71, 63, 63, -49, -16, 63, 63, -52, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -66, -93, -15, -46, 63, 63, -43, 63, 63,
--8, 63, -70, -34, -99, 63, 63, -39, -5, 63, 63, -97, -114, 63, 63, 63,
-
-windows-1251
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, -127, -44, -11, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-windows-1252
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -86, -75, -70, -64, -61, -58,
--55, -52, -49, -46, -43, -40, -37, -34, -31, -28, -25, -22, -19, -16, -13, -10,
--7, -4, -1, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -100, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -114, 63, 63, 63,
-63, 63, 63, -125, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--120, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-windows-1253
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -125, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -94, -71, -68, -65, -62, -59, -56, -53,
--50, -47, -44, -41, -38, -35, -32, -29, -26, -23, -20, -17, -14, -11, -8, -5,
--2, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-windows-1254
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -86, -75, -70, -64, -61, -58,
--55, -52, -49, -46, -43, -40, -37, 63, -31, -28, -25, -22, -19, 63, -13, -10,
--7, -4, -1, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -100, 63,
-63, 63, -2, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -125, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-windows-1255
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -125, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--120, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -32, -43, 63,
-
-windows-1256
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -25, -22, 63, 63, 63, 63,
--7, -4, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -100, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -125, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--120, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -63,
--34, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-windows-1257
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, -75, 63, 63, 63, -81,
--55, 63, 63, 63, -43, -88, 63, 63, 63, -28, 63, 63, 63, 63, -13, -10,
-63, -4, 63, 63, -32, 63, 63, 63, 63, 63, -21, 63, 63, 63, -20, 63,
-63, 63, -31, 63, 63, 63, -49, 63, -39, -15, 63, 63, -12, 63, 63, -86,
-63, 63, 63, 63, 63, 63, -5, 63, 63, 63, 63, -22, -34, 63, 63, 63,
-
-windows-1258
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -86, -75, -70, -64, 63, -58,
--55, 63, -49, 63, 63, -40, -37, 63, -31, -28, -25, -22, -19, 63, -13, -10,
--7, -4, -1, -61, 63, 63, 63, 63, -16, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -100, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -125, 63, 63, 63, 63, -11, 63, 63, 63, 63, -3, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--120, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-
- */
-
-/*
-Big5
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, -93, -68, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -93, 69, -93,
-72, -93, 75, -93, 78, -93, 81, -93, 84, -93, 86, -93, 89, 63, 63, 63,
--93, 94, -93, 97, -93, 100, -93, 103, -93, 106, 63, -93, 111, -93, 114, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -57, -68, -57, -34, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95,
-64, 63, -58, -74, -58, -41, 63, -57, 77, -57, 110, 63, -93, -87, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -92, 64, 63, -55, 64,
-63, -36, -78, -91, -24, -92, -78, 63, -55, -77, 63, 63, -53, -53, 63, 63,
--85, 91, -83, -63, 63, -48, -36, 63, -44, 101, -40, 83, -74, -59, -71, -81,
-63, -66, -88, -11, -63, -48, -34, 63, 63, -88, -26, -24, -7, 63, 63, -88,
--17, -48, -20, -71, -70, 63, 63, -74, -45, 63, 63, -91, 99, 63, 63, -31,
-70, -92, -49, -91, 109, -90, 79, -54, 118, 63, -50, 77, 63, 63, 63, 63,
--48, -14, -80, -31, 63, 63, 63, 63, -36, -48, -71, -66, -71, -54, -27, 65,
-63, -20, -57, 63, 63, -54, -87, 63, 63, 63, -87, 88, 63, 63, -47, 74,
--44, -76, -44, -62, -77, -13, 63, -36, -15, 63, -68, 88, -20, -53, 63, -91,
-126, -90, 105, -82, 78, -90, 111, 63, -87, 100, -85, -72, -50, 105, -47, 99,
-63, -44, -50, 63, -40, -71, 63, 63, -27, 95, -20, -44, -11, -56, 63, -90,
-119, 63, -40, -46, -68, 101, -71, -17, 63, -85, -52, 63, -89, -62, 63, -50,
--89, -82, 115, 63, -40, -17, 63, 63, -27, 98, -64, -83, 63, 63, -85, -46,
--43, 69, -68, 109, -55, 121, 63, -76, 91, -68, 115, -89, -53, 63, -71, -5,
--47, 123, -85, -36, -76, 95, 63, -89, -42, -52, -82, -52, 122, 63, -82, -89,
--43, 82, -43, 94, 63, -73, 81, -40, -2, 63, -31, -43, -70, 66, 63, 63,
-63, -14, 65, 63, -52, -78, -55, -28, -87, -45, 63, 63, 63, -50, -39, 63,
--47, -74, 63, -43, 115, -79, -64, -76, 124, -76, -86, -35, -74, -73, 104, -31,
--38, -27, -83, -27, -76, -68, -74, 63, -62, 89, -12, 78, 63, -79, -43, -27,
--67, -92, -26, -8, -16, 63, -87, -12, 63, 63, -79, -34, -76, -67, -31, -8,
--23, -75, 63, 63, -23, -67, 63, 63, -52, -38, 63, -50, -3, -84, 94, 63,
--47, -27, -82, -32, -43, -76, 63, -79, -24, -39, -58, -39, -79, -76, -44, -35,
--37, -73, -92, -73, -91, -30, 66, -70, 101, 63, 63, 63, -23, -52, 63, 63,
--20, -5, 63, -14, 77, 63, 63, -35, -9, -90, -71, 63, -27, -12, -23, -27,
--46, 64, -19, 77, -43, -33, -55, -2, 63, -88, 91, -86, 113, -51, 77, -82,
--11, -49, 123, -84, 119, 63, -81, 68, -82, -9, 63, -42, 68, 63, -75, 65,
--76, -7, -76, -17, 63, -73, -66, -34, 90, 63, -26, 83, -30, -71, 63, -26,
-94, -68, -31, -23, -9, -27, -3, -19, 85, 63, -14, 100, -11, -43, -92, -11,
-63, -84, -76, -46, 123, -78, 109, -42, 81, -38, 93, -34, 109, 63, -70, -78,
--26, 105, -22, 75, 63, 63, -81, 82, -38, 103, -42, 93, 63, -53, 98, 63,
--42, 103, 63, 63, -26, -95, -9, -23, -51, 102, -49, -54, 63, -42, 113, -75,
-98, 63, -70, -65, -68, -3, 63, 63, -49, -40, -19, 114, -91, -48, 63, 63,
-63, 63, -78, -86, -34, -47, 63, -65, 97, -16, 76, 63, -26, -69, 63, -34,
--41, -84, -34, -81, 117, 63, -70, -50, -30, -27, -22, 124, -14, 123, -86, -66,
--49, -22, -81, 122, -42, -77, -38, -50, 63, -30, -15, -26, -61, -22, -85, -62,
--90, -11, -29, -81, -89, 63, -29, 66, -59, -95, 63, 63, 63, -67, 94, -19,
--76, -86, -58, 63, 63, 63, -84, -14, -78, -57, 63, -72, 97, 63, 63, 63,
--65, 119, -19, -70, -16, 104, -12, -87, 63, -81, -69, 63, -26, -30, -14, -83,
--81, -57, -78, -49, -38, -14, -75, -69, -72, 105, -70, -12, 63, -67, 109, -22,
--43, -19, -34, -16, 118, -14, -79, -7, 66, 63, 63, 63, 63, -38, -4, -81,
--53, 63, -37, 67, -45, 100, -29, 124, */
-
-/* 1-BYTE:
-IBM864
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, -77, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-x-IBM874
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -95, -62, -29, 63, 63, 63, 63, 63, 63,
- */
-
-/*
-GB2312
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -88, -94, 63, 63, -88, -70, -88, -86,
-63, -88, -82, 63, -88, -76, -88, -71, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -88, -83, 63, 63, 63, 63, 63, 63, 63, 63, 63, -88, -79, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -88,
--93, 63, -88, -77, 63, -88, -73, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -91, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -90, -94, -90, -91, -90, -88, -90, -85,
--90, -82, -90, -79, -90, -77, -90, -74, 63, 63, 63, -90, -61, -90, -58, -90,
--55, -90, -52, -90, -49, 63, -90, -44, -90, -41, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -89, -74, -89,
--25, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -95, 63, -92, -78, -92,
--45, 63, -91, -75, -91, -42, 63, -88, -40, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, -46, -69, 63, 63, 63, 63, -70, -91, -58, -51,
-63, 63, 63, 63, 63, 63, 63, -39, -34, -72, -87, 63, 63, 63, 63, 63,
-63, -39, -46, 63, 63, 63, -75, -77, -47, -8, -59, -87, -39, -3, 63, -44,
--28, -55, -66, -74, -25, 63, 63, 63, 63, 63, 63, 63, -69, -36, 63, -47,
--71, 63, -73, -76, -74, -93, -64, -12, 63, 63, -33, -38, 63, -33, -44, -33,
--36, 63, 63, 63, 63, 63, 63, 63, -32, -61, -32, -43, -32, -67, 63, 63,
-63, -49, -7, 63, 63, -44, -78, 63, 63, -37, -31, 63, -75, -26, 63, -36,
--92, 63, 63, 63, 63, -55, -54, 63, 63, 63, -51, -30, -46, -60, -34, -54,
--53, -3, 63, -58, -34, -67, -86, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -80, -78, -49, -36, 63, 63, 63, 63, -58, -63, 63, -31, -81,
-63, 63, 63, 63, 63, 63, 63, -31, -41, 63, -25, -35, 63, -75, -37, 63,
-63, -30, -49, 63, 63, 63, -59, -86, -61, -42, 63, 63, -70, -36, 63, 63,
--65, -20, 63, 63, 63, -49, -94, 63, -29, -83, 63, -49, -21, 63, 63, 63,
--65, -74, 63, 63, 63, 63, 63, -20, -26, 63, -77, -48, -65, -39, 63, -62,
--93, 63, -68, -73, -51, -79, 63, -74, -34, -51, -58, -56, -32, -66, -66, -34,
--11, -80, -31, 63, 63, 63, -41, -85, 63, 63, 63, -22, -73, -21, -73, 63,
--74, -73, 63, 63, -51, -6, 63, -42, -25, 63, -63, -64, 63, 63, 63, 63,
-63, 63, -64, -76, 63, -24, -59, 63, -24, -47, -24, -48, 63, -41, -64, 63,
-63, -52, -35, 63, -64, -30, -67, -73, 63, -48, -88, 63, 63, -56, -74, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -69, -74, -20, -90, -76, -53, 63,
-63, 63, 63, 63, -21, -76, 63, 63, 63, -66, -38, 63, -52, -87, 63, -42,
--34, -59, -88, -44, -95, -52, -23, 63, 63, 63, 63, -61, -20, -43, -65, 63,
-63, 63, -28, -39, 63, 63, 63, 63, -77, -50, 63, 63, 63, 63, 63, 63,
--69, -16, 63, -52, -65, 63, -49, -87, -20, -55, -20, -51, 63, -20, -50, -56,
--37, -20, -40, 63, 63, 63, -75, -7, 63, 63, 63, 63, -60, -4, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -25, -5, 63, 63, -24, -80, 63, 63, -50,
--51, -22, -76, -52, -17, 63, -18, -76, 63, -16, -30, -70, -37, 63, -16, -7,
--56, -77, 63, 63, 63, 63, 63, -74, -36, -43, -26, -41, -59, -53, -81, 63,
-63, 63, -42, -86, 63, -43, -24, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -20, -4, 63, 63, 63, -16, -94, 63, -15, -73, 63, 63, 63, -13,
--60, -13, -41, 63, -13, -34, 63, -13, -18, 63, 63, 63, -12, -93, 63, 63,
--73, -37, -73, -32, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -73, -60, -25, -83, -41, -37, -73, -20, 63, -18, -71, 63, -49,
--37, 63, 63, */
-
-/*
-EUC-JP
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -113, -94, -20, 63, -113, -94,
--21, -113, -86, -94, -113, -86, -86, -113, -87, -95, -113, -86, -79, -113, -86, -64,
--113, -86, -63, -113, -86, -46, -113, -86, -40, -113, -87, -84, -113, -86, -27, -113,
--87, -80, -113, -85, -95, -113, -85, -93, -113, -85, -82, -113, -85, -76, -113, -85,
--65, -113, -87, -61, -113, -85, -47, -113, -85, -45, -113, -85, -29, -113, -85, -28,
--113, -85, -13, -113, -86, -91, -113, -85, -88, -113, -86, -84, -113, -85, -81, -113,
--86, -80, -113, -87, -62, 63, -113, -85, -74, -113, -86, -75, -113, -85, -70, -113,
--86, -67, 63, -113, -87, -92, -113, -85, -57, 63, -113, -85, -58, -113, -87, -90,
--113, -85, -56, -113, -87, -57, -113, -86, -52, -113, -85, -53, -113, -87, -88, -113,
--85, -51, -113, -86, -50, -113, -87, -85, -113, -85, -41, -113, -86, -42, -113, -87,
--51, -113, -86, -37, -113, -85, -38, -113, -86, -35, -113, -85, -33, -113, -86, -31,
--113, -85, -32, -113, -86, -20, -113, -85, -23, -113, -86, -21, -113, -85, -24, -113,
--86, -15, -113, -85, -12, -113, -85, -11, -113, -86, -10, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, -113, -85, -90, -113, -86, -43, -113, -85, -25, -113, -86,
--19, -113, -85, -17, 63, 63, 63, 63, 63, 63, 63, 63, -113, -85, -71, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -113, -90, -31, -113, -90, -29, -113, -90, -25, -113, -90, -20, -90, -94,
--90, -91, -90, -88, -90, -85, -90, -82, -90, -79, -90, -77, -90, -74, -113, -90,
--27, -113, -90, -14, -113, -90, -5, -90, -61, -90, -58, -90, -55, -90, -52, -90,
--49, -113, -90, -8, -90, -44, -90, -41, -113, -90, -6, -113, -90, -4, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -113, -89,
--61, -89, -74, -89, -25, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -95,
-63, -92, -78, -92, -45, 63, -91, -75, -91, -42, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -80, -20, -50, -66, -48, -87, -113,
--80, -74, 63, -80, -25, -48, -67, 63, -113, -80, -43, 63, 63, 63, -113, -79,
--92, -53, -7, -48, -39, -48, -19, -113, -79, -48, 63, -113, -79, -24, 63, -113,
--78, -93, -70, -60, -47, -91, 63, -48, -42, -113, -78, -28, -59, -34, 63, 63,
--47, -40, -113, -77, -88, 63, 63, 63, 63, -77, -60, -113, -77, -39, -60, -68,
--46, -85, 63, -113, -76, -85, -46, -61, 63, 63, 63, -56, -65, -46, -38, -51,
--7, 63, -58, -35, 63, 63, 63, 63, -113, -75, -63, 63, -45, -71, 63, 63,
-63, 63, 63, -45, -43, 63, -113, -74, -66, -113, -74, -54, 63, 63, 63, -113,
--74, -8, 63, -80, -75, 63, -44, -80, 63, 63, -113, -73, -23, -113, -73, -14,
-63, -12, -95, -113, -72, -79, 63, 63, -54, -81, -113, -72, -41, 63, -77, -80,
--80, -48, -44, -7, -113, -71, -91, 63, -70, -54, -43, -86, 63, -113, -71, -45,
-63, 63, 63, -113, -71, -12, 63, 63, 63, 63, 63, -113, -70, -64, -80, -62,
-63, 63, 63, -43, -12, -113, -70, -14, -42, -94, -113, -69, -94, -42, -86, -113,
--69, -75, 63, -113, -69, -63, -42, -67, 63, 63, 63, -113, -69, -20, -50, -26,
--42, -33, 63, -60, -21, -113, -68, -79, -42, -16, -113, -68, -62, 63, -42, -5,
--41, -94, -49, -82, -52, -17, 63, -113, -68, -2, -41, -52, -55, -4, 63, -78,
--9, 63, -113, -67, -37, 63, -62, -87, 63, -113, -67, -3, 63, -63, -37, -113,
--66, -64, -113, -66, -53, 63, -40, -51, -113, -66, -28, -113, -66, -18, 63, 63,
--113, -65, -86, -113, -65, -78, -39, -86, -66, -75, 63, 63, 63, -113, -65, -37,
-63, 63, -113, -65, -7, -113, -64, -89, -65, -28, -39, -26, -113, -64, -64, 63,
--56, -62, 63, 63, -113, -64, -18, -64, -15, -113, -63, -88, -38, -77, -113, -63,
--69, -38, -67, -38, -59, 63, -59, -51, 63, -38, -38, -78, -94, 63, -61, -21,
--38, -20, -113, -62, -61, -113, -62, -42, -113, -62, -33, 63, 63, 63, 63, -51,
--24, 63, 63, -113, -61, -67, -37, -51, 63, -37, -31, -113, -61, -37, 63, 63,
--60, -12, -113, -60, -95, -113, -60, -81, -36, -91, -113, -60, -66, -36, -72, -74,
--53, -113, -60, -40, -113, -60, -31, -51, -51, -36, -33, -113, -60, -8, -113, -59,
--93, 63, 63, -113, -59, -64, -113, -59, -54, 63, 63, 63, -35, -67, -70, -95,
--113, -58, -93, 63, 63, 63, -113, -58, -58, 63, -113, -58, -39, 63, -35, -20,
--35, -4, -113, -58, -7, -62, -39, -113, -57, -80, -67, -89, 63, -51, -31, -34,
--72, 63, 63, 63, -34, -46, -34, -35, -61, -71, 63, -71, -62, 63, 63, 63,
-63, 63, 63, -64, -95, -113, -56, -15, -33, -71, 63, 63, 63, -113, -55, -69,
--78, -48, 63, -61, -70, 63, 63, 63, -113, -55, -16, -113, -55, -7, 63, -51,
--48, 63, -113, -54, -72, 63, 63, -113, -54, -52, -113, -54, -41, -113, -54, -29,
-63, 63, 63, 63, 63, 63, 63, -113, -53, -49, 63, -113, -53, -24, -113, -53,
--11, -113, -52, -91, -113, -52, -84, 63, -32, -11, -32, -8, 63, 63, -31, -91,
-63, -59, -60, -56, -86, 63, -113, -51, -57, -113, -51, -51, -70, -81, 63, 63,
--113, -51, -3, -113, -50, -84, -56, -81, -113, -50, -70, 63, 63, -67, -30, -65,
--65, -61, -27, -65, -25, 63, 63, 63, -61, -50, -113, -49, -49, -75, -50, -113,
--49, -32, 63, -113, -49, -17, 63, -113, -48, -89, 63, -63, -61, 63, -51, -76,
-63, 63, -29, -70, -113, -48, -6, 63, 63, -29, -51, 63, -29, -42, 63, -113,
--47, -30, -50, -75, -113, -47, -15, -29, -6, -113, -46, -92, -113, -46, -86, 63,
-63, 63, -58, -58, 63, -113, -46, -22, 63, 63, -54, -76, 63, 63, 63, -57,
--68, -27, -89, -27, -78, -113, -45, -19, -113, -45, -5, -52, -42, 63, -50, -3,
--113, -44, -62, -113, -44, -51, 63, -113, -44, -34, 63, 63, 63, 63, 63, -113,
--44, -18, -26, -86, -113, -43, -91, -113, -43, -82, 63, -113, -43, -67, */
-
-/* 1-BYTE:
-KOI8-R
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -26, -56, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-
-x-MacRoman
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -69, -75, -68, -53, -52, -82,
--125, -19, -20, -15, -51, -81, -13, 63, -121, -118, -115, -112, -110, 63, -105, -102,
--99, -97, -40, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -49, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -60, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--10, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
- */
-
-/*
-GBK
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -88, -94, 63, 63, -88, -70, -88, -86,
-63, -88, -82, 63, -88, -76, -88, -71, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -88,
--67, 63, 63, -88, -83, 63, 63, 63, 63, 63, 63, 63, 63, 63, -88, -79,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--88, -93, 63, -88, -77, 63, -88, -73, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -91, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -90, -94, -90, -91, -90, -88, -90,
--85, -90, -82, -90, -79, -90, -77, -90, -74, 63, 63, 63, -90, -61, -90, -58,
--90, -55, -90, -52, -90, -49, 63, -90, -44, -90, -41, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -89, -74,
--89, -25, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -95, 63, -92, -78,
--92, -45, 63, -91, -75, -91, -42, 63, -88, -40, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -46, -69, -127, 73, -127, 86, -127, 96, -127,
-123, -70, -91, -58, -51, -127, -97, -127, -78, -127, -65, -127, -45, -127, -34, -127,
--16, -126, 66, -39, -34, -72, -87, -126, -126, -126, -109, -126, -85, -126, -57, -126,
--33, -126, -7, -39, -46, -125, 112, -125, -115, -125, -83, -75, -77, -47, -8, -59,
--87, -39, -3, -124, 68, -44, -28, -55, -66, -74, -25, -124, -122, -124, -99, -124,
--77, -124, -56, -124, -32, -124, -7, -123, 77, -69, -36, -123, 109, -47, -71, -123,
--111, -73, -76, -74, -93, -64, -12, -123, -58, -123, -41, -33, -38, -123, -9, -33,
--44, -33, -36, -122, 95, -122, 116, -122, -120, -122, -99, -122, -80, -122, -65, -122,
--42, -32, -61, -32, -43, -32, -67, -121, 101, -121, 126, -121, -107, -49, -7, -121,
--50, -121, -29, -44, -78, -120, 82, -120, 99, -37, -31, -120, -124, -75, -26, -120,
--80, -36, -92, -120, -39, -120, -14, -119, 79, -119, 105, -55, -54, -119, -98, -119,
--69, -119, -43, -51, -30, -46, -60, -34, -54, -53, -3, -118, 118, -58, -34, -67,
--86, -118, -71, -118, -52, -118, -29, -118, -2, -117, 87, -117, 117, -117, -113, -117,
--90, -117, -61, -117, -31, -117, -2, -116, 78, -80, -78, -49, -36, -116, 123, -116,
--110, -116, -90, -116, -71, -58, -63, -116, -37, -31, -81, -115, 68, -115, 91, -115,
-115, -115, -114, -115, -91, -115, -64, -115, -39, -31, -41, -114, 88, -25, -35, -114,
--121, -75, -37, -114, -86, -114, -61, -30, -49, -114, -27, -114, -5, -113, 86, -59,
--86, -61, -42, -113, -107, -113, -86, -70, -36, -113, -51, -113, -30, -65, -20, -112,
-67, -112, 80, -112, 103, -49, -94, -112, -118, -29, -83, -112, -78, -49, -21, -112,
--42, -112, -18, -111, 73, -65, -74, -111, -126, -111, -99, -111, -74, -111, -43, -111,
--28, -20, -26, -110, 73, -77, -48, -65, -39, -110, 126, -62, -93, -110, -108, -68,
--73, -51, -79, -110, -51, -74, -34, -51, -58, -56, -32, -66, -66, -34, -11, -80,
--31, -109, -103, -109, -77, -109, -51, -41, -85, -109, -8, -108, 83, -108, 113, -22,
--73, -21, -73, -108, -76, -74, -73, -108, -31, -108, -13, -51, -6, -107, 90, -42,
--25, -107, -125, -63, -64, -107, -80, -107, -53, -107, -24, -107, -3, -106, 83, -106,
-101, -64, -76, -106, -119, -24, -59, -106, -82, -24, -47, -24, -48, -106, -25, -41,
--64, -105, 70, -105, 96, -52, -35, -105, -110, -64, -30, -67, -73, -105, -36, -48,
--88, -104, 79, -104, 98, -56, -74, -104, -108, -104, -80, -104, -52, -104, -26, -103,
-64, -103, 92, -103, 119, -103, -107, -103, -74, -103, -41, -69, -74, -20, -90, -76,
--53, -102, 125, -102, -109, -102, -85, -102, -64, -102, -41, -21, -76, -102, -11, -101,
-72, -101, 90, -66, -38, -101, 123, -52, -87, -101, -102, -42, -34, -59, -88, -44,
--95, -52, -23, -101, -15, -100, 72, -100, 91, -100, 111, -61, -20, -43, -65, -100,
--72, -100, -49, -100, -30, -28, -39, -99, 78, -99, 103, -99, 126, -99, -104, -77,
--50, -99, -54, -99, -27, -98, 65, -98, 96, -98, 125, -98, -99, -69, -16, -98,
--51, -52, -65, -98, -12, -49, -87, -20, -55, -20, -51, -97, -104, -20, -50, -56,
--37, -20, -40, -96, 64, -96, 93, -96, 124, -75, -7, -96, -86, -96, -67, -96,
--44, -96, -21, -60, -4, -86, 80, -86, 101, -86, 119, -86, -108, -85, 80, -85,
-103, -85, 124, -85, -109, -84, 76, -25, -5, -84, 122, -84, -108, -24, -80, -83,
-100, -83, -123, -50, -51, -22, -76, -52, -17, -82, 120, -18, -76, -81, 71, -16,
--30, -70, -37, -81, 116, -16, -7, -56, -77, -80, 80, -80, 107, -80, 126, -80,
--101, -79, 74, -74, -36, -43, -26, -41, -59, -53, -81, -78, 88, -78, 111, -78,
--122, -42, -86, -77, 81, -43, -24, -77, 115, -77, -115, -76, 68, -76, 86, -76,
-107, -76, -121, -75, 65, -75, 95, -75, 118, -75, -120, -75, -96, -20, -4, -74,
-112, -74, -122, -74, -100, -16, -94, -73, 110, -15, -73, -73, -100, -72, 82, -72,
-111, -13, -60, -13, -41, -71, 74, -13, -34, -71, 114, -13, -18, -71, -97, -70,
-86, -70, 111, -12, -93, -69, 68, -69, 100, -73, -37, -73, -32, -68, 71, -68,
-94, -68, 123, -68, -103, -67, 88, -67, 120, -67, -103, -66, 87, -66, 120, -66,
--102, -65, 90, -65, 123, -65, -102, -64, 90, -64, 122, -73, -60, -25, -83, -41,
--37, -73, -20, -64, -112, -18, -71, -63, 91, -49, -37, -63, -119, -63, -96, */
-
-/*
-GB2312
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -88, -94, 63, 63, -88, -70, -88, -86,
-63, -88, -82, 63, -88, -76, -88, -71, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -88, -83, 63, 63, 63, 63, 63, 63, 63, 63, 63, -88, -79, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -88,
--93, 63, -88, -77, 63, -88, -73, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -91, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, -90, -94, -90, -91, -90, -88, -90, -85,
--90, -82, -90, -79, -90, -77, -90, -74, 63, 63, 63, -90, -61, -90, -58, -90,
--55, -90, -52, -90, -49, 63, -90, -44, -90, -41, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -89, -74, -89,
--25, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -95, 63, -92, -78, -92,
--45, 63, -91, -75, -91, -42, 63, -88, -40, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, -46, -69, 63, 63, 63, 63, -70, -91, -58, -51,
-63, 63, 63, 63, 63, 63, 63, -39, -34, -72, -87, 63, 63, 63, 63, 63,
-63, -39, -46, 63, 63, 63, -75, -77, -47, -8, -59, -87, -39, -3, 63, -44,
--28, -55, -66, -74, -25, 63, 63, 63, 63, 63, 63, 63, -69, -36, 63, -47,
--71, 63, -73, -76, -74, -93, -64, -12, 63, 63, -33, -38, 63, -33, -44, -33,
--36, 63, 63, 63, 63, 63, 63, 63, -32, -61, -32, -43, -32, -67, 63, 63,
-63, -49, -7, 63, 63, -44, -78, 63, 63, -37, -31, 63, -75, -26, 63, -36,
--92, 63, 63, 63, 63, -55, -54, 63, 63, 63, -51, -30, -46, -60, -34, -54,
--53, -3, 63, -58, -34, -67, -86, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -80, -78, -49, -36, 63, 63, 63, 63, -58, -63, 63, -31, -81,
-63, 63, 63, 63, 63, 63, 63, -31, -41, 63, -25, -35, 63, -75, -37, 63,
-63, -30, -49, 63, 63, 63, -59, -86, -61, -42, 63, 63, -70, -36, 63, 63,
--65, -20, 63, 63, 63, -49, -94, 63, -29, -83, 63, -49, -21, 63, 63, 63,
--65, -74, 63, 63, 63, 63, 63, -20, -26, 63, -77, -48, -65, -39, 63, -62,
--93, 63, -68, -73, -51, -79, 63, -74, -34, -51, -58, -56, -32, -66, -66, -34,
--11, -80, -31, 63, 63, 63, -41, -85, 63, 63, 63, -22, -73, -21, -73, 63,
--74, -73, 63, 63, -51, -6, 63, -42, -25, 63, -63, -64, 63, 63, 63, 63,
-63, 63, -64, -76, 63, -24, -59, 63, -24, -47, -24, -48, 63, -41, -64, 63,
-63, -52, -35, 63, -64, -30, -67, -73, 63, -48, -88, 63, 63, -56, -74, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -69, -74, -20, -90, -76, -53, 63,
-63, 63, 63, 63, -21, -76, 63, 63, 63, -66, -38, 63, -52, -87, 63, -42,
--34, -59, -88, -44, -95, -52, -23, 63, 63, 63, 63, -61, -20, -43, -65, 63,
-63, 63, -28, -39, 63, 63, 63, 63, -77, -50, 63, 63, 63, 63, 63, 63,
--69, -16, 63, -52, -65, 63, -49, -87, -20, -55, -20, -51, 63, -20, -50, -56,
--37, -20, -40, 63, 63, 63, -75, -7, 63, 63, 63, 63, -60, -4, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -25, -5, 63, 63, -24, -80, 63, 63, -50,
--51, -22, -76, -52, -17, 63, -18, -76, 63, -16, -30, -70, -37, 63, -16, -7,
--56, -77, 63, 63, 63, 63, 63, -74, -36, -43, -26, -41, -59, -53, -81, 63,
-63, 63, -42, -86, 63, -43, -24, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, -20, -4, 63, 63, 63, -16, -94, 63, -15, -73, 63, 63, 63, -13,
--60, -13, -41, 63, -13, -34, 63, -13, -18, 63, 63, 63, -12, -93, 63, 63,
--73, -37, -73, -32, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, -73, -60, -25, -83, -41, -37, -73, -20, 63, -18, -71, 63, -49,
--37, 63, 63, */
-
-/*
-EUC-KR
-9, 12, 28, 31, 48, 51, 54, 57, 65, 68, 71, 74, 77, 80, 83, 86,
-89, 97, 100, 103, 106, 109, 112, 115, 118, 121, -88, -93, 63, -88, -84, 63,
-63, -88, -95, 63, 63, 63, 63, 63, -88, -86, 63, -88, -83, 63, 63, 63,
-63, 63, -87, -93, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -87, -94,
-63, 63, 63, 63, 63, 63, -88, -92, 63, 63, 63, -88, -90, 63, -87, -89,
-63, 63, -88, -87, 63, 63, -88, -81, 63, 63, -87, -85, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -91, -62, -91, -59, -91, -56, -91,
--53, -91, -50, -91, -47, -91, -45, -91, -42, 63, 63, 63, -91, -29, -91, -26,
--91, -23, -91, -20, -91, -17, 63, -91, -12, -91, -9, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -84, -74,
--84, -25, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, -95, -95, 63, -86, -78,
--86, -45, 63, -85, -75, -85, -42, 63, 63, -92, -87, -92, -54, -92, -21, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -20, -23, 63, -25, -47, 63, 63,
--6, -92, 63, 63, 63, 63, 63, 63, 63, 63, -16, -69, -36, -10, 63, 63,
-63, 63, 63, -13, -16, -3, -22, 63, 63, 63, 63, 63, 63, -42, -87, -3,
--21, 63, 63, 63, 63, -4, -15, -48, -62, -10, -49, 63, 63, 63, -3, -63,
-63, 63, 63, -38, -29, 63, -41, -39, 63, -9, -94, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -15, -77, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, 63, 63, -24, -21, 63, 63, 63, -35, -59,
-63, 63, -24, -30, -20, -88, 63, 63, 63, -12, -93, -53, -87, 63, 63, 63,
-63, 63, 63, 63, 63, -5, -5, 63, 63, 63, -28, -52, 63, 63, -50, -80,
--45, -33, 63, 63, 63, -19, -44, 63, 63, -6, -42, 63, 63, 63, 63, 63,
--42, -70, 63, 63, -16, -88, 63, -10, -70, 63, 63, -33, -53, -50, -58, -42,
--25, 63, 63, -23, -18, 63, -36, -42, 63, -10, -31, 63, 63, 63, -29, -45,
-63, 63, 63, -33, -52, 63, 63, 63, -53, -81, -3, -13, 63, 63, 63, 63,
-63, 63, -29, -81, 63, 63, 63, 63, 63, 63, 63, 63, -11, -49, 63, 63,
-63, -38, -26, 63, 63, 63, -13, -68, 63, -12, -83, 63, 63, 63, 63, -44,
--32, 63, 63, -24, -38, 63, 63, -15, -72, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, -49, -81, 63, 63, 63, -14, -51, 63, -16, -84, 63, 63,
--11, -95, 63, -32, -37, -48, -65, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, -13, -82, 63, 63, 63, 63, 63, 63, 63, 63, 63,
--18, -63, 63, -9, -63, -36, -57, -15, -67, 63, -23, -79, -12, -15, 63, 63,
--12, -24, -4, -71, -39, -35, -45, -64, 63, -49, -75, 63, 63, 63, 63, 63,
-63, -13, -91, 63, 63, 63, 63, 63, 63, -5, -3, 63, -9, -87, 63, 63,
-63, 63, 63, 63, -23, -62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, 63, 63, 63, 63, 63, 63, -6, -64, -30, -81, -51, -28, 63, -40, -91,
--19, -16, 63, 63, -24, -73, 63, -17, -93, -17, -91, 63, 63, 63, -3, -35,
-63, 63, 63, 63, 63, 63, 63, 63, -30, -22, 63, -13, -73, -30, -78, 63,
-63, 63, -14, -79, 63, -10, -37, 63, 63, 63, 63, 63, 63, -11, -88, 63,
--23, -34, 63, 63, -27, -52, 63, 63, 63, -14, -61, 63, -49, -30, 63, 63,
-63, 63, -9, -62, 63, -48, -75, 63, 63, 63, -44, -65, 63, 63, 63, 63,
--35, -49, 63, 63, 63, -46, -95, -13, -49, 63, 63, 63, -40, -47, 63, -42,
--93, -24, -78, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
-63, */
-
-
-/*
-~/ddeclipse/dalvik$ ./run-core-tests.sh tests.api.java.nio.charset.Charset_DomainEndToEnd_Test
-mode: simulator
-Running selected tests...
-.US-ASCII MaxBytes = 1.0
- - IBM367
- - iso_646.irv:1983
- - csASCII
- - US-ASCII
- - ascii7
- - cp367
- - windows-20127
- - ASCII
- - ANSI_X3.4-1986
- - 646
- - ISO646-US
- - ANSI_X3.4-1968
- - iso-ir-6
- - ibm-367
- - ISO_646.irv:1991
- - us
-UTF-8 MaxBytes = 3.0
- - ibm-17593
- - ibm-1208
- - UTF-8
- - ibm-1209
- - cp1208
- - ibm-13496
- - ibm-13497
- - windows-65001
- - ibm-5304
- - ibm-5305
- - ibm-17592
-UTF-16 MaxBytes = 2.0
- - ucs-2
- - UTF-16
- - csUnicode
- - unicode
- - ibm-1204
- - ISO-10646-UCS-2
- - ibm-1205
-UTF-16BE MaxBytes = 2.0
- - x-utf-16be
- - ibm-61955
- - ibm-61956
- - UTF16_BigEndian
- - windows-1201
- - cp1200
- - UTF-16BE
- - cp1201
- - ibm-17584
- - ibm-17585
- - ibm-21680
- - ibm-21681
- - ibm-13488
- - ibm-1200
- - ibm-13489
- - ibm-25776
- - ibm-1201
- - ibm-25777
-UTF-16LE MaxBytes = 2.0
- - UTF16_LittleEndian
- - UTF-16LE
- - windows-1200
- - ibm-13490
- - ibm-13491
- - ibm-17586
- - ibm-17587
- - ibm-21682
- - x-utf-16le
- - ibm-21683
- - ibm-1202
- - ibm-25778
- - ibm-1203
- - ibm-25779
-ISO-8859-1 MaxBytes = 1.0
- - 819
- - ISO-8859-1
- - csISOLatin1
- - cp819
- - l1
- - iso-ir-100
- - 8859_1
- - ibm-819
- - IBM819
- - latin1
- - ISO_8859-1:1987
-ISO-8859-2 MaxBytes = 1.0
- - ISO-8859-2
- - ibm-912
- - ibm-912_P100-1995
- - csISOLatin2
- - l2
- - iso-ir-101
- - 8859_2
- - 912
- - cp912
- - windows-28592
- - latin2
- - ISO_8859-2:1987
-ISO-8859-3 MaxBytes = 1.0
- - ISO-8859-3
- - ibm-913
- - csISOLatin3
- - l3
- - 8859_3
- - 913
- - ibm-913_P100-2000
- - cp913
- - iso-ir-109
- - ISO_8859-3:1988
- - windows-28593
- - latin3
-ISO-8859-4 MaxBytes = 1.0
- - windows-28594
- - latin4
- - ISO-8859-4
- - ibm-914
- - iso-ir-110
- - ibm-914_P100-1995
- - csISOLatin4
- - l4
- - 8859_4
- - 914
- - ISO_8859-4:1988
- - cp914
-ISO-8859-5 MaxBytes = 1.0
- - cp915
- - windows-28595
- - ISO-8859-5
- - ibm-915
- - iso-ir-144
- - ibm-915_P100-1995
- - csISOLatinCyrillic
- - cyrillic
- - 8859_5
- - ISO_8859-5:1988
- - 915
-ISO-8859-6 MaxBytes = 1.0
- - 1089
- - windows-28596
- - ASMO-708
- - ibm-1089_P100-1995
- - arabic
- - ISO-8859-6-E
- - cp1089
- - ISO-8859-6-I
- - ISO-8859-6
- - ibm-1089
- - ECMA-114
- - iso-ir-127
- - ISO_8859-6:1987
- - csISOLatinArabic
- - 8859_6
-ISO-8859-7 MaxBytes = 1.0
- - greek
- - ibm-9005_X110-2007
- - csISOLatinGreek
- - windows-28597
- - sun_eu_greek
- - ibm-9005
- - ISO-8859-7
- - greek8
- - ISO_8859-7:1987
- - iso-ir-126
- - ELOT_928
- - ECMA-118
-ISO-8859-8 MaxBytes = 1.0
- - ISO-8859-8-I
- - windows-28598
- - ibm-5012
- - ISO-8859-8
- - ISO_8859-8:1988
- - iso-ir-138
- - ibm-5012_P100-1999
- - 8859_8
- - csISOLatinHebrew
- - ISO-8859-8-E
- - hebrew
-ISO-8859-8 MaxBytes = 1.0
- - ISO-8859-8-I
- - windows-28598
- - ibm-5012
- - ISO-8859-8
- - ISO_8859-8:1988
- - iso-ir-138
- - ibm-5012_P100-1999
- - 8859_8
- - csISOLatinHebrew
- - ISO-8859-8-E
- - hebrew
-ISO-8859-9 MaxBytes = 1.0
- - windows-28599
- - csISOLatin5
- - l5
- - cp920
- - ibm-920_P100-1995
- - latin5
- - 920
- - ISO-8859-9
- - iso-ir-148
- - ISO_8859-9:1989
- - ECMA-128
- - ibm-920
- - 8859_9
-ISO-8859-10 MaxBytes = 1.0
- - ISO-8859-10
- - latin6
- - iso-8859_10-1998
- - csISOLatin6
- - iso-ir-157
- - l6
- - ISO_8859-10:1992
-x-iso-8859_11-2001 MaxBytes = 1.0
- - ISO-8859-11
- - iso-8859_11-2001
- - thai8
-ISO-8859-13 MaxBytes = 1.0
- - ibm-921_P100-1995
- - ISO-8859-13
- - 921
- - windows-28603
- - cp921
- - 8859_13
- - ibm-921
-ISO-8859-14 MaxBytes = 1.0
- - latin8
- - ISO-8859-14
- - iso-ir-199
- - l8
- - iso-celtic
- - iso-8859_14-1998
- - ISO_8859-14:1998
-ISO-8859-15 MaxBytes = 1.0
- - ibm-923
- - csisolatin0
- - ISO-8859-15
- - csisolatin9
- - windows-28605
- - latin0
- - l9
- - iso8859_15_fdis
- - cp923
- - Latin-9
- - ibm-923_P100-1998
- - 923
- - 8859_15
-ISO-8859-16 MaxBytes = 1.0
- - latin10
- - iso-8859_16-2001
- - ISO_8859-16:2001
- - ISO-8859-16
- - iso-ir-226
- - l10
-ISO-2022-JP MaxBytes = 6.0
- - csISO2022JP
- - ISO-2022-JP
-Big5 MaxBytes = 2.0
- - windows-950-2000
- - csBig5
- - Big5
- - x-big5
- - windows-950
-windows-1250 MaxBytes = 1.0
- - windows-1250
- - cp1250
- - ibm-5346
- - ibm-5346_P100-1998
-windows-1251 MaxBytes = 1.0
- - ANSI1251
- - windows-1251
- - cp1251
- - ibm-5347
- - ibm-5347_P100-1998
-windows-1252 MaxBytes = 1.0
- - windows-1252
- - cp1252
- - ibm-5348
- - ibm-5348_P100-1997
-windows-1253 MaxBytes = 1.0
- - ibm-5349_P100-1998
- - windows-1253
- - cp1253
- - ibm-5349
-windows-1254 MaxBytes = 1.0
- - ibm-5350
- - ibm-5350_P100-1998
- - windows-1254
- - cp1254
-windows-1255 MaxBytes = 1.0
- - ibm-9447_P100-2002
- - ibm-9447
- - windows-1255
- - cp1255
-windows-1256 MaxBytes = 1.0
- - ibm-9448_X100-2005
- - ibm-9448
- - windows-1256
- - cp1256
-windows-1257 MaxBytes = 1.0
- - cp1257
- - ibm-9449_P100-2002
- - ibm-9449
- - windows-1257
-windows-1258 MaxBytes = 1.0
- - cp1258
- - ibm-5354
- - ibm-5354_P100-1998
- - windows-1258
-Big5 MaxBytes = 2.0
- - windows-950-2000
- - csBig5
- - Big5
- - x-big5
- - windows-950
-cp864 MaxBytes = 1.0
- - csIBM864
- - IBM864
- - cp864
- - ibm-864_X110-1999
- - ibm-864
-TIS-620 MaxBytes = 1.0
- - ibm-9066
- - TIS-620
- - eucTH
- - cp874
- - tis620.2533
- - ibm-874
- - ibm-874_P100-1995
-GBK MaxBytes = 2.0
- - EUC-CN
- - csISO58GB231280
- - chinese
- - csGB2312
- - CP936
- - GBK
- - gb2312-1980
- - windows-936
- - MS936
- - windows-936-2000
- - GB2312
- - iso-ir-58
- - GB_2312-80
-EUC-JP MaxBytes = 3.0
- - EUC-JP
- - ibm-954_P101-2007
- - eucjis
- - X-EUC-JP
- - csEUCPkdFmtJapanese
- - Extended_UNIX_Code_Packed_Format_for_Japanese
- - ujis
- - ibm-954
-KOI8-R MaxBytes = 1.0
- - windows-20866
- - ibm-878
- - ibm-878_P100-1996
- - koi8
- - KOI8-R
- - cp878
- - csKOI8R
-macintosh MaxBytes = 1.0
- - csMacintosh
- - macintosh
- - windows-10000
- - macos-0_2-10.2
- - mac
-GBK MaxBytes = 2.0
- - EUC-CN
- - csISO58GB231280
- - chinese
- - csGB2312
- - CP936
- - GBK
- - gb2312-1980
- - windows-936
- - MS936
- - windows-936-2000
- - GB2312
- - iso-ir-58
- - GB_2312-80
-GBK MaxBytes = 2.0
- - EUC-CN
- - csISO58GB231280
- - chinese
- - csGB2312
- - CP936
- - GBK
- - gb2312-1980
- - windows-936
- - MS936
- - windows-936-2000
- - GB2312
- - iso-ir-58
- - GB_2312-80
-EUC-KR MaxBytes = 2.0
- - KS_C_5601-1989
- - EUC-KR
- - 5601
- - korean
- - csKSC56011987
- - windows-949
- - KSC_5601
- - windows-949-2000
- - ms949
- - csEUCKR
- - iso-ir-149
- - KS_C_5601-1987
-Big5
- - windows-950-2000
- - csBig5
- - Big5
- - x-big5
- - windows-950
-BOCU-1
- - csBOCU-1
- - BOCU-1
- - ibm-1214
- - ibm-1215
-CESU-8
- - ibm-9400
- - CESU-8
-cp864
- - csIBM864
- - IBM864
- - cp864
- - ibm-864_X110-1999
- - ibm-864
-EUC-JP
- - EUC-JP
- - ibm-954_P101-2007
- - eucjis
- - X-EUC-JP
- - csEUCPkdFmtJapanese
- - Extended_UNIX_Code_Packed_Format_for_Japanese
- - ujis
- - ibm-954
-EUC-KR
- - KS_C_5601-1989
- - EUC-KR
- - 5601
- - korean
- - csKSC56011987
- - windows-949
- - KSC_5601
- - windows-949-2000
- - ms949
- - csEUCKR
- - iso-ir-149
- - KS_C_5601-1987
-GBK
- - EUC-CN
- - csISO58GB231280
- - chinese
- - csGB2312
- - CP936
- - GBK
- - gb2312-1980
- - windows-936
- - MS936
- - windows-936-2000
- - GB2312
- - iso-ir-58
- - GB_2312-80
-HZ-GB-2312
- - HZ
- - HZ-GB-2312
-ISO-2022-JP
- - csISO2022JP
- - ISO-2022-JP
-ISO-8859-1
- - 819
- - ISO-8859-1
- - csISOLatin1
- - cp819
- - l1
- - iso-ir-100
- - 8859_1
- - ibm-819
- - IBM819
- - latin1
- - ISO_8859-1:1987
-ISO-8859-10
- - ISO-8859-10
- - latin6
- - iso-8859_10-1998
- - csISOLatin6
- - iso-ir-157
- - l6
- - ISO_8859-10:1992
-ISO-8859-13
- - ibm-921_P100-1995
- - ISO-8859-13
- - 921
- - windows-28603
- - cp921
- - 8859_13
- - ibm-921
-ISO-8859-14
- - latin8
- - ISO-8859-14
- - iso-ir-199
- - l8
- - iso-celtic
- - iso-8859_14-1998
- - ISO_8859-14:1998
-ISO-8859-15
- - ibm-923
- - csisolatin0
- - ISO-8859-15
- - csisolatin9
- - windows-28605
- - latin0
- - l9
- - iso8859_15_fdis
- - cp923
- - Latin-9
- - ibm-923_P100-1998
- - 923
- - 8859_15
-ISO-8859-16
- - latin10
- - iso-8859_16-2001
- - ISO_8859-16:2001
- - ISO-8859-16
- - iso-ir-226
- - l10
-ISO-8859-2
- - ISO-8859-2
- - ibm-912
- - ibm-912_P100-1995
- - csISOLatin2
- - l2
- - iso-ir-101
- - 8859_2
- - 912
- - cp912
- - windows-28592
- - latin2
- - ISO_8859-2:1987
-ISO-8859-3
- - ISO-8859-3
- - ibm-913
- - csISOLatin3
- - l3
- - 8859_3
- - 913
- - ibm-913_P100-2000
- - cp913
- - iso-ir-109
- - ISO_8859-3:1988
- - windows-28593
- - latin3
-ISO-8859-4
- - windows-28594
- - latin4
- - ISO-8859-4
- - ibm-914
- - iso-ir-110
- - ibm-914_P100-1995
- - csISOLatin4
- - l4
- - 8859_4
- - 914
- - ISO_8859-4:1988
- - cp914
-ISO-8859-5
- - cp915
- - windows-28595
- - ISO-8859-5
- - ibm-915
- - iso-ir-144
- - ibm-915_P100-1995
- - csISOLatinCyrillic
- - cyrillic
- - 8859_5
- - ISO_8859-5:1988
- - 915
-ISO-8859-6
- - 1089
- - windows-28596
- - ASMO-708
- - ibm-1089_P100-1995
- - arabic
- - ISO-8859-6-E
- - cp1089
- - ISO-8859-6-I
- - ISO-8859-6
- - ibm-1089
- - ECMA-114
- - iso-ir-127
- - ISO_8859-6:1987
- - csISOLatinArabic
- - 8859_6
-ISO-8859-7
- - greek
- - ibm-9005_X110-2007
- - csISOLatinGreek
- - windows-28597
- - sun_eu_greek
- - ibm-9005
- - ISO-8859-7
- - greek8
- - ISO_8859-7:1987
- - iso-ir-126
- - ELOT_928
- - ECMA-118
-ISO-8859-8
- - ISO-8859-8-I
- - windows-28598
- - ibm-5012
- - ISO-8859-8
- - ISO_8859-8:1988
- - iso-ir-138
- - ibm-5012_P100-1999
- - 8859_8
- - csISOLatinHebrew
- - ISO-8859-8-E
- - hebrew
-ISO-8859-9
- - windows-28599
- - csISOLatin5
- - l5
- - cp920
- - ibm-920_P100-1995
- - latin5
- - 920
- - ISO-8859-9
- - iso-ir-148
- - ISO_8859-9:1989
- - ECMA-128
- - ibm-920
- - 8859_9
-KOI8-R
- - windows-20866
- - ibm-878
- - ibm-878_P100-1996
- - koi8
- - KOI8-R
- - cp878
- - csKOI8R
-macintosh
- - csMacintosh
- - macintosh
- - windows-10000
- - macos-0_2-10.2
- - mac
-SCSU
- - SCSU
- - ibm-1212
- - ibm-1213
-Shift_JIS
- - sjis
- - ibm-943_P15A-2003
- - csShiftJIS
- - windows-31j
- - IBM-943C
- - cp932
- - windows-932
- - ms932
- - x-sjis
- - Shift_JIS
- - pck
- - cp943c
- - csWindows31J
- - x-ms-cp932
- - ibm-943_VSUB_VPUA
- - MS_Kanji
- - ibm-943
-TIS-620
- - ibm-9066
- - TIS-620
- - eucTH
- - cp874
- - tis620.2533
- - ibm-874
- - ibm-874_P100-1995
-US-ASCII
- - IBM367
- - iso_646.irv:1983
- - csASCII
- - US-ASCII
- - ascii7
- - cp367
- - windows-20127
- - ASCII
- - ANSI_X3.4-1986
- - 646
- - ISO646-US
- - ANSI_X3.4-1968
- - iso-ir-6
- - ibm-367
- - ISO_646.irv:1991
- - us
-UTF-16
- - ucs-2
- - UTF-16
- - csUnicode
- - unicode
- - ibm-1204
- - ISO-10646-UCS-2
- - ibm-1205
-UTF-16BE
- - x-utf-16be
- - ibm-61955
- - ibm-61956
- - UTF16_BigEndian
- - windows-1201
- - cp1200
- - UTF-16BE
- - cp1201
- - ibm-17584
- - ibm-17585
- - ibm-21680
- - ibm-21681
- - ibm-13488
- - ibm-1200
- - ibm-13489
- - ibm-25776
- - ibm-1201
- - ibm-25777
-UTF-16LE
- - UTF16_LittleEndian
- - UTF-16LE
- - windows-1200
- - ibm-13490
- - ibm-13491
- - ibm-17586
- - ibm-17587
- - ibm-21682
- - x-utf-16le
- - ibm-21683
- - ibm-1202
- - ibm-25778
- - ibm-1203
- - ibm-25779
-UTF-32
- - ISO-10646-UCS-4
- - UTF-32
- - ucs-4
- - ibm-1236
- - ibm-1237
- - csUCS4
-UTF-32BE
- - UTF32_BigEndian
- - UTF-32BE
- - ibm-1232
- - ibm-1233
-UTF-32LE
- - UTF32_LittleEndian
- - ibm-1234
- - ibm-1235
- - UTF-32LE
-UTF-7
- - UTF-7
- - windows-65000
-UTF-8
- - ibm-17593
- - ibm-1208
- - UTF-8
- - ibm-1209
- - cp1208
- - ibm-13496
- - ibm-13497
- - windows-65001
- - ibm-5304
- - ibm-5305
- - ibm-17592
-windows-1250
- - windows-1250
- - cp1250
- - ibm-5346
- - ibm-5346_P100-1998
-windows-1251
- - ANSI1251
- - windows-1251
- - cp1251
- - ibm-5347
- - ibm-5347_P100-1998
-windows-1252
- - windows-1252
- - cp1252
- - ibm-5348
- - ibm-5348_P100-1997
-windows-1253
- - ibm-5349_P100-1998
- - windows-1253
- - cp1253
- - ibm-5349
-windows-1254
- - ibm-5350
- - ibm-5350_P100-1998
- - windows-1254
- - cp1254
-windows-1255
- - ibm-9447_P100-2002
- - ibm-9447
- - windows-1255
- - cp1255
-windows-1256
- - ibm-9448_X100-2005
- - ibm-9448
- - windows-1256
- - cp1256
-windows-1257
- - cp1257
- - ibm-9449_P100-2002
- - ibm-9449
- - windows-1257
-windows-1258
- - cp1258
- - ibm-5354
- - ibm-5354_P100-1998
- - windows-1258
-x-gsm-03.38-2000
- - gsm-03.38-2000
- - GSM0338
-x-ibm-1383_P110-1999
- - ibm-eucCN
- - ibm-1383
- - hp15CN
- - cp1383
- - ibm-1383_P110-1999
- - 1383
- - ibm-1383_VPUA
-x-IMAP-mailbox-name
- - IMAP-mailbox-name
-x-iscii-be
- - iscii-bng
- - windows-57003
- - windows-57006
- - x-iscii-as
- - x-iscii-be
-x-iscii-de
- - ibm-4902
- - iscii-dev
- - windows-57002
- - x-iscii-de
-x-iscii-gu
- - windows-57010
- - x-iscii-gu
- - iscii-guj
-x-iscii-ka
- - windows-57008
- - iscii-knd
- - x-iscii-ka
-x-iscii-ma
- - iscii-mlm
- - windows-57009
- - x-iscii-ma
-x-iscii-or
- - iscii-ori
- - windows-57007
- - x-iscii-or
-x-iscii-pa
- - iscii-gur
- - windows-57011
- - x-iscii-pa
-x-iscii-ta
- - x-iscii-ta
- - windows-57004
- - iscii-tml
-x-iscii-te
- - windows-57005
- - x-iscii-te
- - iscii-tlg
-x-iso-8859_11-2001
- - ISO-8859-11
- - iso-8859_11-2001
- - thai8
-x-UTF16_OppositeEndian
- - UTF16_OppositeEndian
-x-UTF16_PlatformEndian
- - UTF16_PlatformEndian
-x-UTF32_OppositeEndian
- - UTF32_OppositeEndian
-x-UTF32_PlatformEndian
- - UTF32_PlatformEndian
- */
-}
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/api/javax/xml/parsers/AllTests.java b/luni/src/test/java/tests/api/javax/xml/parsers/AllTests.java
index 282fd3e..6771ea5 100644
--- a/luni/src/test/java/tests/api/javax/xml/parsers/AllTests.java
+++ b/luni/src/test/java/tests/api/javax/xml/parsers/AllTests.java
@@ -18,7 +18,6 @@
import junit.framework.Test;
import junit.framework.TestSuite;
-import org.apache.harmony.xml.ExpatParserTest;
/**
* This is autogenerated source file. Includes tests for package tests.api.javax.xml.parsers;
@@ -35,8 +34,6 @@
suite.addTestSuite(ParserConfigurationExceptionTest.class);
suite.addTestSuite(SAXParserFactoryTest.class);
suite.addTestSuite(SAXParserTest.class);
- // TODO Move ExpatParser to impl tests package
- // suite.addTestSuite(ExpatParserTest.class);
// $JUnit-END$
return suite;
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/java/tests/luni/AllTestsIo.java b/luni/src/test/java/tests/luni/AllTestsIo.java
index 010916c..41b4d51 100644
--- a/luni/src/test/java/tests/luni/AllTestsIo.java
+++ b/luni/src/test/java/tests/luni/AllTestsIo.java
@@ -30,13 +30,11 @@
TestRunner.main(new String[] { AllTestsIo.class.getName() });
}
- public static final Test suite() {
+ public static Test suite() {
TestSuite suite = new TestSuite("Tests for java.io");
suite.addTest(tests.api.java.io.AllTests.suite());
- suite.addTest(org.apache.harmony.luni.tests.java.io.AllTests.suite());
-
return suite;
}
}
diff --git a/luni/src/test/java/tests/nio/AllTests.java b/luni/src/test/java/tests/nio/AllTests.java
deleted file mode 100644
index 92de0ca..0000000
--- a/luni/src/test/java/tests/nio/AllTests.java
+++ /dev/null
@@ -1,35 +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.nio;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Test suite that includes all tests for the Math project.
- */
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All Math test suites");
- // $JUnit-BEGIN$
- suite.addTest(org.apache.harmony.nio.tests.java.nio.AllTests.suite());
- suite.addTest(org.apache.harmony.nio.tests.java.nio.channels.AllTests.suite());
- suite.addTest(org.apache.harmony.nio.tests.java.nio.channels.spi.AllTests.suite());
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/nio_char/AllTests.java b/luni/src/test/java/tests/nio_char/AllTests.java
index ba6b82c..ce7ea8f 100644
--- a/luni/src/test/java/tests/nio_char/AllTests.java
+++ b/luni/src/test/java/tests/nio_char/AllTests.java
@@ -28,7 +28,6 @@
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.nio_char.tests.java.nio.charset.AllTests.suite());
suite.addTest(org.apache.harmony.nio_char.tests.java.nio.charset.spi.AllTests.suite());
- suite.addTest(tests.api.java.nio.charset.AllTests.suite());
// $JUnit-END$
return suite;
}
diff --git a/luni/src/test/java/tests/xml/AllTests.java b/luni/src/test/java/tests/xml/AllTests.java
index 2e12a59..8fd8096 100644
--- a/luni/src/test/java/tests/xml/AllTests.java
+++ b/luni/src/test/java/tests/xml/AllTests.java
@@ -40,7 +40,6 @@
// suite.addTest(tests.api.org.w3c.dom.AllTests.suite());
// END android-changed
suite.addTest(tests.org.w3c.dom.AllTests.suite());
- suite.addTest(org.apache.harmony.xml.AllTests.suite());
suite.addTest(org.kxml2.io.AllTests.suite());
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/dalvik/system/CloseGuardTester.java b/support/src/test/java/libcore/dalvik/system/CloseGuardTester.java
new file mode 100644
index 0000000..4ed59a2
--- /dev/null
+++ b/support/src/test/java/libcore/dalvik/system/CloseGuardTester.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.dalvik.system;
+
+import dalvik.system.CloseGuard;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Handler;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+import junit.framework.Assert;
+
+public final class CloseGuardTester implements Closeable {
+
+ private final List<LogRecord> logRecords = new CopyOnWriteArrayList<LogRecord>();
+ private final Logger logger = Logger.getLogger(CloseGuard.class.getName());
+
+ private final Handler logWatcher = new Handler() {
+ @Override public void close() {}
+ @Override public void flush() {}
+ @Override public void publish(LogRecord record) {
+ logRecords.add(record);
+ }
+ };
+
+ public CloseGuardTester() {
+ /*
+ * Collect immediately before we start monitoring the CloseGuard logs.
+ * This lowers the chance that we'll report an unrelated leak.
+ */
+ System.gc();
+ System.runFinalization();
+ logger.addHandler(logWatcher);
+ }
+
+ public void assertEverythingWasClosed() {
+ System.gc();
+ System.runFinalization();
+
+ if (!logRecords.isEmpty()) {
+ // print the log records with the output of this test
+ for (LogRecord leak : logRecords) {
+ new ConsoleHandler().publish(leak);
+ }
+ Assert.fail("CloseGuard detected unclosed resources!");
+ }
+ }
+
+ @Override public void close() throws IOException {
+ Logger.getLogger(CloseGuard.class.getName()).removeHandler(logWatcher);
+ }
+}
diff --git a/support/src/test/java/libcore/java/security/StandardNames.java b/support/src/test/java/libcore/java/security/StandardNames.java
index 452634c..21456af 100644
--- a/support/src/test/java/libcore/java/security/StandardNames.java
+++ b/support/src/test/java/libcore/java/security/StandardNames.java
@@ -53,6 +53,7 @@
public static final String SECURITY_PROVIDER_NAME = (IS_RI) ? "SUN" : "BC";
public static final String KEY_MANAGER_FACTORY_DEFAULT = (IS_RI) ? "SunX509" : "X509";
+ public static final String TRUST_MANAGER_FACTORY_DEFAULT = (IS_RI) ? "PKIX" : "X509";
/**
* A map from algorithm type (e.g. Cipher) to a set of algorithms (e.g. AES, DES, ...)
@@ -451,32 +452,32 @@
static {
// Note these are added in priority order as defined by RI 6 documentation.
- // Android currently does not support Elliptic Curve or Diffie-Hellman
+ // Android currently does not support Elliptic Curve
addBoth( "SSL_RSA_WITH_RC4_128_MD5");
addBoth( "SSL_RSA_WITH_RC4_128_SHA");
addBoth( "TLS_RSA_WITH_AES_128_CBC_SHA");
addBoth( "TLS_RSA_WITH_AES_256_CBC_SHA");
- addNeither("TLS_ECDH_ECDSA_WITH_RC4_128_SHA");
- addNeither("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA");
- addNeither("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
- addNeither("TLS_ECDH_RSA_WITH_RC4_128_SHA");
- addNeither("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA");
- addNeither("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA");
- addNeither("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA");
- addNeither("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA");
- addNeither("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA");
- addNeither("TLS_ECDHE_RSA_WITH_RC4_128_SHA");
- addNeither("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
- addNeither("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
+ addRi( "TLS_ECDH_ECDSA_WITH_RC4_128_SHA");
+ addRi( "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA");
+ addRi( "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
+ addRi( "TLS_ECDH_RSA_WITH_RC4_128_SHA");
+ addRi( "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA");
+ addRi( "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA");
+ addRi( "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA");
+ addRi( "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA");
+ addRi( "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA");
+ addRi( "TLS_ECDHE_RSA_WITH_RC4_128_SHA");
+ addRi( "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
+ addRi( "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");
addBoth( "TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
addBoth( "TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
addBoth( "TLS_DHE_DSS_WITH_AES_128_CBC_SHA");
addBoth( "TLS_DHE_DSS_WITH_AES_256_CBC_SHA");
addBoth( "SSL_RSA_WITH_3DES_EDE_CBC_SHA");
- addNeither("TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA");
- addNeither("TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA");
- addNeither("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA");
- addNeither("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA");
+ addRi( "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA");
+ addRi( "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA");
+ addRi( "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA");
+ addRi( "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA");
addBoth( "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
addBoth( "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA");
addBoth( "SSL_RSA_WITH_DES_CBC_SHA");
@@ -488,34 +489,34 @@
addBoth( "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
addBoth( "SSL_RSA_WITH_NULL_MD5");
addBoth( "SSL_RSA_WITH_NULL_SHA");
- addNeither("TLS_ECDH_ECDSA_WITH_NULL_SHA");
- addNeither("TLS_ECDH_RSA_WITH_NULL_SHA");
- addNeither("TLS_ECDHE_ECDSA_WITH_NULL_SHA");
- addNeither("TLS_ECDHE_RSA_WITH_NULL_SHA");
+ addRi( "TLS_ECDH_ECDSA_WITH_NULL_SHA");
+ addRi( "TLS_ECDH_RSA_WITH_NULL_SHA");
+ addRi( "TLS_ECDHE_ECDSA_WITH_NULL_SHA");
+ addRi( "TLS_ECDHE_RSA_WITH_NULL_SHA");
addBoth( "SSL_DH_anon_WITH_RC4_128_MD5");
addBoth( "TLS_DH_anon_WITH_AES_128_CBC_SHA");
addBoth( "TLS_DH_anon_WITH_AES_256_CBC_SHA");
addBoth( "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA");
addBoth( "SSL_DH_anon_WITH_DES_CBC_SHA");
- addNeither("TLS_ECDH_anon_WITH_RC4_128_SHA");
- addNeither("TLS_ECDH_anon_WITH_AES_128_CBC_SHA");
- addNeither("TLS_ECDH_anon_WITH_AES_256_CBC_SHA");
- addNeither("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA");
+ addRi( "TLS_ECDH_anon_WITH_RC4_128_SHA");
+ addRi( "TLS_ECDH_anon_WITH_AES_128_CBC_SHA");
+ addRi( "TLS_ECDH_anon_WITH_AES_256_CBC_SHA");
+ addRi( "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA");
addBoth( "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5");
addBoth( "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
- addNeither("TLS_ECDH_anon_WITH_NULL_SHA");
+ addRi( "TLS_ECDH_anon_WITH_NULL_SHA");
// Android does not have Keberos support
- addRi ("TLS_KRB5_WITH_RC4_128_SHA");
- addRi ("TLS_KRB5_WITH_RC4_128_MD5");
- addRi ("TLS_KRB5_WITH_3DES_EDE_CBC_SHA");
- addRi ("TLS_KRB5_WITH_3DES_EDE_CBC_MD5");
- addRi ("TLS_KRB5_WITH_DES_CBC_SHA");
- addRi ("TLS_KRB5_WITH_DES_CBC_MD5");
- addRi ("TLS_KRB5_EXPORT_WITH_RC4_40_SHA");
- addRi ("TLS_KRB5_EXPORT_WITH_RC4_40_MD5");
- addRi ("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA");
- addRi ("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5");
+ addRi( "TLS_KRB5_WITH_RC4_128_SHA");
+ addRi( "TLS_KRB5_WITH_RC4_128_MD5");
+ addRi( "TLS_KRB5_WITH_3DES_EDE_CBC_SHA");
+ addRi( "TLS_KRB5_WITH_3DES_EDE_CBC_MD5");
+ addRi( "TLS_KRB5_WITH_DES_CBC_SHA");
+ addRi( "TLS_KRB5_WITH_DES_CBC_MD5");
+ addRi( "TLS_KRB5_EXPORT_WITH_RC4_40_SHA");
+ addRi( "TLS_KRB5_EXPORT_WITH_RC4_40_MD5");
+ addRi( "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA");
+ addRi( "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5");
// Dropped
addNeither("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");
@@ -553,7 +554,7 @@
unknownCipherSuites.add(cipherSuite);
}
}
- assertEquals(Collections.EMPTY_SET, unknownCipherSuites);
+ assertEquals("Unknown cipher suites", Collections.EMPTY_SET, unknownCipherSuites);
return remainingCipherSuites;
}
@@ -564,7 +565,7 @@
*/
public static void assertSupportedCipherSuites(Set<String> expected, String[] cipherSuites) {
Set<String> remainingCipherSuites = assertValidCipherSuites(expected, cipherSuites);
- assertEquals(Collections.EMPTY_SET, remainingCipherSuites);
+ assertEquals("Extra cipher suites", Collections.EMPTY_SET, remainingCipherSuites);
assertEquals(expected.size(), cipherSuites.length);
}
@@ -587,7 +588,7 @@
unknownProtocols.add(protocol);
}
}
- assertEquals(Collections.EMPTY_SET, unknownProtocols);
+ assertEquals("Unknown protocols", Collections.EMPTY_SET, unknownProtocols);
return remainingProtocols;
}
@@ -598,7 +599,7 @@
*/
public static void assertSupportedProtocols(Set<String> expected, String[] protocols) {
Set<String> remainingProtocols = assertValidProtocols(expected, protocols);
- assertEquals(Collections.EMPTY_SET, remainingProtocols);
+ assertEquals("Extra protocols", Collections.EMPTY_SET, remainingProtocols);
assertEquals(expected.size(), protocols.length);
}
}
diff --git a/support/src/test/java/libcore/java/security/TestKeyStore.java b/support/src/test/java/libcore/java/security/TestKeyStore.java
index 346149e..bd5815b 100644
--- a/support/src/test/java/libcore/java/security/TestKeyStore.java
+++ b/support/src/test/java/libcore/java/security/TestKeyStore.java
@@ -24,6 +24,7 @@
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore;
+import java.security.Principal;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
@@ -257,9 +258,19 @@
x509c = null;
} else {
// 1.) we make the keys
- int keysize = 1024;
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm);
- kpg.initialize(keysize, new SecureRandom());
+ int keySize;
+ if (keyAlgorithm.equals("RSA")) {
+ keySize = 512;
+ } else if (keyAlgorithm.equals("DSA")) {
+ keySize = 512;
+ } else if (keyAlgorithm.startsWith("EC")) {
+ keySize = 192;
+ } else {
+ throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
+ }
+ kpg.initialize(keySize, new SecureRandom());
+
KeyPair kp = kpg.generateKeyPair();
privateKey = (PrivateKey)kp.getPrivate();
PublicKey publicKey = (PublicKey)kp.getPublic();
@@ -343,6 +354,15 @@
}
/**
+ * Return the only private key in a TestKeyStore for the given
+ * algorithm. Throws IllegalStateException if there are are more
+ * or less than one.
+ */
+ public PrivateKeyEntry getPrivateKey(String algorithm) {
+ return privateKey(keyStore, keyPassword, algorithm);
+ }
+
+ /**
* Return the only private key in a keystore for the given
* algorithm. Throws IllegalStateException if there are are more
* or less than one.
@@ -380,8 +400,7 @@
*/
public static KeyStore createClient(KeyStore caKeyStore) {
try {
- KeyStore clientKeyStore = clientKeyStore = KeyStore.getInstance("BKS");
- clientKeyStore.load(null, null);
+ KeyStore clientKeyStore = createKeyStore();
copySelfSignedCertificates(clientKeyStore, caKeyStore);
return clientKeyStore;
} catch (RuntimeException e) {
@@ -392,9 +411,11 @@
}
/**
- * Copy self-signed certifcates from one key store to another
+ * Copy self-signed certifcates from one key store to another.
+ * Returns true if successful, false if no match found.
*/
- public static void copySelfSignedCertificates(KeyStore dst, KeyStore src) throws Exception {
+ public static boolean copySelfSignedCertificates(KeyStore dst, KeyStore src) throws Exception {
+ boolean copied = false;
for (String alias: Collections.list(src.aliases())) {
if (!src.isCertificateEntry(alias)) {
continue;
@@ -404,7 +425,29 @@
continue;
}
dst.setCertificateEntry(alias, cert);
+ copied = true;
}
+ return copied;
+ }
+
+ /**
+ * Copy named certifcates from one key store to another.
+ * Returns true if successful, false if no match found.
+ */
+ public static boolean copyCertificate(Principal subject, KeyStore dst, KeyStore src)
+ throws Exception {
+ for (String alias: Collections.list(src.aliases())) {
+ if (!src.isCertificateEntry(alias)) {
+ continue;
+ }
+ X509Certificate cert = (X509Certificate)src.getCertificate(alias);
+ if (!cert.getSubjectDN().equals(subject)) {
+ continue;
+ }
+ dst.setCertificateEntry(alias, cert);
+ return true;
+ }
+ return false;
}
/**
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
*/
diff --git a/support/src/test/java/tests/http/DefaultResponseCache.java b/support/src/test/java/tests/http/DefaultResponseCache.java
index c922726..912e879 100644
--- a/support/src/test/java/tests/http/DefaultResponseCache.java
+++ b/support/src/test/java/tests/http/DefaultResponseCache.java
@@ -24,13 +24,19 @@
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.ResponseCache;
+import java.net.SecureCacheResponse;
import java.net.URI;
import java.net.URLConnection;
+import java.security.Principal;
+import java.security.cert.Certificate;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLPeerUnverifiedException;
/**
* Cache all responses in memory by URI.
@@ -111,10 +117,12 @@
};
private final Map<String, List<String>> headers;
private final URI uri;
+ private final CacheResponse cacheResponse;
- private Entry(URI uri, URLConnection conn) {
+ private Entry(URI uri, URLConnection connection) {
this.uri = uri;
- this.headers = deepCopy(conn.getHeaderFields());
+ this.headers = deepCopy(connection.getHeaderFields());
+ this.cacheResponse = connectionToCacheResponse(connection);
}
public CacheRequest asRequest() {
@@ -136,17 +144,79 @@
};
}
- public CacheResponse asResponse() {
- return new CacheResponse() {
- @Override public InputStream getBody() throws IOException {
+ private CacheResponse connectionToCacheResponse(URLConnection connection) {
+ if (!(connection instanceof HttpsURLConnection)) {
+ return new CacheResponse() {
+ @Override public InputStream getBody() {
+ return new ByteArrayInputStream(getBytes());
+ }
+ @Override public Map<String, List<String>> getHeaders() {
+ return deepCopy(headers);
+ }
+ };
+ }
+
+ HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
+
+ /*
+ * Retrieve the fields eagerly to avoid needing a strong reference
+ * to the connection. We do acrobatics for the two methods that can
+ * throw so that the cache response also throws.
+ */
+ List<Certificate> serverCertificatesNonFinal = null;
+ try {
+ serverCertificatesNonFinal = Arrays.asList(httpsConnection.getServerCertificates());
+ } catch (SSLPeerUnverifiedException ignored) {
+ }
+ Principal peerPrincipalNonFinal = null;
+ try {
+ peerPrincipalNonFinal = httpsConnection.getPeerPrincipal();
+ } catch (SSLPeerUnverifiedException ignored) {
+ }
+ final String cipherSuite = httpsConnection.getCipherSuite();
+ final Certificate[] localCertificates = httpsConnection.getLocalCertificates();
+ final List<Certificate> serverCertificates = serverCertificatesNonFinal;
+ final Principal peerPrincipal = peerPrincipalNonFinal;
+ final Principal localPrincipal = httpsConnection.getLocalPrincipal();
+
+ return new SecureCacheResponse() {
+ @Override public InputStream getBody() {
return new ByteArrayInputStream(getBytes());
}
- @Override public Map<String, List<String>> getHeaders() throws IOException {
+ @Override public Map<String, List<String>> getHeaders() {
return deepCopy(headers);
}
+ @Override public String getCipherSuite() {
+ return cipherSuite;
+ }
+ @Override public List<Certificate> getLocalCertificateChain() {
+ return localCertificates != null
+ ? Arrays.asList(localCertificates.clone())
+ : null;
+ }
+ @Override public List<Certificate> getServerCertificateChain()
+ throws SSLPeerUnverifiedException {
+ if (serverCertificates == null) {
+ throw new SSLPeerUnverifiedException(null);
+ }
+ return new ArrayList<Certificate>(serverCertificates);
+ }
+ @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+ if (peerPrincipal == null) {
+ throw new SSLPeerUnverifiedException(null);
+ }
+ return peerPrincipal;
+ }
+ @Override public Principal getLocalPrincipal() {
+ return localPrincipal;
+ }
};
}
+ public CacheResponse asResponse() {
+ return cacheResponse;
+ }
+
public byte[] getBytes() {
return bytesOut.toByteArray();
}
diff --git a/support/src/test/java/tests/http/MockWebServer.java b/support/src/test/java/tests/http/MockWebServer.java
index d790399..312e6e5 100644
--- a/support/src/test/java/tests/http/MockWebServer.java
+++ b/support/src/test/java/tests/http/MockWebServer.java
@@ -242,6 +242,8 @@
socket = sslSocketFactory.createSocket(
raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
((SSLSocket) socket).setUseClientMode(false);
+ openClientSockets.add(socket);
+ openClientSockets.remove(raw);
} else {
socket = raw;
}
@@ -256,8 +258,8 @@
in.close();
out.close();
- raw.close();
- openClientSockets.remove(raw);
+ socket.close();
+ openClientSockets.remove(socket);
return null;
}
diff --git a/support/src/test/java/tests/util/ClassLoaderBuilder.java b/support/src/test/java/tests/util/ClassLoaderBuilder.java
new file mode 100644
index 0000000..8fd18c2
--- /dev/null
+++ b/support/src/test/java/tests/util/ClassLoaderBuilder.java
@@ -0,0 +1,131 @@
+/*
+ * 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 tests.util;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Builds a configured class loader. The constructed class loader can load a
+ * private copy of a class in addition to the copy in the application class
+ * loader. It can also refuse to load a class altogether, even if that class
+ * exists on the classpath.
+ */
+public final class ClassLoaderBuilder {
+ private ClassLoader parent = ClassLoaderBuilder.class.getClassLoader();
+ private final Set<String> prefixesToNotInherit = new HashSet<String>();
+ private final Set<String> prefixesToLoad = new HashSet<String>();
+
+ public ClassLoaderBuilder parent(ClassLoader parent) {
+ this.parent = parent;
+ return this;
+ }
+
+ /**
+ * @param classNamePrefix the prefix of classes that can be loaded by both
+ * the constructed class loader and the application class loader.
+ */
+ public ClassLoaderBuilder withPrivateCopy(String classNamePrefix) {
+ prefixesToLoad.add(classNamePrefix);
+ return this;
+ }
+
+ /**
+ * @param classNamePrefix the prefix of classes that will not be loaded by
+ * this class loader. Attempts to load such classes will fail at runtime
+ * with a NoClassDefFoundError.
+ */
+ public ClassLoaderBuilder without(String classNamePrefix) {
+ prefixesToNotInherit.add(classNamePrefix);
+ return this;
+ }
+
+ public ClassLoader build() {
+ // make a defensive copy in case this builder is reused!
+ final Set<String> prefixesToNotInherit = new HashSet<String>(this.prefixesToNotInherit);
+ final Set<String> prefixesToLoad = new HashSet<String>(this.prefixesToLoad);
+
+ /*
+ * To load two copies of a given class in the VM, we end up creating two
+ * new class loaders: a bridge class loader and a leaf class loader.
+ *
+ * The bridge class loader is a child of the application class loader.
+ * It never loads any classes. All it does is decide when to delegate to
+ * the application class loader (which has a copy of everything) and
+ * when to fail.
+ *
+ * The leaf class loader is a child of the bridge class loader. It
+ * uses the same classpath as the application class loader. It loads
+ * anything that its parent failed on.
+ */
+
+ ClassLoader bridge = new ClassLoader(parent) {
+ @Override protected Class<?> loadClass(String className, boolean resolve)
+ throws ClassNotFoundException {
+ for (String prefix : prefixesToLoad) {
+ if (className.startsWith(prefix)) {
+ /* ClassNotFoundException causes the child loader to load the class. */
+ throw new ClassNotFoundException();
+ }
+ }
+
+ for (String prefix : prefixesToNotInherit) {
+ if (className.startsWith(prefix)) {
+ /* NoClassDefFoundError prevents the class from being loaded at all. */
+ throw new NoClassDefFoundError();
+ }
+ }
+
+ return super.loadClass(className, resolve);
+ }
+ };
+
+ try {
+ // first try to create a PathClassLoader for a dalvik VM...
+ String classPath = System.getProperty("java.class.path");
+ return (ClassLoader) Class.forName("dalvik.system.PathClassLoader")
+ .getConstructor(String.class, ClassLoader.class)
+ .newInstance(classPath, bridge);
+ } catch (Exception ignored) {
+ }
+
+ // fall back to a URLClassLoader on a JVM
+ List<URL> classpath = new ArrayList<URL>();
+ classpath.addAll(classpathToUrls("java.class.path"));
+ classpath.addAll(classpathToUrls("sun.boot.class.path"));
+ return new URLClassLoader(classpath.toArray(new URL[classpath.size()]), bridge);
+ }
+
+ private List<URL> classpathToUrls(String propertyName) {
+ try {
+ String classpath = System.getProperty(propertyName);
+ List<URL> result = new ArrayList<URL>();
+ for (String pathElement : classpath.split(File.pathSeparator)) {
+ result.add(new File(pathElement).toURI().toURL());
+ }
+ return result;
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}