Merge commit '995a3842' into manualmerge
Conflicts:
expectations/knownfailures.txt
Change-Id: Iee137d2c0c5e8bfa6994258f5fab8e07caeb86e1
diff --git a/Android.mk b/Android.mk
index 421e01d..14b1e32 100644
--- a/Android.mk
+++ b/Android.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 2207d3e..1618f1b 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
# Copyright (C) 2007 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/Docs.mk b/Docs.mk
index 13eddec..1f75a5e 100644
--- a/Docs.mk
+++ b/Docs.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
# List of libcore directories to include in documentation.
# Shared between libcore and frameworks/base.
diff --git a/NativeCode.mk b/NativeCode.mk
index b5cc769..d4960c5 100644
--- a/NativeCode.mk
+++ b/NativeCode.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
# Copyright (C) 2007 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -101,7 +102,7 @@
LOCAL_MODULE := libjavacore
ifneq ($(TARGET_SIMULATOR),true)
-LOCAL_C_INCLUDES += external/stlport/stlport bionic/ bionic/libstdc++/include
+LOCAL_C_INCLUDES += external/stlport/stlport bionic/ bionic/libstdc++/include
LOCAL_SHARED_LIBRARIES += libstlport
endif
diff --git a/dalvik/src/main/java/dalvik/system/DexFile.java b/dalvik/src/main/java/dalvik/system/DexFile.java
index 4156f12..13d067c 100644
--- a/dalvik/src/main/java/dalvik/system/DexFile.java
+++ b/dalvik/src/main/java/dalvik/system/DexFile.java
@@ -74,10 +74,6 @@
* access rights missing for opening it
*/
public DexFile(String fileName) throws IOException {
- String wantDex = System.getProperty("android.vm.dexfile", "false");
- if (!wantDex.equals("true"))
- throw new UnsupportedOperationException("No dex in this VM");
-
mCookie = openDexFile(fileName, null, 0);
mFileName = fileName;
guard.open("close");
@@ -95,13 +91,7 @@
* @param flags
* Enable optional features.
*/
- private DexFile(String sourceName, String outputName, int flags)
- throws IOException {
-
- String wantDex = System.getProperty("android.vm.dexfile", "false");
- if (!wantDex.equals("true"))
- throw new UnsupportedOperationException("No dex in this VM");
-
+ private DexFile(String sourceName, String outputName, int flags) throws IOException {
mCookie = openDexFile(sourceName, outputName, flags);
mFileName = sourceName;
guard.open("close");
diff --git a/dalvik/src/main/java/dalvik/system/TouchDex.java b/dalvik/src/main/java/dalvik/system/TouchDex.java
deleted file mode 100644
index 53cd00c..0000000
--- a/dalvik/src/main/java/dalvik/system/TouchDex.java
+++ /dev/null
@@ -1,147 +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 dalvik.system;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-/**
- * Induces optimization/verification of a set of DEX files.
- *
- * @hide
- */
-public class TouchDex {
-
- /**
- * Forks a process, makes sure the DEX files are prepared, and returns
- * when everything is finished.
- * <p>
- * The filenames must be the same as will be used when the files are
- * actually opened, because the dalvik-cache filename is based upon
- * this filename. (The absolute path to the JAR/ZIP/APK should work.)
- *
- * @param dexFiles a colon-separated list of DEX files.
- * @return zero on success
- */
- public static int start(String dexFiles) {
- return trampoline(dexFiles, System.getProperty("java.boot.class.path"));
- }
-
- /**
- * This calls fork() and then, in the child, calls cont(dexFiles).
- *
- * @param dexFiles Colon-separated list of DEX files.
- * @return zero on success
- */
- native private static int trampoline(String dexFiles, String bcp);
-
- /**
- * The entry point for the child process. args[0] can be a colon-separated
- * path list, or "-" to read from stdin.
- * <p>
- * Alternatively, if we're invoked directly from the command line we
- * just start here (skipping the fork/exec stuff).
- *
- * @param args command line args
- */
- public static void main(String[] args) {
-
- if ("-".equals(args[0])) {
- BufferedReader in = new BufferedReader(
- new InputStreamReader(System.in), 256);
-
- String line;
- try {
- while ((line = in.readLine()) != null) {
- prepFiles(line);
- }
- } catch (IOException ex) {
- throw new RuntimeException ("Error processing stdin");
- }
- } else {
- prepFiles(args[0]);
- }
-
- System.out.println(" Prep complete");
- }
-
-
- private static String expandDirectories(String dexPath) {
- String[] parts = dexPath.split(":");
- StringBuilder outPath = new StringBuilder(dexPath.length());
-
- // A filename filter accepting *.jar and *.apk
- FilenameFilter filter = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith(".jar") || name.endsWith(".apk");
- }
- };
-
- for (String part: parts) {
- File f = new File(part);
-
- if (f.isFile()) {
- outPath.append(part);
- outPath.append(':');
- } else if (f.isDirectory()) {
- String[] filenames = f.list(filter);
-
- if (filenames == null) {
- System.err.println("I/O error with directory: " + part);
- continue;
- }
-
- for (String filename: filenames) {
- outPath.append(part);
- outPath.append(File.separatorChar);
- outPath.append(filename);
- outPath.append(':');
- }
- } else {
- System.err.println("File not found: " + part);
- }
- }
-
-
- return outPath.toString();
- }
-
- private static void prepFiles(String dexPath) {
-
- System.out.println(" Prepping: " + dexPath);
-
- TouchDexLoader loader
- = new TouchDexLoader(expandDirectories(dexPath), null);
-
- try {
- /* By looking for a nonexistent class, we'll trick TouchDexLoader
- * into trying to load something from every file on dexPath,
- * optimizing all of them as a side-effect.
- *
- * The optimization happens implicitly in the VM the first time
- * someone tries to load a class from an unoptimized dex file.
- */
- loader.loadClass("com.google.NonexistentClassNeverFound");
- throw new RuntimeException("nonexistent class loaded?!");
- } catch (ClassNotFoundException cnfe) {
- //System.out.println("got expected dnfe");
- }
- }
-}
diff --git a/dalvik/src/main/java/dalvik/system/TouchDexLoader.java b/dalvik/src/main/java/dalvik/system/TouchDexLoader.java
deleted file mode 100644
index e5f9743..0000000
--- a/dalvik/src/main/java/dalvik/system/TouchDexLoader.java
+++ /dev/null
@@ -1,315 +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 dalvik.system;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.RandomAccessFile;
-import java.net.MalformedURLException;
-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
- * substantially smaller, since we don't need most of this.
- */
-class TouchDexLoader extends ClassLoader {
-
- private String path;
-
- /*
- * Parallel arrays for jar/apk files.
- *
- * (could stuff these into an object and have a single array;
- * improves clarity but adds overhead)
- */
- private final String[] mPaths;
- private final File[] mFiles;
- private final ZipFile[] mZips;
- private final DexFile[] mDexs;
-
- /**
- * Native library path.
- */
- private final String[] mLibPaths;
-
- /**
- * Create a ClassLoader that finds files in the specified path.
- */
- public TouchDexLoader(String path, ClassLoader parent) {
- super(parent);
-
- if (path == null)
- throw new NullPointerException();
-
- this.path = path;
-
- mPaths = path.split(":");
- //System.out.println("TouchDexLoader: " + mPaths);
- mFiles = new File[mPaths.length];
- mZips = new ZipFile[mPaths.length];
- mDexs = new DexFile[mPaths.length];
-
- boolean wantDex =
- System.getProperty("android.vm.dexfile", "").equals("true");
-
- /* open all Zip and DEX files up front */
- for (int i = 0; i < mPaths.length; i++) {
- //System.out.println("My path is: " + mPaths[i]);
- File pathFile = new File(mPaths[i]);
- mFiles[i] = pathFile;
-
- if (pathFile.isFile()) {
- if (false) { //--------------------
- try {
- mZips[i] = new ZipFile(pathFile);
- }
- catch (IOException ioex) {
- // expecting IOException and ZipException
- //System.out.println("Failed opening '" + archive + "': " + ioex);
- //ioex.printStackTrace();
- }
- } //--------------------
- if (wantDex) {
- /* we need both DEX and Zip, because dex has no resources */
- try {
- mDexs[i] = new DexFile(pathFile);
- }
- catch (IOException ioex) {
- System.err.println("Couldn't open " + mPaths[i]
- + " as DEX");
- }
- }
- } else {
- System.err.println("File not found: " + mPaths[i]);
- }
- }
-
- /*
- * Prep for native library loading.
- */
- String pathList = System.getProperty("java.library.path", ".");
- String pathSep = System.getProperty("path.separator", ":");
- String fileSep = System.getProperty("file.separator", "/");
-
- mLibPaths = pathList.split(pathSep);
-
- // Add a '/' to the end so we don't have to do the property lookup
- // and concatenation later.
- for (int i = 0; i < mLibPaths.length; i++) {
- if (!mLibPaths[i].endsWith(fileSep))
- mLibPaths[i] += fileSep;
- if (false)
- System.out.println("Native lib path: " + mLibPaths[i]);
- }
- }
-
- /**
- * Find the class with the specified name. None of our ancestors were
- * able to find it, so it's up to us now.
- *
- * "name" is a "binary name", e.g. "java.lang.String" or
- * "java.net.URLClassLoader$3$1".
- *
- * This method will either return a valid Class object or throw an
- * exception. Does not return null.
- */
- protected Class<?> findClass(String name) throws ClassNotFoundException
- {
- byte[] data = null;
- int i;
-
- //System.out.println("TouchDexLoader " + this + ": findClass '" + name + "'");
-
- for (i = 0; i < mPaths.length; i++) {
- //System.out.println("My path is: " + mPaths[i]);
-
- if (mDexs[i] != null) {
- String slashName = name.replace('.', '/');
- Class clazz = mDexs[i].loadClass(slashName, this);
- if (clazz != null)
- return clazz;
- } else if (mZips[i] != null) {
- String fileName = name.replace('.', '/') + ".class";
- data = loadFromArchive(mZips[i], fileName);
- } else {
- File pathFile = mFiles[i];
- if (pathFile.isDirectory()) {
- String fileName =
- mPaths[i] + "/" + name.replace('.', '/') + ".class";
- data = loadFromDirectory(fileName);
- } else {
- //System.out.println("TouchDexLoader: can't find '"
- // + mPaths[i] + "'");
- }
-
- }
-
- if (data != null) {
- //System.out.println(" found class " + name);
- int dotIndex = name.lastIndexOf('.');
- if (dotIndex != -1) {
- String packageName = name.substring(0, dotIndex);
- synchronized (this) {
- Package packageObj = getPackage(packageName);
- if (packageObj == null) {
- definePackage(packageName, null, null,
- null, null, null, null, null);
- }
- }
- }
-
- return defineClass(name, data, 0, data.length);
- }
- }
-
- throw new ClassNotFoundException(name + " in loader " + this);
- }
-
- /*
- * Find a resource by name. This could be in a directory or in an
- * archive.
- */
- protected URL findResource(String name) {
- byte[] data = null;
- int i;
-
- //System.out.println("TouchDexLoader: findResource '" + name + "'");
-
- for (i = 0; i < mPaths.length; i++) {
- File pathFile = mFiles[i];
- ZipFile zip = mZips[i];
- if (zip != null) {
- if (isInArchive(zip, name)) {
- //System.out.println(" found " + name + " in " + pathFile);
- // Create URL correctly - was XXX, new code should be ok.
- try {
- return new URL("jar:file://" + pathFile + "!/" + name);
- }
- catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- } else if (pathFile.isDirectory()) {
- File dataFile = new File(mPaths[i] + "/" + name);
- if (dataFile.exists()) {
- //System.out.println(" found resource " + name);
- // Create URL correctly - was XXX, new code should be ok.
- try {
- return new URL("file:" + name);
- }
- catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- } else if (pathFile.isFile()) {
- } else {
- System.err.println("TouchDexLoader: can't find '"
- + mPaths[i] + "'");
- }
- }
-
- return null;
- }
-
-
- /*
- * Load the contents of a file from a file in a directory.
- *
- * Returns null if the class wasn't found.
- */
- private byte[] loadFromDirectory(String path) {
- try {
- return IoUtils.readFileAsByteArray(path);
- } catch (IOException ex) {
- System.err.println("Error reading from " + path);
- // swallow it, return null instead
- return null;
- }
- }
-
- /*
- * Load a class from a file in an archive. We currently assume that
- * the file is a Zip archive.
- *
- * Returns null if the class wasn't found.
- */
- private byte[] loadFromArchive(ZipFile zip, String name) {
- ZipEntry entry;
-
- entry = zip.getEntry(name);
- if (entry == null)
- return null;
-
- ByteArrayOutputStream byteStream;
- InputStream stream;
- int count;
-
- /*
- * Copy the data out of the stream. Because we got the ZipEntry
- * from a ZipFile, the uncompressed size is known, and we can set
- * the initial size of the ByteArrayOutputStream appropriately.
- */
- try {
- stream = zip.getInputStream(entry);
- byteStream = new ByteArrayOutputStream((int) entry.getSize());
- byte[] buf = new byte[4096];
- while ((count = stream.read(buf)) > 0)
- byteStream.write(buf, 0, count);
-
- stream.close();
- }
- catch (IOException ioex) {
- //System.out.println("Failed extracting '" + archive + "': " +ioex);
- return null;
- }
-
- //System.out.println(" loaded from Zip");
- return byteStream.toByteArray();
- }
-
- /*
- * Figure out if "name" is a member of "archive".
- */
- private boolean isInArchive(ZipFile zip, String name) {
- return zip.getEntry(name) != null;
- }
-
- /**
- * Find a native library.
- *
- * Return the full pathname of the first appropriate-looking file
- * we find.
- */
- protected String findLibrary(String libname) {
- String fileName = System.mapLibraryName(libname);
- for (int i = 0; i < mLibPaths.length; i++) {
- String pathName = mLibPaths[i] + fileName;
- File test = new File(pathName);
-
- if (test.exists())
- return pathName;
- }
-
- return null;
- }
-}
diff --git a/dalvik/src/main/java/dalvik/system/VMRuntime.java b/dalvik/src/main/java/dalvik/system/VMRuntime.java
index 373dd03..f570197 100644
--- a/dalvik/src/main/java/dalvik/system/VMRuntime.java
+++ b/dalvik/src/main/java/dalvik/system/VMRuntime.java
@@ -47,6 +47,27 @@
}
/**
+ * Returns a copy of the VM's command-line property settings.
+ * These are in the form "name=value" rather than "-Dname=value".
+ */
+ public native String[] properties();
+
+ /**
+ * Returns the VM's boot class path.
+ */
+ public native String bootClassPath();
+
+ /**
+ * Returns the VM's class path.
+ */
+ public native String classPath();
+
+ /**
+ * Returns the VM's version.
+ */
+ public native String vmVersion();
+
+ /**
* Gets the current ideal heap utilization, represented as a number
* between zero and one. After a GC happens, the Dalvik heap may
* be resized so that (size of live objects) / (size of heap) is
@@ -104,10 +125,11 @@
}
/**
- * Requests that the virtual machine collect available memory,
- * and collects any SoftReferences that are not strongly-reachable.
+ * This method exists for binary compatibility. It used to
+ * perform a garbage collection that cleared SoftReferences.
*/
- public native void gcSoftReferences();
+ @Deprecated
+ public void gcSoftReferences() {}
/**
* Does not return until any pending finalizers have been called.
diff --git a/dalvik/src/main/native/dalvik_system_TouchDex.cpp b/dalvik/src/main/native/dalvik_system_TouchDex.cpp
deleted file mode 100644
index 719ac3c..0000000
--- a/dalvik/src/main/native/dalvik_system_TouchDex.cpp
+++ /dev/null
@@ -1,269 +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.
- */
-
-/*
- * Bit of code to wrap DEX force-updating with a fork() call.
- */
-
-#define LOG_TAG "TouchDex"
-#include "JNIHelp.h"
-
-#include "cutils/properties.h"
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <signal.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/time.h>
-#include <assert.h>
-#include <errno.h>
-
-#define JAVA_PACKAGE "dalvik/system"
-
-#ifndef HAVE_ANDROID_OS
-# define BASE_DIR "/work/device/out/linux-x86-debug-sim"
-#else
-# define BASE_DIR ""
-#endif
-
-namespace android {
-
-// fwd
-static void logProcStatus(pid_t pid);
-
-
-/*
- * private static int trampoline(String dexFiles, String bcp)
- */
-static jint dalvik_system_TouchDex_trampoline(JNIEnv* env,
- jclass, jstring dexFilesStr, jstring bcpStr)
-{
-#ifndef HAVE_ANDROID_OS
- /* don't do this on simulator -- gdb goes "funny" in goobuntu */
- return 0;
-#endif
-
- const int kMinTimeout = 900; // 90 seconds
- const char* bcp;
- const char* dexFiles;
- static const char* kExecFile = BASE_DIR "/system/bin/dalvikvm";
- //static const char* kDebugArg =
- // "-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n";
- static const char* kBcpArgName = "-Xbootclasspath:";
- static const char* kClassName = "dalvik.system.TouchDex";
- static const char* kExecMode = "-Xint";
- static const int argc = 7;
- const char* argv[argc+1];
- const char* kVerifyArg;
- const char* kDexOptArg;
- int timeoutMult;
- pid_t pid;
- struct timeval startWhen, endWhen;
- char propBuf[PROPERTY_VALUE_MAX];
- char execModeBuf[PROPERTY_VALUE_MAX + sizeof("-X")];
- bool verifyJava = true;
-
- property_get("dalvik.vm.verify-bytecode", propBuf, "");
- if (strcmp(propBuf, "true") == 0) {
- verifyJava = true;
- } else if (strcmp(propBuf, "false") == 0) {
- verifyJava = false;
- } else {
- /* bad value or not defined; use default */
- }
-
- if (verifyJava) {
- kVerifyArg = "-Xverify:all";
- kDexOptArg = "-Xdexopt:verified";
- timeoutMult = 11;
- } else {
- kVerifyArg = "-Xverify:none";
- //kDexOptArg = "-Xdexopt:all";
- kDexOptArg = "-Xdexopt:verified";
- timeoutMult = 7;
- }
-
- property_get("dalvik.vm.execution-mode", propBuf, "");
- if (strncmp(propBuf, "int:", 4) == 0) {
- strcpy(execModeBuf, "-X");
- strcat(execModeBuf, propBuf);
- kExecMode = execModeBuf;
- }
-
- LOGV("TouchDex trampoline forking\n");
- gettimeofday(&startWhen, NULL);
-
- /*
- * Retrieve strings. Note we want to do this *before* the fork() -- bad
- * idea to perform Java operations in the child process (not all threads
- * get carried over to the new process).
- */
- bcp = env->GetStringUTFChars(bcpStr, NULL);
- dexFiles = env->GetStringUTFChars(dexFilesStr, NULL);
- if (bcp == NULL || dexFiles == NULL) {
- LOGE("Bad values for bcp=%p dexFiles=%p\n", bcp, dexFiles);
- abort();
- }
-
- pid = fork();
- if (pid < 0) {
- LOGE("fork failed: %s", strerror(errno));
- return -1;
- }
-
- if (pid == 0) {
- /* child */
- char* bcpArg;
-
- LOGV("TouchDex trampoline in child\n");
-
- bcpArg = (char*) malloc(strlen(bcp) + strlen(kBcpArgName) +1);
- strcpy(bcpArg, kBcpArgName);
- strcat(bcpArg, bcp);
-
- argv[0] = kExecFile;
- argv[1] = bcpArg;
- argv[2] = kVerifyArg;
- argv[3] = kDexOptArg;
- argv[4] = kExecMode;
- argv[5] = kClassName;
- argv[6] = dexFiles;
- argv[7] = NULL;
-
- //LOGI("Calling execv with args:\n");
- //for (int i = 0; i < argc; i++)
- // LOGI(" %d: '%s'\n", i, argv[i]);
-
- execv(kExecFile, (char* const*) argv);
- free(bcpArg);
-
- LOGE("execv '%s' failed: %s\n", kExecFile, strerror(errno));
- exit(1);
- } else {
- int cc, count, dexCount, timeout;
- int result = -1;
- const char* cp;
-
- /*
- * Adjust the timeout based on how many DEX files we have to
- * process. Larger DEX files take longer, so this is a crude
- * approximation at best.
- *
- * We need this for http://b/issue?id=836771, which can leave us
- * stuck waiting for a long time even if there is no work to be done.
- *
- * This is currently being (ab)used to convert single files, which
- * sort of spoils the timeout calculation. We establish a minimum
- * timeout for single apps.
- *
- * The timeout calculation doesn't work at all right when a
- * directory is specified. So the minimum is now a minute. At
- * this point it's probably safe to just remove the timeout.
- *
- * The timeout is in 1/10ths of a second.
- */
- dexCount = 1;
- cp = dexFiles;
- while (*++cp != '\0') {
- if (*cp == ':')
- dexCount++;
- }
- timeout = timeoutMult * dexCount;
- if (timeout < kMinTimeout)
- timeout = kMinTimeout;
-
- env->ReleaseStringUTFChars(bcpStr, bcp);
- env->ReleaseStringUTFChars(dexFilesStr, dexFiles);
-
-
- LOGD("TouchDex parent waiting for pid=%d (timeout=%.1fs)\n",
- (int) pid, timeout / 10.0);
- for (count = 0; count < timeout; count++) {
- /* waitpid doesn't take a timeout, so poll and sleep */
- cc = waitpid(pid, &result, WNOHANG);
- if (cc < 0) {
- LOGE("waitpid(%d) failed: %s", (int) pid, strerror(errno));
- return -1;
- } else if (cc == 0) {
- usleep(100000); /* 0.1 sec */
- } else {
- /* success! */
- break;
- }
- }
-
- if (count == timeout) {
- /* note kill(0) returns 0 if the pid is a zombie */
- LOGE("timed out waiting for %d; kill(0) returns %d\n",
- (int) pid, kill(pid, 0));
- logProcStatus(pid);
- } else {
- LOGV("TouchDex done after %d iterations (kill(0) returns %d)\n",
- count, kill(pid, 0));
- }
-
- gettimeofday(&endWhen, NULL);
- long long start = startWhen.tv_sec * 1000000 + startWhen.tv_usec;
- long long end = endWhen.tv_sec * 1000000 + endWhen.tv_usec;
-
- LOGI("Dalvik-cache prep: status=0x%04x, finished in %dms\n",
- result, (int) ((end - start) / 1000));
-
- if (WIFEXITED(result))
- return WEXITSTATUS(result);
- else
- return result;
- }
-}
-
-/*
- * Dump the contents of /proc/<pid>/status to the log file.
- */
-static void logProcStatus(pid_t pid)
-{
- char localBuf[256];
- FILE* fp;
-
- sprintf(localBuf, "/proc/%d/status", (int) pid);
- fp = fopen(localBuf, "r");
- if (fp == NULL) {
- LOGI("Unable to open '%s'\n", localBuf);
- return;
- }
-
- LOGI("Contents of %s:\n", localBuf);
- while (true) {
- fgets(localBuf, sizeof(localBuf), fp);
- if (ferror(fp) || feof(fp))
- break;
- LOGI(" %s", localBuf);
- }
-
- fclose(fp);
-}
-
-static JNINativeMethod gMethods[] = {
- { "trampoline", "(Ljava/lang/String;Ljava/lang/String;)I",
- (void*) dalvik_system_TouchDex_trampoline },
-};
-int register_dalvik_system_TouchDex(JNIEnv* env) {
- return jniRegisterNativeMethods(env, JAVA_PACKAGE "/TouchDex", gMethods, NELEM(gMethods));
-}
-
-}; // namespace android
diff --git a/dalvik/src/main/native/sub.mk b/dalvik/src/main/native/sub.mk
index 27d4c9c..4adc8a1 100644
--- a/dalvik/src/main/native/sub.mk
+++ b/dalvik/src/main/native/sub.mk
@@ -1,9 +1,9 @@
+# -*- mode: makefile -*-
# This file is included by the top-level libcore Android.mk.
# It's not a normal makefile, so we don't include CLEAR_VARS
# or BUILD_*_LIBRARY.
LOCAL_SRC_FILES := \
- dalvik_system_TouchDex.cpp \
org_apache_harmony_dalvik_NativeTestTarget.cpp
#LOCAL_C_INCLUDES +=
@@ -15,4 +15,3 @@
#LOCAL_SHARED_LIBRARIES +=
#LOCAL_STATIC_LIBRARIES +=
-
diff --git a/expectations/brokentests.txt b/expectations/brokentests.txt
index 213b519..ae509fe 100644
--- a/expectations/brokentests.txt
+++ b/expectations/brokentests.txt
@@ -3,6 +3,25 @@
*/
[
{
+ description: "This test and testGetKeepAlive have been failing in our continuous build recently.",
+ names: [
+ "libcore.java.net.URLConnectionTest#testConnectTimeouts",
+ "libcore.java.net.URLConnectionTest#testGetKeepAlive"
+ ],
+ bug: 3441111
+},
+{
+ description: "on the RI, writing the two halves of the surrogate pair in separate writes
+ is an error because the CharsetEncoder doesn't remember it's half-way through a
+ surrogate pair across the two calls!",
+ result: EXEC_FAILED,
+ names: [
+ "libcore.java.nio.charset.CharsetEncoderTest#testCharsetEncoderSurrogatesBrokenByDesign_IGNORE_RI",
+ "libcore.java.nio.charset.CharsetEncoderTest#testCharsetEncoderSurrogatesBrokenByDesign_REPLACE_RI",
+ "libcore.java.nio.charset.CharsetEncoderTest#testCharsetEncoderSurrogatesBrokenByDesign_REPORT_RI"
+ ]
+},
+{
description: "We're retiring the security manager. Unfortunately, tests all over the place
need to check that they're secure, so they all fail when we refuse to install
a security manager. This suppresses all of these failures.",
diff --git a/expectations/knownfailures.txt b/expectations/knownfailures.txt
index 625a19f..6b577d4 100644
--- a/expectations/knownfailures.txt
+++ b/expectations/knownfailures.txt
@@ -3,6 +3,27 @@
*/
[
{
+ name: "libcore.java.lang.StringTest#testCaseMapping_en_US",
+ bug: 3387655
+},
+{
+ name: "org.apache.harmony.crypto.tests.javax.crypto.CipherTest#testGetMaxAllowedKeyLength",
+ bug: 3387688
+},
+{
+ name: "libcore.java.io.FileTest#test_emptyFilename",
+ bug: 3387758
+},
+{
+ description: "Turkish dotless i behaves differently on dalvik vs. RI",
+ names: [
+ "libcore.java.lang.StringTest#testChangeCase_en_US",
+ "libcore.java.lang.StringTest#testEqualsIgnoreCase_en_US",
+ "libcore.java.lang.StringTest#testEqualsIgnoreCase_tr_TR"
+ ],
+ bug: 3325799
+},
+{
description: "KxmlPullParser doesn't enforce top-level document element",
names: [
"libcore.xml.KxmlPullParserDtdTest#testDoctypeInDocumentElement",
@@ -125,7 +146,7 @@
{
description: "finalize() called on objects whose constructor didn't complete normally",
name: "libcore.java.lang.SystemTest#testBackFromTheDead",
- bug: 2645458
+ bug: 3342343
},
{
description: "DecimalFormat is limited to 127 digits",
@@ -174,7 +195,10 @@
},
{
description: "Double.parseDouble().toString does wrong rounding",
- name: "libcore.java.lang.OldDoubleTest#test_parseDoubleLjava_lang_String",
+ names: [
+ "libcore.java.lang.OldDoubleTest#test_parseDoubleLjava_lang_String",
+ "libcore.java.lang.DoubleTest.testParseLargestSubnormalDoublePrecision"
+ ],
bug: 1607938
},
{
@@ -232,10 +256,6 @@
modes: [ "host" ]
},
{
- name: "libcore.java.net.URLConnectionTest#testConnectTimeouts",
- bug: 3032900
-},
-{
description: "Fails in CTS but passes under run-core-tests",
result: EXEC_FAILED,
name: "libcore.java.io.OldFileTest#test_deleteOnExit"
@@ -259,12 +279,16 @@
description: "Fails in CTS but passes under run-core-tests",
result: EXEC_FAILED,
names: [
- "libcore.java.lang.OldRuntimeTest#test_traceMethodCalls",
"tests.api.java.net.MulticastSocketTest#test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface",
"tests.api.java.util.FormatterTest#test_formatLjava_lang_String$Ljava_lang_Object_DateTimeConversion"
]
},
{
+ description: "Runtime.getRuntime().traceMethodCalls(true) doesn't return on the host, fails in CTS",
+ bug: 3447964,
+ name: "libcore.java.lang.OldRuntimeTest#test_traceMethodCalls"
+},
+{
description: "It's not allowed to pass null as parent class loader to a new ClassLoader anymore. Maybe we need
to change URLClassLoader to allow this? It's not specified.",
result: EXEC_FAILED,
@@ -512,7 +536,7 @@
},
{
description: "not supported",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
"tests.java.sql.DatabaseMetaDataNotSupportedTest#test_locatorsUpdateCopy",
"tests.java.sql.DatabaseMetaDataNotSupportedTest#test_supportsANSI92EntryLevelSQL",
@@ -523,445 +547,445 @@
"tests.java.sql.DatabaseMetaDataNotSupportedTest#test_supportsSubqueriesInIns",
"tests.java.sql.DatabaseMetaDataNotSupportedTest#test_supportsTransactions",
"tests.java.sql.DatabaseMetaDataNotSupportedTest#test_usesLocalFiles",
- "tests.sql.ConnectionTest#testClearWarnings",
- "tests.sql.ConnectionTest#testCreateStatementIntIntIntNotSupported"
+ "libcore.java.sql.OldConnectionTest#testClearWarnings",
+ "libcore.java.sql.OldConnectionTest#testCreateStatementIntIntIntNotSupported"
]
},
{
description: "Scrolling on a forward only RS not allowed. conn.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ConnectionTest#testCreateStatement_int_int"
+ bug: 3403706,
+ name: "libcore.java.sql.OldConnectionTest#testCreateStatement_int_int"
},
{
description: "not supported",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ConnectionTest#testGetCatalog",
- "tests.sql.ConnectionTest#testGetHoldability"
+ "libcore.java.sql.OldConnectionTest#testGetCatalog",
+ "libcore.java.sql.OldConnectionTest#testGetHoldability"
]
},
{
description: "conn.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ConnectionTest#testGetMetaData"
+ bug: 3403706,
+ name: "libcore.java.sql.OldConnectionTest#testGetMetaData"
},
{
description: "not supported",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ConnectionTest#testGetTransactionIsolation",
- "tests.sql.ConnectionTest#testGetWarnings"
+ "libcore.java.sql.OldConnectionTest#testGetTransactionIsolation",
+ "libcore.java.sql.OldConnectionTest#testGetWarnings"
]
},
{
description: "conn.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ConnectionTest#testIsReadOnly"
+ bug: 3403706,
+ name: "libcore.java.sql.OldConnectionTest#testIsReadOnly"
},
{
description: "not supported",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ConnectionTest#testPrepareStatementNotSupported",
- "tests.sql.ConnectionTest#testPrepareStatement_String_int"
+ "libcore.java.sql.OldConnectionTest#testPrepareStatementNotSupported",
+ "libcore.java.sql.OldConnectionTest#testPrepareStatement_String_int"
]
},
{
description: "conn.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ConnectionTest#testSetAutoCommit"
+ bug: 3403706,
+ name: "libcore.java.sql.OldConnectionTest#testSetAutoCommit"
},
{
description: "not supported",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ConnectionTest#testSetHoldability",
- "tests.sql.ConnectionTest#testSetReadOnly"
+ "libcore.java.sql.OldConnectionTest#testSetHoldability",
+ "libcore.java.sql.OldConnectionTest#testSetReadOnly"
]
},
{
description: "First Exception test fails: parameters not cleared.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testClearParameters"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testClearParameters"
},
{
description: "preparedStatement.execute() does not return false on update.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testExecute"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testExecute"
},
{
description: "it is not possible to invoke the method getMetaData on a PreparedStatement object before it is
executed: got NullPointerException.Test passes on RI.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testGetMetaData"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testGetMetaData"
},
{
description: "preparedStatement.execute() does not return false on update.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetBigDecimal"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetBigDecimal"
},
{
description: "exception test fails",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.PreparedStatementTest#testSetBoolean",
- "tests.sql.PreparedStatementTest#testSetByte"
+ "libcore.java.sql.OldPreparedStatementTest#testSetBoolean",
+ "libcore.java.sql.OldPreparedStatementTest#testSetByte"
]
},
{
description: "preparedStatement.execute() does not return false on update.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetBytes"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetBytes"
},
{
description: "preparedStatement.execute() does not return false on update. Setting a data for a declared
INTEGER should throw Exception",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetDate_int_Date"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetDate_int_Date"
},
{
description: "preparedStatement.execute() does not return false on update.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetDate_int_Date_Calendar"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetDate_int_Date_Calendar"
},
{
description: "exception test fails",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.PreparedStatementTest#testSetDouble",
- "tests.sql.PreparedStatementTest#testSetFloat",
- "tests.sql.PreparedStatementTest#testSetInt",
- "tests.sql.PreparedStatementTest#testSetLong",
- "tests.sql.PreparedStatementTest#testSetObject_int_Object"
+ "libcore.java.sql.OldPreparedStatementTest#testSetDouble",
+ "libcore.java.sql.OldPreparedStatementTest#testSetFloat",
+ "libcore.java.sql.OldPreparedStatementTest#testSetInt",
+ "libcore.java.sql.OldPreparedStatementTest#testSetLong",
+ "libcore.java.sql.OldPreparedStatementTest#testSetObject_int_Object"
]
},
{
description: "Fails for Types.DATE",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.PreparedStatementTest#testSetObject_int_Object_int",
- "tests.sql.PreparedStatementTest#testSetObject_int_Object_int_int"
+ "libcore.java.sql.OldPreparedStatementTest#testSetObject_int_Object_int",
+ "libcore.java.sql.OldPreparedStatementTest#testSetObject_int_Object_int_int"
]
},
{
description: "exception test fails",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.PreparedStatementTest#testSetShort",
- "tests.sql.PreparedStatementTest#testSetString_charField",
- "tests.sql.PreparedStatementTest#testSetString_longTextField"
+ "libcore.java.sql.OldPreparedStatementTest#testSetShort",
+ "libcore.java.sql.OldPreparedStatementTest#testSetString_charField",
+ "libcore.java.sql.OldPreparedStatementTest#testSetString_longTextField"
]
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetString_tinyTextField"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetString_tinyTextField"
},
{
description: "preparedStatement.execute() does not return False on update.",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetTime_int_Time_Calendar"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetTime_int_Time_Calendar"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.PreparedStatementTest#testSetTimeint_Time"
+ bug: 3403706,
+ name: "libcore.java.sql.OldPreparedStatementTest#testSetTimeint_Time"
},
{
description: "preparedStatement.execute() does not return false on update.",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.PreparedStatementTest#testSetTimestampIntTimestampCalendar",
- "tests.sql.PreparedStatementTest#testSetTimestamp_int_Timestamp"
+ "libcore.java.sql.OldPreparedStatementTest#testSetTimestampIntTimestampCalendar",
+ "libcore.java.sql.OldPreparedStatementTest#testSetTimestamp_int_Timestamp"
]
},
{
description: "last assertion fails: invalid conversion. Test passes on RI",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ResultSetGetterTests#testGetBytesStringBinary",
- "tests.sql.ResultSetGetterTests#testGetBytesStringVarbinary"
+ "libcore.java.sql.OldResultSetGetterTests#testGetBytesStringBinary",
+ "libcore.java.sql.OldResultSetGetterTests#testGetBytesStringVarbinary"
]
},
{
description: "Wrong value returned for Long: java.lang.String (VARCHAR)",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetMetaData"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetMetaData"
},
{
description: "Wrong value returned for Long: java.lang.String",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ResultSetGetterTests#testGetObjectInt",
- "tests.sql.ResultSetGetterTests#testGetObjectString"
+ "libcore.java.sql.OldResultSetGetterTests#testGetObjectInt",
+ "libcore.java.sql.OldResultSetGetterTests#testGetObjectString"
]
},
{
description: "If there is no current row 0 must be returned. res.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetRow"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetRow"
},
{
description: "According to spec info.getStatement should return null but an exception is thrown: stale result
set.",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetStatement"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetStatement"
},
{
description: "getTime should return Time value for a TIMESTAMP type but returns null",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetTimeInt"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetTimeInt"
},
{
description: "getTime on TIMESTAMP value fails: returns null",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetTimeIntCalendar"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetTimeIntCalendar"
},
{
description: "getTime should return a Time value for a TIMESTAMP type but returns null",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetTimeString"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetTimeString"
},
{
description: "getTime on TIMESTAMP value fails: returns null",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetTimeStringCalendar"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetTimeStringCalendar"
},
{
description: "res.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetGetterTests#testGetType"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetGetterTests#testGetType"
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetCatalogName"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetCatalogName"
},
{
description: "SQLException checking test fails",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetColumnCount"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetColumnCount"
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetColumnDisplaySize"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetColumnDisplaySize"
},
{
description: "Column label has format TABLE.COLUMN expected: COLUMN",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ResultSetMetaDataTest#testGetColumnLabel",
- "tests.sql.ResultSetMetaDataTest#testGetColumnName"
+ "libcore.java.sql.OldResultSetMetaDataTest#testGetColumnLabel",
+ "libcore.java.sql.OldResultSetMetaDataTest#testGetColumnName"
]
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetPrecision"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetPrecision"
},
{
description: "Not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetScale"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetScale"
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetSchema"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetSchema"
},
{
description: "For int = 0, exception expected",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetMetaDataTest#testGetTableName"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetMetaDataTest#testGetTableName"
},
{
description: "not supported",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ResultSetMetaDataTest#testIsCaseSensitive",
- "tests.sql.ResultSetMetaDataTest#testIsCurrency",
- "tests.sql.ResultSetMetaDataTest#testIsDefinitlyWritable",
- "tests.sql.ResultSetMetaDataTest#testIsNullable",
- "tests.sql.ResultSetMetaDataTest#testIsReadOnly",
- "tests.sql.ResultSetMetaDataTest#testIsSearchable",
- "tests.sql.ResultSetMetaDataTest#testIsSigned",
- "tests.sql.ResultSetMetaDataTest#testIsWritable",
- "tests.sql.ResultSetMetaDataTest#testisAutoIncrement"
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsCaseSensitive",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsCurrency",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsDefinitlyWritable",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsNullable",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsReadOnly",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsSearchable",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsSigned",
+ "libcore.java.sql.OldResultSetMetaDataTest#testIsWritable",
+ "libcore.java.sql.OldResultSetMetaDataTest#testisAutoIncrement"
]
},
{
description: "res.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testAfterLast"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testAfterLast"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testBeforeFirst"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testBeforeFirst"
},
{
description: "Not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testClearWarnings"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testClearWarnings"
},
{
description: "Resultset.close() does not wrap up",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ResultSetTest#testClose1",
- "tests.sql.ResultSetTest#testNext"
+ "libcore.java.sql.OldResultSetTest#testClose1",
+ "libcore.java.sql.OldResultSetTest#testNext"
]
},
{
description: "no exception is thrown when moving cursor backwards on forward only statement",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testRelative"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testRelative"
},
{
description: "Scrollable resultSet. Not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testRelativeScrollableResultSet"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testRelativeScrollableResultSet"
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testUpdateObjectStringObject"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testUpdateObjectStringObject"
},
{
description: "Feature not supported",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testUpdateStringStringString"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testUpdateStringStringString"
},
{
description: "the default tests, and exception tests fail.",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testWasNull"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testWasNull"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.ResultSetTest#testtestFirst",
- "tests.sql.ResultSetTest#testtestIsAfterLast"
+ "libcore.java.sql.OldResultSetTest#testtestFirst",
+ "libcore.java.sql.OldResultSetTest#testtestIsAfterLast"
]
},
{
description: "In Second code block assertion fails. statement. close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testtestIsBeforeFirst"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testtestIsBeforeFirst"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testtestIsFirst"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testtestIsFirst"
},
{
description: "Second block first assertion fails. Is Last should evaluate true if the row on which the cursor
is actually provides a result.statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testtestIsLast"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testtestIsLast"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.ResultSetTest#testtestLast"
+ bug: 3403706,
+ name: "libcore.java.sql.OldResultSetTest#testtestLast"
},
{
description: "Bug in implementation of cancel: Does not fulfill spec.",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testCancel"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testCancel"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testClose"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testClose"
},
{
description: "Return value wrong for queries below.",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testExecute"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testExecute"
},
{
description: "always returns 1 for no. of updates",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testExecuteBatch"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testExecuteBatch"
},
{
description: "Does throw an exception on non select statement.",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testExecuteQuery_String"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testExecuteQuery_String"
},
{
description: "Spec is not precise enough: should be: number of rows affected. eg. to be consistent for deletes:
'delete from s1;' should be different from 'delete from s1 where c1 = 1;'",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testExecuteUpdate_String"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testExecuteUpdate_String"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
- "tests.sql.StatementTest#testGetConnection",
- "tests.sql.StatementTest#testGetFetchDirection",
- "tests.sql.StatementTest#testGetFetchSize"
+ "libcore.java.sql.OldStatementTest#testGetConnection",
+ "libcore.java.sql.OldStatementTest#testGetFetchDirection",
+ "libcore.java.sql.OldStatementTest#testGetFetchSize"
]
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetMoreResults"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetMoreResults"
},
{
description: "An other value is returned than was set (X * 1000)",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetQueryTimeout"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetQueryTimeout"
},
{
description: "Does not return null on update count > 0 (not a select statement)",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetResultSet"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetResultSet"
},
{
description: "Not supported",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetResultSetConcurrency"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetResultSetConcurrency"
},
{
description: "Test for default value fails",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetResultSetHoldability"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetResultSetHoldability"
},
{
description: "not fully supported",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetResultSetType"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetResultSetType"
},
{
description: "statement.close() does not wrap up",
- result: EXEC_FAILED,
- name: "tests.sql.StatementTest#testGetUpdateCount"
+ bug: 3403706,
+ name: "libcore.java.sql.OldStatementTest#testGetUpdateCount"
},
{
description: "Handshake Status is never finished. NPE in ClientSessionContext$HostAndPort.hashCode() when host
is null",
- result: EXEC_FAILED,
+ bug: 3403706,
name: "tests.api.javax.net.ssl.SSLEngineTest#testHandshake"
},
{
description: "org.apache.harmony.xnet.provider.jsse.SSLEngineImpl#getDelegatedTask() throws NPE instead of
returning null",
- result: EXEC_FAILED,
+ bug: 3403706,
name: "tests.api.javax.net.ssl.SSLEngineTest#test_getDelegatedTask"
},
{
description: "Fixed in DonutBurger, boundary checks missing",
- result: EXEC_FAILED,
+ bug: 3403706,
name: "tests.api.javax.net.ssl.SSLEngineTest#test_unwrap_02"
},
{
description: "Fixed on DonutBurger, Wrong Exception thrown",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
"tests.api.javax.net.ssl.SSLEngineTest#test_unwrap_03",
"tests.api.javax.net.ssl.SSLEngineTest#test_unwrap_04",
@@ -973,12 +997,12 @@
},
{
description: "Fixed in DonutBurger, boundary checks missing",
- result: EXEC_FAILED,
+ bug: 3403706,
name: "tests.api.javax.net.ssl.SSLEngineTest#test_wrap_02"
},
{
description: "Fixed on DonutBurger, Wrong Exception thrown",
- result: EXEC_FAILED,
+ bug: 3403706,
names: [
"tests.api.javax.net.ssl.SSLEngineTest#test_wrap_04",
"tests.api.javax.net.ssl.SSLEngineTest#test_wrap_ByteBuffer$ByteBuffer_03",
@@ -988,7 +1012,7 @@
{
description: "ManagerFactoryParameters object is not supported and InvalidAlgorithmParameterException was
thrown.",
- result: EXEC_FAILED,
+ bug: 3403706,
name: "tests.api.javax.net.ssl.TrustManagerFactory1Test#test_initLjavax_net_ssl_ManagerFactoryParameters"
},
{
@@ -1018,58 +1042,67 @@
},
{
description: "method test fails once in a while. Cannot be sure that exception is thrown in every test execution.",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testBusy_handler"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testBusy_handler"
},
{
description: "Database does not lock values",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testBusy_timeout"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testBusy_timeout"
},
{
description: "Returns wrong number for updates: returns value > 1 for select.",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testChanges"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testChanges"
},
{
description: "Aggregation function not called",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testCreate_aggregate"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testCreate_aggregate"
},
{
description: "Reason for failure unknown: Database should be locked. Specification of interrupt is scarce.",
result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testInterrupt"
+ name: "libcore.sqlite.OldDatabaseTest#testInterrupt"
},
{
description: "not supported",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testOpen_blob"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testOpen_blob"
},
{
description: "Callback never made for authorization. Results of private table are returned without further checks.",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testSet_authorizer"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testSet_authorizer"
},
{
description: "ASCII encoding does not work: a UTF encoded val is returned. Spec is not sufficient. Might be that test impl is wrong or String constructor for the ASCII encoding.",
- result: EXEC_FAILED,
- name: "tests.SQLite.DatabaseTest#testSet_encoding"
+ bug: 3403706,
+ name: "libcore.sqlite.OldDatabaseTest#testSet_encoding"
},
{
description: "db.open_blob is not supported.",
- result: EXEC_FAILED,
- name: "tests.SQLite.BlobTest#testBlob"
+ bug: 3403706,
+ name: "libcore.sqlite.OldBlobTest#testBlob"
},
{
description: "Wrong value is returned in case of a prepared statement to which a '*' bound",
- result: EXEC_FAILED,
- name: "tests.SQLite.StmtTest#testColumn_count"
+ bug: 3403706,
+ name: "libcore.sqlite.OldStmtTest#testColumn_count"
},
{
description: "ZeroBlob not supported",
- result: EXEC_FAILED,
- name: "tests.SQLite.FunctionContextTest#testSet_result_zeroblob"
+ bug: 3403706,
+ name: "libcore.sqlite.OldFunctionContextTest#testSet_result_zeroblob"
+},
+{
+ description: "SQLite test fail",
+ bug: 3403706,
+ names: [
+ "libcore.sqlite.OldDatabaseTest#testGet_tableString",
+ "libcore.sqlite.OldDatabaseTest#testGet_tableStringStringArrayTableResult",
+ "libcore.sqlite.OldStmtTest#testColumn_type"
+ ]
},
{
modes: [ "jvm" ],
diff --git a/include/ScopedStringChars.h b/include/ScopedStringChars.h
new file mode 100644
index 0000000..9f543b7
--- /dev/null
+++ b/include/ScopedStringChars.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2011 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 SCOPED_STRING_CHARS_H_included
+#define SCOPED_STRING_CHARS_H_included
+
+#include "JNIHelp.h"
+
+// A smart pointer that provides access to a jchar* given a JNI jstring.
+class ScopedStringChars {
+public:
+ ScopedStringChars(JNIEnv* env, jstring s) : mEnv(env), mString(s), mSize(0) {
+ mChars = env->GetStringChars(mString, NULL);
+ if (mChars != NULL) {
+ mSize = env->GetStringLength(mString);
+ }
+ }
+
+ ~ScopedStringChars() {
+ mEnv->ReleaseStringChars(mString, mChars);
+ }
+
+ const jchar* get() const { return mChars; }
+ const jchar& operator[](size_t n) const { return mChars[n]; }
+ size_t size() const { return mSize; }
+
+private:
+ JNIEnv* mEnv;
+ jstring mString;
+ const UChar* mChars;
+ size_t mSize;
+
+ // Disallow copy and assignment.
+ ScopedStringChars(const ScopedStringChars&);
+ void operator=(const ScopedStringChars&);
+};
+
+#endif // SCOPED_STRING_CHARS_H_included
diff --git a/luni/src/main/java/java/beans/PropertyChangeSupport.java b/luni/src/main/java/java/beans/PropertyChangeSupport.java
index 6df04c5..04f8155 100644
--- a/luni/src/main/java/java/beans/PropertyChangeSupport.java
+++ b/luni/src/main/java/java/beans/PropertyChangeSupport.java
@@ -43,9 +43,9 @@
private static final long serialVersionUID = 6401253773779951803l;
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("source", Object.class),
- new ObjectStreamField("children", Object.class),
- new ObjectStreamField("propertyChangeSupportSerializedDataVersion", int.class)
+ new ObjectStreamField("source", Object.class),
+ new ObjectStreamField("children", Object.class),
+ new ObjectStreamField("propertyChangeSupportSerializedDataVersion", int.class),
};
private transient Object sourceBean;
diff --git a/luni/src/main/java/java/io/BufferedInputStream.java b/luni/src/main/java/java/io/BufferedInputStream.java
index bfd18cf..d45595b 100644
--- a/luni/src/main/java/java/io/BufferedInputStream.java
+++ b/luni/src/main/java/java/io/BufferedInputStream.java
@@ -343,19 +343,12 @@
*/
@Override
public synchronized void reset() throws IOException {
- // BEGIN android-changed
- /*
- * These exceptions get thrown in some "normalish" circumstances,
- * so it is preferable to avoid loading up the whole big set of
- * messages just for these cases.
- */
if (buf == null) {
throw new IOException("Stream is closed");
}
if (-1 == markpos) {
throw new IOException("Mark has been invalidated.");
}
- // END android-changed
pos = markpos;
}
diff --git a/luni/src/main/java/java/io/BufferedReader.java b/luni/src/main/java/java/io/BufferedReader.java
index 0d77735..bc6b9a6 100644
--- a/luni/src/main/java/java/io/BufferedReader.java
+++ b/luni/src/main/java/java/io/BufferedReader.java
@@ -359,9 +359,6 @@
}
for (int charPos = pos; charPos < end; charPos++) {
char ch = buf[charPos];
- // BEGIN android-note
- // a switch statement may be more efficient
- // END android-note
if (ch > '\r') {
continue;
}
diff --git a/luni/src/main/java/java/io/BufferedWriter.java b/luni/src/main/java/java/io/BufferedWriter.java
index 3017065..c0af9bf 100644
--- a/luni/src/main/java/java/io/BufferedWriter.java
+++ b/luni/src/main/java/java/io/BufferedWriter.java
@@ -17,9 +17,7 @@
package java.io;
-import java.security.AccessController;
import java.util.Arrays;
-import org.apache.harmony.luni.util.PriviAction;
import org.apache.harmony.luni.util.SneakyThrow;
/**
@@ -46,8 +44,7 @@
private int pos;
- private final String lineSeparator = AccessController
- .doPrivileged(new PriviAction<String>("line.separator"));
+ private final String lineSeparator = System.getProperty("line.separator");
/**
* Constructs a new {@code BufferedWriter}, providing {@code out} with a buffer
diff --git a/luni/src/main/java/java/io/ByteArrayInputStream.java b/luni/src/main/java/java/io/ByteArrayInputStream.java
index 642ba01..0a8c453 100644
--- a/luni/src/main/java/java/io/ByteArrayInputStream.java
+++ b/luni/src/main/java/java/io/ByteArrayInputStream.java
@@ -73,9 +73,6 @@
* the number of bytes available for streaming.
*/
public ByteArrayInputStream(byte[] buf, int offset, int length) {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
this.buf = buf;
pos = offset;
mark = offset;
diff --git a/luni/src/main/java/java/io/CharArrayWriter.java b/luni/src/main/java/java/io/CharArrayWriter.java
index ea5e10e..eda56f7 100644
--- a/luni/src/main/java/java/io/CharArrayWriter.java
+++ b/luni/src/main/java/java/io/CharArrayWriter.java
@@ -206,16 +206,9 @@
if (str == null) {
throw new NullPointerException("str == null");
}
- // avoid int overflow
- // BEGIN android-changed
- // Exception priorities (in case of multiple errors) differ from
- // 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 || offset > str.length() - count) {
throw new StringIndexOutOfBoundsException(str, offset, count);
}
- // END android-changed
synchronized (lock) {
expand(count);
str.getChars(offset, offset + count, buf, this.count);
diff --git a/luni/src/main/java/java/io/EmulatedFields.java b/luni/src/main/java/java/io/EmulatedFields.java
index 580cfe3..7d71643 100644
--- a/luni/src/main/java/java/io/EmulatedFields.java
+++ b/luni/src/main/java/java/io/EmulatedFields.java
@@ -76,8 +76,7 @@
* an array of ObjectStreamFields, which describe the declared
* fields.
*/
- public EmulatedFields(ObjectStreamField[] fields,
- ObjectStreamField[] declared) {
+ public EmulatedFields(ObjectStreamField[] fields, ObjectStreamField[] declared) {
super();
// We assume the slots are already sorted in the right shape for dumping
buildSlots(fields);
@@ -145,7 +144,6 @@
*/
private ObjectSlot findSlot(String fieldName, Class<?> fieldType) {
boolean isPrimitive = fieldType != null && fieldType.isPrimitive();
-
for (int i = 0; i < slotsToSerialize.length; i++) {
ObjectSlot slot = slotsToSerialize[i];
if (slot.field.getName().equals(fieldName)) {
@@ -172,10 +170,8 @@
for (int i = 0; i < declaredFields.length; i++) {
ObjectStreamField field = declaredFields[i];
if (field.getName().equals(fieldName)) {
- if (isPrimitive ? field.getType() == fieldType
- : fieldType == null
- || field.getType().isAssignableFrom(
- fieldType)) {
+ if (isPrimitive ? fieldType == field.getType() : fieldType == null ||
+ field.getType().isAssignableFrom(fieldType)) {
ObjectSlot slot = new ObjectSlot();
slot.field = field;
slot.defaulted = true;
@@ -187,6 +183,14 @@
return null;
}
+ private ObjectSlot findMandatorySlot(String name, Class<?> type) {
+ ObjectSlot slot = findSlot(name, type);
+ if (slot == null || (type == null && slot.field.getType().isPrimitive())) {
+ throw new IllegalArgumentException("no field '" + name + "' of type " + type);
+ }
+ return slot;
+ }
+
/**
* Finds and returns the byte value of a given field named {@code name}
* in the receiver. If the field has not been assigned any value yet, the
@@ -202,15 +206,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public byte get(String name, byte defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Byte.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no byte field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Byte) slot.fieldValue)
- .byteValue();
+ public byte get(String name, byte defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, byte.class);
+ return slot.defaulted ? defaultValue : ((Byte) slot.fieldValue).byteValue();
}
/**
@@ -228,15 +226,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public char get(String name, char defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Character.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no char field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Character) slot.fieldValue)
- .charValue();
+ public char get(String name, char defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, char.class);
+ return slot.defaulted ? defaultValue : ((Character) slot.fieldValue).charValue();
}
/**
@@ -254,15 +246,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public double get(String name, double defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Double.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no double field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Double) slot.fieldValue)
- .doubleValue();
+ public double get(String name, double defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, double.class);
+ return slot.defaulted ? defaultValue : ((Double) slot.fieldValue).doubleValue();
}
/**
@@ -280,15 +266,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public float get(String name, float defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Float.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no float field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Float) slot.fieldValue)
- .floatValue();
+ public float get(String name, float defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, float.class);
+ return slot.defaulted ? defaultValue : ((Float) slot.fieldValue).floatValue();
}
/**
@@ -306,15 +286,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public int get(String name, int defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Integer.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no int field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Integer) slot.fieldValue)
- .intValue();
+ public int get(String name, int defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, int.class);
+ return slot.defaulted ? defaultValue : ((Integer) slot.fieldValue).intValue();
}
/**
@@ -332,15 +306,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public long get(String name, long defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Long.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no long field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Long) slot.fieldValue)
- .longValue();
+ public long get(String name, long defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, long.class);
+ return slot.defaulted ? defaultValue : ((Long) slot.fieldValue).longValue();
}
/**
@@ -358,13 +326,8 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public Object get(String name, Object defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, null);
- // if not initialized yet, we give the default value
- if (slot == null || slot.field.getType().isPrimitive()) {
- throw new IllegalArgumentException("no Object field '" + name + "'");
- }
+ public Object get(String name, Object defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, null);
return slot.defaulted ? defaultValue : slot.fieldValue;
}
@@ -383,15 +346,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public short get(String name, short defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Short.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no short field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Short) slot.fieldValue)
- .shortValue();
+ public short get(String name, short defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, short.class);
+ return slot.defaulted ? defaultValue : ((Short) slot.fieldValue).shortValue();
}
/**
@@ -409,15 +366,9 @@
* @throws IllegalArgumentException
* if the corresponding field can not be found.
*/
- public boolean get(String name, boolean defaultValue)
- throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Boolean.TYPE);
- // if not initialized yet, we give the default value
- if (slot == null) {
- throw new IllegalArgumentException("no boolean field '" + name + "'");
- }
- return slot.defaulted ? defaultValue : ((Boolean) slot.fieldValue)
- .booleanValue();
+ public boolean get(String name, boolean defaultValue) throws IllegalArgumentException {
+ ObjectSlot slot = findMandatorySlot(name, boolean.class);
+ return slot.defaulted ? defaultValue : ((Boolean) slot.fieldValue).booleanValue();
}
/**
@@ -433,10 +384,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, byte value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Byte.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no byte field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, byte.class);
slot.fieldValue = Byte.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -454,10 +402,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, char value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Character.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no char field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, char.class);
slot.fieldValue = Character.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -475,10 +420,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, double value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Double.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no double field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, double.class);
slot.fieldValue = Double.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -496,10 +438,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, float value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Float.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no float field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, float.class);
slot.fieldValue = Float.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -517,10 +456,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, int value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Integer.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no integer field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, int.class);
slot.fieldValue = Integer.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -538,10 +474,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, long value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Long.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no long field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, long.class);
slot.fieldValue = Long.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -563,10 +496,7 @@
if (value != null) {
valueClass = value.getClass();
}
- ObjectSlot slot = findSlot(name, valueClass);
- if (slot == null) {
- throw new IllegalArgumentException("no Object field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, valueClass);
slot.fieldValue = value;
slot.defaulted = false; // No longer default value
}
@@ -584,10 +514,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, short value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Short.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no short field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, short.class);
slot.fieldValue = Short.valueOf(value);
slot.defaulted = false; // No longer default value
}
@@ -605,10 +532,7 @@
* if the corresponding field can not be found.
*/
public void put(String name, boolean value) throws IllegalArgumentException {
- ObjectSlot slot = findSlot(name, Boolean.TYPE);
- if (slot == null) {
- throw new IllegalArgumentException("no boolean field '" + name + "'");
- }
+ ObjectSlot slot = findMandatorySlot(name, boolean.class);
slot.fieldValue = Boolean.valueOf(value);
slot.defaulted = false; // No longer default value
}
diff --git a/luni/src/main/java/java/io/EmulatedFieldsForDumping.java b/luni/src/main/java/java/io/EmulatedFieldsForDumping.java
index 9b51dc1..9cf6eae 100644
--- a/luni/src/main/java/java/io/EmulatedFieldsForDumping.java
+++ b/luni/src/main/java/java/io/EmulatedFieldsForDumping.java
@@ -200,21 +200,21 @@
for (EmulatedFields.ObjectSlot slot : emulatedFields.slots()) {
Object fieldValue = slot.getFieldValue();
Class<?> type = slot.getField().getType();
- if (type == Integer.TYPE) {
+ if (type == int.class) {
output.writeInt(fieldValue != null ? ((Integer) fieldValue).intValue() : 0);
- } else if (type == Byte.TYPE) {
+ } else if (type == byte.class) {
output.writeByte(fieldValue != null ? ((Byte) fieldValue).byteValue() : 0);
- } else if (type == Character.TYPE) {
+ } else if (type == char.class) {
output.writeChar(fieldValue != null ? ((Character) fieldValue).charValue() : 0);
- } else if (type == Short.TYPE) {
+ } else if (type == short.class) {
output.writeShort(fieldValue != null ? ((Short) fieldValue).shortValue() : 0);
- } else if (type == Boolean.TYPE) {
+ } else if (type == boolean.class) {
output.writeBoolean(fieldValue != null ? ((Boolean) fieldValue).booleanValue() : false);
- } else if (type == Long.TYPE) {
+ } else if (type == long.class) {
output.writeLong(fieldValue != null ? ((Long) fieldValue).longValue() : 0);
- } else if (type == Float.TYPE) {
+ } else if (type == float.class) {
output.writeFloat(fieldValue != null ? ((Float) fieldValue).floatValue() : 0);
- } else if (type == Double.TYPE) {
+ } else if (type == double.class) {
output.writeDouble(fieldValue != null ? ((Double) fieldValue).doubleValue() : 0);
} else {
// Either array or Object
diff --git a/luni/src/main/java/java/io/File.java b/luni/src/main/java/java/io/File.java
index 1e1d625..7c2c926 100644
--- a/luni/src/main/java/java/io/File.java
+++ b/luni/src/main/java/java/io/File.java
@@ -15,27 +15,15 @@
* limitations under the License.
*/
-// BEGIN android-note
-// We've dropped Windows support, except where it's exposed: we still support
-// non-Unix separators in serialized File objects, for example, but we don't
-// have any code for UNC paths or case-insensitivity.
-// We've also changed the JNI interface to better match what the Java actually wants.
-// (The JNI implementation is also much simpler.)
-// Some methods have been rewritten to reduce unnecessary allocation.
-// Some duplication has been factored out.
-// END android-note
-
package java.io;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
-import java.security.AccessController;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.harmony.luni.util.DeleteOnExit;
-import org.apache.harmony.luni.util.PriviAction;
/**
* An "abstract" representation of a file system entity identified by a
@@ -191,7 +179,7 @@
if (isAbsolute) {
this.path = this.absolutePath = cleanPath;
} else {
- String userDir = AccessController.doPrivileged(new PriviAction<String>("user.dir"));
+ String userDir = System.getProperty("user.dir");
this.absolutePath = cleanPath.isEmpty() ? userDir : join(userDir, cleanPath);
// We want path to be equal to cleanPath, but we'd like to reuse absolutePath's char[].
this.path = absolutePath.substring(absolutePath.length() - cleanPath.length());
@@ -277,22 +265,12 @@
* to actually attempt the operation.
*
* @return {@code true} if this file can be executed, {@code false} otherwise.
- * @throws SecurityException
- * If a security manager exists and
- * SecurityManager.checkExec(java.lang.String) disallows read
- * permission to this file object
- * @see java.lang.SecurityManager#checkExec(String)
- *
* @since 1.6
*/
public boolean canExecute() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkExec(path); // Seems bogus, but this is what the RI does.
- }
return canExecuteImpl(absolutePath);
}
private static native boolean canExecuteImpl(String path);
@@ -301,18 +279,11 @@
* Indicates whether the current context is allowed to read from this file.
*
* @return {@code true} if this file can be read, {@code false} otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * read request.
*/
public boolean canRead() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
return canReadImpl(absolutePath);
}
private static native boolean canReadImpl(String path);
@@ -322,18 +293,11 @@
*
* @return {@code true} if this file can be written, {@code false}
* otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * write request.
*/
public boolean canWrite() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
return canWriteImpl(absolutePath);
}
private static native boolean canWriteImpl(String path);
@@ -359,19 +323,11 @@
* Callers must check the return value.
*
* @return {@code true} if this file was deleted, {@code false} otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * request.
- * @see java.lang.SecurityManager#checkDelete
*/
public boolean delete() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkDelete(path);
- }
return deleteImpl(absolutePath);
}
@@ -381,16 +337,8 @@
* Schedules this file to be automatically deleted once the virtual machine
* terminates. This will only happen when the virtual machine terminates
* normally as described by the Java Language Specification section 12.9.
- *
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * request.
*/
public void deleteOnExit() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkDelete(path);
- }
DeleteOnExit.getInstance().addFile(getAbsoluteName());
}
@@ -416,20 +364,11 @@
* underlying file system.
*
* @return {@code true} if this file exists, {@code false} otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
- * @see #getPath
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
*/
public boolean exists() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
return existsImpl(absolutePath);
}
@@ -497,7 +436,6 @@
* @return the new file constructed from this file's canonical path.
* @throws IOException
* if an I/O error occurs.
- * @see java.lang.SecurityManager#checkPropertyAccess
*/
public File getCanonicalFile() throws IOException {
return new File(getCanonicalPath());
@@ -595,18 +533,11 @@
*
* @return {@code true} if this file is a directory, {@code false}
* otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
*/
public boolean isDirectory() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
return isDirectoryImpl(absolutePath);
}
@@ -617,18 +548,11 @@
* file system.
*
* @return {@code true} if this file is a file, {@code false} otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
*/
public boolean isFile() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
return isFileImpl(absolutePath);
}
@@ -642,18 +566,11 @@
* purpose.
*
* @return {@code true} if the file is hidden, {@code false} otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
*/
public boolean isHidden() {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
return getName().startsWith(".");
}
@@ -663,18 +580,11 @@
* Returns 0 if the file does not exist.
*
* @return the time when this file was last modified.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
*/
public long lastModified() {
if (path.isEmpty()) {
return 0;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
return lastModifiedImpl(absolutePath);
}
@@ -693,9 +603,6 @@
* otherwise.
* @throws IllegalArgumentException
* if {@code time < 0}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies write
- * access to this file.
*/
public boolean setLastModified(long time) {
if (path.isEmpty()) {
@@ -704,10 +611,6 @@
if (time < 0) {
throw new IllegalArgumentException("time < 0");
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
return setLastModifiedImpl(absolutePath, time);
}
@@ -741,20 +644,12 @@
* pathname the operation will fail. If the underlying file system
* does not support execute permission and the value of executable
* is false, this operation will fail.
- * @throws SecurityException -
- * If a security manager exists and
- * SecurityManager.checkWrite(java.lang.String) disallows write
- * permission to this file object
* @since 1.6
*/
public boolean setExecutable(boolean executable, boolean ownerOnly) {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
return setExecutableImpl(absolutePath, executable, ownerOnly);
}
@@ -785,20 +680,12 @@
* pathname the operation will fail. If the underlying file system
* does not support read permission and the value of readable is
* false, this operation will fail.
- * @throws SecurityException -
- * If a security manager exists and
- * SecurityManager.checkWrite(java.lang.String) disallows write
- * permission to this file object
* @since 1.6
*/
public boolean setReadable(boolean readable, boolean ownerOnly) {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
return setReadableImpl(absolutePath, readable, ownerOnly);
}
@@ -827,20 +714,12 @@
* @return true if and only if the operation succeeded. If the user does not
* have permission to change the access permissions of this abstract
* pathname the operation will fail.
- * @throws SecurityException -
- * If a security manager exists and
- * SecurityManager.checkWrite(java.lang.String) disallows write
- * permission to this file object
* @since 1.6
*/
public boolean setWritable(boolean writable, boolean ownerOnly) {
if (path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
return setWritableImpl(absolutePath, writable, ownerOnly);
}
@@ -861,14 +740,10 @@
* The result for a directory is not defined.
*
* @return the number of bytes in this file.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
*/
public long length() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
+ if (path.isEmpty()) {
+ return 0;
}
return lengthImpl(absolutePath);
}
@@ -884,17 +759,8 @@
* directory are not returned as part of the list.
*
* @return an array of strings with file names or {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
- * @see #isDirectory
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
*/
public String[] list() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(path);
- }
if (path.isEmpty()) {
return null;
}
@@ -916,12 +782,6 @@
* @param filter
* the filter to match names against, may be {@code null}.
* @return an array of files or {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
- * @see #getPath
- * @see #isDirectory
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
*/
public String[] list(FilenameFilter filter) {
String[] filenames = list();
@@ -944,11 +804,6 @@
* absolute, they are relative otherwise.
*
* @return an array of files or {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
- * @see #list
- * @see #isDirectory
*/
public File[] listFiles() {
return filenamesToFiles(list());
@@ -967,13 +822,6 @@
* @param filter
* the filter to match names against, may be {@code null}.
* @return an array of files or {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
- * @see #list(FilenameFilter filter)
- * @see #getPath
- * @see #isDirectory
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
*/
public File[] listFiles(FilenameFilter filter) {
return filenamesToFiles(list(filter));
@@ -991,12 +839,6 @@
* @param filter
* the filter to match names against, may be {@code null}.
* @return an array of files or {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies read
- * access to this file.
- * @see #getPath
- * @see #isDirectory
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
*/
public File[] listFiles(FileFilter filter) {
File[] files = listFiles();
@@ -1039,16 +881,9 @@
*
* @return {@code true} if the directory has been created, {@code false}
* otherwise.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies write
- * access for this file.
* @see #mkdirs
*/
public boolean mkdir() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
return mkdirImpl(absolutePath);
}
@@ -1064,9 +899,6 @@
* @return {@code true} if the necessary directories have been created,
* {@code false} if the target directory already exists or one of
* the directories can not be created.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies write
- * access for this file.
* @see #mkdir
*/
public boolean mkdirs() {
@@ -1100,15 +932,8 @@
* @return {@code true} if the file has been created, {@code false} if it
* already exists.
* @throws IOException if it's not possible to create the file.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies write
- * access for this file.
*/
public boolean createNewFile() throws IOException {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- }
if (path.isEmpty()) {
throw new IOException("No such file or directory");
}
@@ -1158,9 +983,8 @@
* @throws IOException
* if an error occurs when writing the file.
*/
- @SuppressWarnings("nls")
- public static File createTempFile(String prefix, String suffix,
- File directory) throws IOException {
+ public static File createTempFile(String prefix, String suffix, File directory)
+ throws IOException {
// Force a prefix null check first
if (prefix.length() < 3) {
throw new IllegalArgumentException("prefix must be at least 3 characters");
@@ -1170,8 +994,7 @@
}
File tmpDirFile = directory;
if (tmpDirFile == null) {
- String tmpDir = AccessController.doPrivileged(
- new PriviAction<String>("java.io.tmpdir", "."));
+ String tmpDir = System.getProperty("java.io.tmpdir", ".");
tmpDirFile = new File(tmpDir);
}
File result;
@@ -1199,19 +1022,11 @@
*
* @param newPath the new path.
* @return true on success.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies write
- * access for this file or {@code newPath}.
*/
public boolean renameTo(File newPath) {
if (path.isEmpty() || newPath.path.isEmpty()) {
return false;
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkWrite(path);
- security.checkWrite(newPath.path);
- }
return renameToImpl(absolutePath, newPath.absolutePath);
}
@@ -1235,7 +1050,6 @@
*
* @return an URI for this file.
*/
- @SuppressWarnings("nls")
public URI toURI() {
String name = getAbsoluteName();
try {
@@ -1266,7 +1080,6 @@
* correct escaping of illegal characters.
*/
@Deprecated
- @SuppressWarnings("nls")
public URL toURL() throws java.net.MalformedURLException {
String name = getAbsoluteName();
if (!name.startsWith("/")) {
@@ -1312,10 +1125,6 @@
* @since 1.6
*/
public long getTotalSpace() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkPermission(new RuntimePermission("getFileSystemAttributes"));
- }
return getTotalSpaceImpl(absolutePath);
}
private static native long getTotalSpaceImpl(String path);
@@ -1334,10 +1143,6 @@
* @since 1.6
*/
public long getUsableSpace() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkPermission(new RuntimePermission("getFileSystemAttributes"));
- }
return getUsableSpaceImpl(absolutePath);
}
private static native long getUsableSpaceImpl(String path);
@@ -1352,10 +1157,6 @@
* @since 1.6
*/
public long getFreeSpace() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkPermission(new RuntimePermission("getFileSystemAttributes"));
- }
return getFreeSpaceImpl(absolutePath);
}
private static native long getFreeSpaceImpl(String path);
diff --git a/luni/src/main/java/java/io/FileDescriptor.java b/luni/src/main/java/java/io/FileDescriptor.java
index cfda96f..e118a3e 100644
--- a/luni/src/main/java/java/io/FileDescriptor.java
+++ b/luni/src/main/java/java/io/FileDescriptor.java
@@ -52,14 +52,11 @@
*/
public static final FileDescriptor err = new FileDescriptor();
- // BEGIN android-changed
- // file descriptors are only int on android
/**
- * Represents a link to any underlying OS resources for this FileDescriptor.
+ * The Unix file descriptor backing this FileDescriptor.
* A value of -1 indicates that this FileDescriptor is invalid.
*/
int descriptor = -1;
- // END android-changed
boolean readOnly = false;
diff --git a/luni/src/main/java/java/io/FileFilter.java b/luni/src/main/java/java/io/FileFilter.java
index 5638dd9..da36fa8 100644
--- a/luni/src/main/java/java/io/FileFilter.java
+++ b/luni/src/main/java/java/io/FileFilter.java
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// the abstract modifier of the interface was removed.
-// END android-note
-
package java.io;
/**
diff --git a/luni/src/main/java/java/io/FileInputStream.java b/luni/src/main/java/java/io/FileInputStream.java
index 7cdc235..93dcf2d 100644
--- a/luni/src/main/java/java/io/FileInputStream.java
+++ b/luni/src/main/java/java/io/FileInputStream.java
@@ -71,18 +71,11 @@
* the file from which this stream reads.
* @throws FileNotFoundException
* if {@code file} does not exist.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * read request.
*/
public FileInputStream(File file) throws FileNotFoundException {
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 = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), IFileSystem.O_RDONLY);
@@ -97,18 +90,11 @@
* the FileDescriptor from which this stream reads.
* @throws NullPointerException
* if {@code fd} is {@code null}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies the
- * read request.
*/
public FileInputStream(FileDescriptor fd) {
if (fd == null) {
throw new NullPointerException("fd == null");
}
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkRead(fd);
- }
this.fd = fd;
this.shouldCloseFd = false;
// Note that we do not call guard.open here because the
diff --git a/luni/src/main/java/java/io/FileOutputStream.java b/luni/src/main/java/java/io/FileOutputStream.java
index 0c73d0b..fd91b53 100644
--- a/luni/src/main/java/java/io/FileOutputStream.java
+++ b/luni/src/main/java/java/io/FileOutputStream.java
@@ -69,9 +69,6 @@
*
* @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 {
this(file, false);
@@ -85,17 +82,8 @@
* @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 {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkWrite(file.getPath());
- }
+ public FileOutputStream(File file, boolean append) throws FileNotFoundException {
this.fd = new FileDescriptor();
this.mode = append ? IFileSystem.O_APPEND : IFileSystem.O_WRONLY;
this.fd.descriptor = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), mode);
@@ -108,18 +96,11 @@
*
* @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) {
if (fd == null) {
throw new NullPointerException();
}
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkWrite(fd);
- }
this.fd = fd;
this.shouldCloseFd = false;
this.channel = NioUtils.newFileChannel(this, fd.descriptor, IFileSystem.O_WRONLY);
diff --git a/luni/src/main/java/java/io/FilePermission.java b/luni/src/main/java/java/io/FilePermission.java
index 7eb4300..94263f1 100644
--- a/luni/src/main/java/java/io/FilePermission.java
+++ b/luni/src/main/java/java/io/FilePermission.java
@@ -17,10 +17,10 @@
package java.io;
-import java.security.AccessController;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.PrivilegedAction;
+import java.util.Locale;
import libcore.util.Objects;
/**
@@ -102,16 +102,11 @@
if (path.equals("<<ALL FILES>>")) {
includeAll = true;
} else {
- canonPath = AccessController
- .doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- try {
- return new File(path).getCanonicalPath();
- } catch (IOException e) {
- return path;
- }
- }
- });
+ canonPath = path;
+ try {
+ canonPath = new File(path).getCanonicalPath();
+ } catch (IOException e) {
+ }
if (path.equals("*") || path.endsWith(File.separator + "*")) {
allDir = true;
}
@@ -131,7 +126,7 @@
* @return the string representing this permission's actions
*/
private String toCanonicalActionString(String action) {
- actions = action.trim().toLowerCase();
+ actions = action.trim().toLowerCase(Locale.US);
// get the numerical representation of the action list
mask = getMask(actions);
diff --git a/luni/src/main/java/java/io/FilterOutputStream.java b/luni/src/main/java/java/io/FilterOutputStream.java
index 24adf87f..5f293b1 100644
--- a/luni/src/main/java/java/io/FilterOutputStream.java
+++ b/luni/src/main/java/java/io/FilterOutputStream.java
@@ -100,9 +100,6 @@
*/
@Override
public void write(byte[] buffer) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
write(buffer, 0, buffer.length);
}
diff --git a/luni/src/main/java/java/io/FilterWriter.java b/luni/src/main/java/java/io/FilterWriter.java
index cd48f64..820fe4f 100644
--- a/luni/src/main/java/java/io/FilterWriter.java
+++ b/luni/src/main/java/java/io/FilterWriter.java
@@ -88,9 +88,6 @@
*/
@Override
public void write(char[] buffer, int offset, int count) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
synchronized (lock) {
out.write(buffer, offset, count);
}
diff --git a/luni/src/main/java/java/io/InputStream.java b/luni/src/main/java/java/io/InputStream.java
index c01ede7..6718395 100644
--- a/luni/src/main/java/java/io/InputStream.java
+++ b/luni/src/main/java/java/io/InputStream.java
@@ -152,9 +152,6 @@
* if this stream is closed or another IOException occurs.
*/
public int read(byte[] b) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
return read(b, 0, b.length);
}
diff --git a/luni/src/main/java/java/io/InputStreamReader.java b/luni/src/main/java/java/io/InputStreamReader.java
index 28091e3..fed7f54 100644
--- a/luni/src/main/java/java/io/InputStreamReader.java
+++ b/luni/src/main/java/java/io/InputStreamReader.java
@@ -138,11 +138,9 @@
@Override
public void close() throws IOException {
synchronized (lock) {
- // BEGIN android-added
if (decoder != null) {
decoder.reset();
}
- // END android-added
decoder = null;
if (in != null) {
in.close();
@@ -152,11 +150,10 @@
}
/**
- * Returns the name of the encoding used to convert bytes into characters.
- * The value {@code null} is returned if this reader has been closed.
- *
- * @return the name of the character converter or {@code null} if this
- * reader is closed.
+ * Returns the historical name of the encoding used by this writer to convert characters to
+ * bytes, or null if this writer has been closed. Most callers should probably keep
+ * track of the String or Charset they passed in; this method may not return the same
+ * name.
*/
public String getEncoding() {
if (!isOpen()) {
@@ -278,10 +275,8 @@
decoder.flush(out);
decoder.reset();
}
- if (result.isMalformed()) {
- throw new MalformedInputException(result.length());
- } else if (result.isUnmappable()) {
- throw new UnmappableCharacterException(result.length());
+ if (result.isMalformed() || result.isUnmappable()) {
+ result.throwException();
}
return out.position() - offset == 0 ? -1 : out.position() - offset;
diff --git a/luni/src/main/java/java/io/ObjectInputStream.java b/luni/src/main/java/java/io/ObjectInputStream.java
index 789a286..3a802a0 100644
--- a/luni/src/main/java/java/io/ObjectInputStream.java
+++ b/luni/src/main/java/java/io/ObjectInputStream.java
@@ -17,11 +17,6 @@
package java.io;
-// BEGIN android-note
-// Harmony uses ObjectAccessors to access fields through JNI. Android has not
-// yet migrated that API. As a consequence, there's a lot of changes here...
-// END android-note
-
import dalvik.system.VMStack;
import java.io.EmulatedFields.ObjectSlot;
import java.lang.reflect.Array;
@@ -29,14 +24,12 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
-import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import libcore.util.EmptyArray;
-import org.apache.harmony.luni.util.PriviAction;
/**
* A specialized {@link InputStream} that is able to read (deserialize) Java
@@ -50,9 +43,7 @@
*/
public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants {
- // BEGIN android-note
- // this is non-static to avoid sync contention. Would static be faster?
- // END android-note
+ // TODO: this is non-static to avoid sync contention. Would static be faster?
private InputStream emptyStream = new ByteArrayInputStream(EmptyArray.BYTE);
// To put into objectsRead when reading unsharedObject
@@ -123,10 +114,6 @@
PRIMITIVE_CLASSES.put("void", void.class);
}
- // BEGIN android-removed
- // private ObjectAccessor accessor = AccessorFactory.getObjectAccessor();
- // END android-removed
-
// Internal type used to keep track of validators & corresponding priority
static class InputValidationDesc {
ObjectInputValidation validator;
@@ -351,17 +338,9 @@
*
* @throws IOException
* if an error occurs when creating this stream.
- * @throws SecurityException
- * if a security manager is installed and it denies subclassing
- * this class.
- * @see SecurityManager#checkPermission(java.security.Permission)
*/
- protected ObjectInputStream() throws IOException, SecurityException {
+ protected ObjectInputStream() throws IOException {
super();
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
- }
// WARNING - we should throw IOException if not called from a subclass
// according to the JavaDoc. Add the test.
this.subclassOverridingImplementation = true;
@@ -378,45 +357,12 @@
* @throws StreamCorruptedException
* if the source stream does not contain serialized objects that
* can be read.
- * @throws SecurityException
- * if a security manager is installed and it denies subclassing
- * this class.
*/
- public ObjectInputStream(InputStream input)
- throws StreamCorruptedException, IOException {
+ public ObjectInputStream(InputStream input) throws StreamCorruptedException, IOException {
final Class<?> implementationClass = getClass();
final Class<?> thisClass = ObjectInputStream.class;
- SecurityManager sm = System.getSecurityManager();
- if (sm != null && implementationClass != thisClass) {
- boolean mustCheck = AccessController
- .doPrivileged(new PrivilegedAction<Boolean>() {
- public Boolean run() {
- try {
- Method method = implementationClass.getMethod("readFields",
- EmptyArray.CLASS);
- if (method.getDeclaringClass() != thisClass) {
- return Boolean.TRUE;
- }
- } catch (NoSuchMethodException ignored) {
- }
- try {
- Method method = implementationClass.getMethod("readUnshared",
- EmptyArray.CLASS);
- if (method.getDeclaringClass() != thisClass) {
- return Boolean.TRUE;
- }
- } catch (NoSuchMethodException ignored) {
- }
- return Boolean.FALSE;
- }
- });
- if (mustCheck) {
- sm
- .checkPermission(ObjectStreamConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
- }
- }
- this.input = (input instanceof DataInputStream) ? (DataInputStream) input
- : new DataInputStream(input);
+ this.input = (input instanceof DataInputStream)
+ ? (DataInputStream) input : new DataInputStream(input);
primitiveTypes = new DataInputStream(this);
enableResolve = false;
this.subclassOverridingImplementation = false;
@@ -524,22 +470,10 @@
* {@code true} to enable object replacement; {@code false} to
* disable it.
* @return the previous setting.
- * @throws SecurityException
- * if a security manager is installed and it denies enabling
- * object replacement for this stream.
* @see #resolveObject
* @see ObjectOutputStream#enableReplaceObject
*/
- protected boolean enableResolveObject(boolean enable)
- throws SecurityException {
- if (enable) {
- // The Stream has to be trusted for this feature to be enabled.
- // trusted means the stream's class loader has to be null
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkPermission(SUBSTITUTION_PERMISSION);
- }
- }
+ protected boolean enableResolveObject(boolean enable) {
boolean originalValue = enableResolve;
enableResolve = enable;
return originalValue;
@@ -1090,21 +1024,21 @@
for (ObjectSlot element : slots) {
element.defaulted = false;
Class<?> type = element.field.getType();
- if (type == Integer.TYPE) {
+ if (type == int.class) {
element.fieldValue = input.readInt();
- } else if (type == Byte.TYPE) {
+ } else if (type == byte.class) {
element.fieldValue = input.readByte();
- } else if (type == Character.TYPE) {
+ } else if (type == char.class) {
element.fieldValue = input.readChar();
- } else if (type == Short.TYPE) {
+ } else if (type == short.class) {
element.fieldValue = input.readShort();
- } else if (type == Boolean.TYPE) {
+ } else if (type == boolean.class) {
element.fieldValue = input.readBoolean();
- } else if (type == Long.TYPE) {
+ } else if (type == long.class) {
element.fieldValue = input.readLong();
- } else if (type == Float.TYPE) {
+ } else if (type == float.class) {
element.fieldValue = input.readFloat();
- } else if (type == Double.TYPE) {
+ } else if (type == double.class) {
element.fieldValue = input.readDouble();
} else {
// Either array or Object
@@ -1162,42 +1096,42 @@
// and do the other checking, so there's no null check on 'field' here.
try {
Class<?> type = fieldDesc.getTypeInternal();
- if (type == Byte.TYPE) {
+ if (type == byte.class) {
byte b = input.readByte();
if (field != null) {
field.setByte(obj, b);
}
- } else if (type == Character.TYPE) {
+ } else if (type == char.class) {
char c = input.readChar();
if (field != null) {
field.setChar(obj, c);
}
- } else if (type == Double.TYPE) {
+ } else if (type == double.class) {
double d = input.readDouble();
if (field != null) {
field.setDouble(obj, d);
}
- } else if (type == Float.TYPE) {
+ } else if (type == float.class) {
float f = input.readFloat();
if (field != null) {
field.setFloat(obj, f);
}
- } else if (type == Integer.TYPE) {
+ } else if (type == int.class) {
int i = input.readInt();
if (field != null) {
field.setInt(obj, i);
}
- } else if (type == Long.TYPE) {
+ } else if (type == long.class) {
long j = input.readLong();
if (field != null) {
field.setLong(obj, j);
}
- } else if (type == Short.TYPE) {
+ } else if (type == short.class) {
short s = input.readShort();
if (field != null) {
field.setShort(obj, s);
}
- } else if (type == Boolean.TYPE) {
+ } else if (type == boolean.class) {
boolean z = input.readBoolean();
if (field != null) {
field.setBoolean(obj, z);
@@ -1217,13 +1151,11 @@
}
if (fieldDesc != null) {
if (toSet != null) {
- // BEGIN android-changed
// Get the field type from the local field rather than
// from the stream's supplied data. That's the field
// we'll be setting, so that's the one that needs to be
// validated.
Class<?> fieldType = localFieldDesc.getTypeInternal();
- // END android-added
Class<?> valueType = toSet.getClass();
if (!fieldType.isAssignableFrom(valueType)) {
throw new ClassCastException(classDesc.getName() + "." + fieldName + " - " + fieldType + " not compatible with " + valueType);
@@ -1431,8 +1363,7 @@
try {
if (readMethod != null) {
// We have to be able to fetch its value, even if it is private
- AccessController.doPrivileged(new PriviAction<Object>(
- readMethod));
+ readMethod.setAccessible(true);
try {
readMethod.invoke(object, this);
} catch (InvocationTargetException e) {
@@ -1543,40 +1474,40 @@
// the array first, and also call different methods depending on the
// elements.
if (componentType.isPrimitive()) {
- if (componentType == Integer.TYPE) {
+ if (componentType == int.class) {
int[] intArray = (int[]) result;
for (int i = 0; i < size; i++) {
intArray[i] = input.readInt();
}
- } else if (componentType == Byte.TYPE) {
+ } else if (componentType == byte.class) {
byte[] byteArray = (byte[]) result;
input.readFully(byteArray, 0, size);
- } else if (componentType == Character.TYPE) {
+ } else if (componentType == char.class) {
char[] charArray = (char[]) result;
for (int i = 0; i < size; i++) {
charArray[i] = input.readChar();
}
- } else if (componentType == Short.TYPE) {
+ } else if (componentType == short.class) {
short[] shortArray = (short[]) result;
for (int i = 0; i < size; i++) {
shortArray[i] = input.readShort();
}
- } else if (componentType == Boolean.TYPE) {
+ } else if (componentType == boolean.class) {
boolean[] booleanArray = (boolean[]) result;
for (int i = 0; i < size; i++) {
booleanArray[i] = input.readBoolean();
}
- } else if (componentType == Long.TYPE) {
+ } else if (componentType == long.class) {
long[] longArray = (long[]) result;
for (int i = 0; i < size; i++) {
longArray[i] = input.readLong();
}
- } else if (componentType == Float.TYPE) {
+ } else if (componentType == float.class) {
float[] floatArray = (float[]) result;
for (int i = 0; i < size; i++) {
floatArray[i] = input.readFloat();
}
- } else if (componentType == Double.TYPE) {
+ } else if (componentType == double.class) {
double[] doubleArray = (double[]) result;
for (int i = 0; i < size; i++) {
doubleArray[i] = input.readDouble();
@@ -1839,10 +1770,7 @@
throws IOException, ClassNotFoundException {
// TODO: This method is opportunity for performance enhancement
// We can cache the classloader and recently used interfaces.
- // BEGIN android-changed
- // ClassLoader loader = VM.getNonBootstrapClassLoader();
ClassLoader loader = ClassLoader.getSystemClassLoader();
- // END android-changed
Class<?>[] interfaces = new Class<?>[interfaceNames.length];
for (int i = 0; i < interfaceNames.length; i++) {
interfaces[i] = Class.forName(interfaceNames[i], false, loader);
@@ -2079,9 +2007,7 @@
// original/outside caller
if (++nestedLevels == 1) {
// Remember the caller's class loader
- // BEGIN android-changed
callerClassLoader = getClosestUserClassLoader();
- // END android-changed
}
result = readNonPrimitiveContent(unshared);
@@ -2118,11 +2044,8 @@
return result;
}
- // BEGIN android-added
- private static final ClassLoader bootstrapLoader
- = Object.class.getClassLoader();
- private static final ClassLoader systemLoader
- = ClassLoader.getSystemClassLoader();
+ private static final ClassLoader bootstrapLoader = Object.class.getClassLoader();
+ private static final ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
/**
* Searches up the call stack to find the closest user-defined class loader.
@@ -2140,7 +2063,6 @@
}
return null;
}
- // END android-added
/**
* Method to be overridden by subclasses to read the next object from the
diff --git a/luni/src/main/java/java/io/ObjectOutputStream.java b/luni/src/main/java/java/io/ObjectOutputStream.java
index 29bfdac..ffc02a0 100644
--- a/luni/src/main/java/java/io/ObjectOutputStream.java
+++ b/luni/src/main/java/java/io/ObjectOutputStream.java
@@ -24,7 +24,6 @@
import java.nio.ByteOrder;
import java.nio.charset.ModifiedUtf8;
import java.util.List;
-import libcore.util.EmptyArray;
import libcore.io.SizeOf;
import org.apache.harmony.luni.platform.OSMemory;
@@ -114,11 +113,6 @@
*/
private boolean subclassOverridingImplementation;
-
- // BEGIN android-removed
- // private ObjectAccessor accessor = AccessorFactory.getObjectAccessor();
- // END android-removed
-
/*
* Descriptor for java.lang.reflect.Proxy
*/
@@ -249,17 +243,9 @@
*
* @throws IOException
* if an error occurs when creating this stream.
- * @throws SecurityException
- * if a security manager is installed and it denies subclassing
- * this class.
- * @see SecurityManager#checkPermission(java.security.Permission)
*/
- protected ObjectOutputStream() throws IOException, SecurityException {
+ protected ObjectOutputStream() throws IOException {
super();
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
- }
/*
* WARNING - we should throw IOException if not called from a subclass
* according to the JavaDoc. Add the test.
@@ -277,36 +263,10 @@
* @throws IOException
* if an error occurs while writing the object stream
* header
- * @throws SecurityException
- * if a security manager is installed and it denies subclassing
- * this class.
*/
public ObjectOutputStream(OutputStream output) throws IOException {
Class<?> implementationClass = getClass();
Class<?> thisClass = ObjectOutputStream.class;
- if (implementationClass != thisClass) {
- boolean mustCheck = false;
- try {
- Method method = implementationClass.getMethod("putFields", EmptyArray.CLASS);
- mustCheck = method.getDeclaringClass() != thisClass;
- } catch (NoSuchMethodException e) {
- }
- if (!mustCheck) {
- try {
- Method method = implementationClass.getMethod("writeUnshared",
- WRITE_UNSHARED_PARAM_TYPES);
- mustCheck = method.getDeclaringClass() != thisClass;
- } catch (NoSuchMethodException e) {
- }
- }
- if (mustCheck) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm
- .checkPermission(ObjectStreamConstants.SUBCLASS_IMPLEMENTATION_PERMISSION);
- }
- }
- }
this.output = (output instanceof DataOutputStream) ? (DataOutputStream) output
: new DataOutputStream(output);
this.enableReplace = false;
@@ -482,22 +442,10 @@
* {@code true} to enable object replacement; {@code false} to
* disable it.
* @return the previous setting.
- * @throws SecurityException
- * if a security manager is installed and it denies enabling
- * object replacement for this stream.
* @see #replaceObject
* @see ObjectInputStream#enableResolveObject
*/
- protected boolean enableReplaceObject(boolean enable)
- 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
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkPermission(SUBSTITUTION_PERMISSION);
- }
- }
+ protected boolean enableReplaceObject(boolean enable) {
boolean originalValue = enableReplace;
enableReplace = enable;
return originalValue;
@@ -976,21 +924,21 @@
for (EmulatedFields.ObjectSlot slot : accessibleSimulatedFields.slots()) {
Object fieldValue = slot.getFieldValue();
Class<?> type = slot.getField().getType();
- if (type == Integer.TYPE) {
+ if (type == int.class) {
output.writeInt(fieldValue != null ? ((Integer) fieldValue).intValue() : 0);
- } else if (type == Byte.TYPE) {
+ } else if (type == byte.class) {
output.writeByte(fieldValue != null ? ((Byte) fieldValue).byteValue() : 0);
- } else if (type == Character.TYPE) {
+ } else if (type == char.class) {
output.writeChar(fieldValue != null ? ((Character) fieldValue).charValue() : 0);
- } else if (type == Short.TYPE) {
+ } else if (type == short.class) {
output.writeShort(fieldValue != null ? ((Short) fieldValue).shortValue() : 0);
- } else if (type == Boolean.TYPE) {
+ } else if (type == boolean.class) {
output.writeBoolean(fieldValue != null ? ((Boolean) fieldValue).booleanValue() : false);
- } else if (type == Long.TYPE) {
+ } else if (type == long.class) {
output.writeLong(fieldValue != null ? ((Long) fieldValue).longValue() : 0);
- } else if (type == Float.TYPE) {
+ } else if (type == float.class) {
output.writeFloat(fieldValue != null ? ((Float) fieldValue).floatValue() : 0);
- } else if (type == Double.TYPE) {
+ } else if (type == double.class) {
output.writeDouble(fieldValue != null ? ((Double) fieldValue).doubleValue() : 0);
} else {
// Either array or Object
@@ -1025,21 +973,21 @@
if (field == null) {
throw new InvalidClassException(classDesc.getName() + " doesn't have a field " + fieldDesc.getName() + " of type " + type);
}
- if (type == Byte.TYPE) {
+ if (type == byte.class) {
output.writeByte(field.getByte(obj));
- } else if (type == Character.TYPE) {
+ } else if (type == char.class) {
output.writeChar(field.getChar(obj));
- } else if (type == Double.TYPE) {
+ } else if (type == double.class) {
output.writeDouble(field.getDouble(obj));
- } else if (type == Float.TYPE) {
+ } else if (type == float.class) {
output.writeFloat(field.getFloat(obj));
- } else if (type == Integer.TYPE) {
+ } else if (type == int.class) {
output.writeInt(field.getInt(obj));
- } else if (type == Long.TYPE) {
+ } else if (type == long.class) {
output.writeLong(field.getLong(obj));
- } else if (type == Short.TYPE) {
+ } else if (type == short.class) {
output.writeShort(field.getShort(obj));
- } else if (type == Boolean.TYPE) {
+ } else if (type == boolean.class) {
output.writeBoolean(field.getBoolean(obj));
} else {
// Reference types (including arrays).
@@ -1215,47 +1163,47 @@
// elements.
if (componentType.isPrimitive()) {
- if (componentType == Integer.TYPE) {
+ if (componentType == int.class) {
int[] intArray = (int[]) array;
output.writeInt(intArray.length);
for (int i = 0; i < intArray.length; i++) {
output.writeInt(intArray[i]);
}
- } else if (componentType == Byte.TYPE) {
+ } else if (componentType == byte.class) {
byte[] byteArray = (byte[]) array;
output.writeInt(byteArray.length);
output.write(byteArray, 0, byteArray.length);
- } else if (componentType == Character.TYPE) {
+ } else if (componentType == char.class) {
char[] charArray = (char[]) array;
output.writeInt(charArray.length);
for (int i = 0; i < charArray.length; i++) {
output.writeChar(charArray[i]);
}
- } else if (componentType == Short.TYPE) {
+ } else if (componentType == short.class) {
short[] shortArray = (short[]) array;
output.writeInt(shortArray.length);
for (int i = 0; i < shortArray.length; i++) {
output.writeShort(shortArray[i]);
}
- } else if (componentType == Boolean.TYPE) {
+ } else if (componentType == boolean.class) {
boolean[] booleanArray = (boolean[]) array;
output.writeInt(booleanArray.length);
for (int i = 0; i < booleanArray.length; i++) {
output.writeBoolean(booleanArray[i]);
}
- } else if (componentType == Long.TYPE) {
+ } else if (componentType == long.class) {
long[] longArray = (long[]) array;
output.writeInt(longArray.length);
for (int i = 0; i < longArray.length; i++) {
output.writeLong(longArray[i]);
}
- } else if (componentType == Float.TYPE) {
+ } else if (componentType == float.class) {
float[] floatArray = (float[]) array;
output.writeInt(floatArray.length);
for (int i = 0; i < floatArray.length; i++) {
output.writeFloat(floatArray[i]);
}
- } else if (componentType == Double.TYPE) {
+ } else if (componentType == double.class) {
double[] doubleArray = (double[]) array;
output.writeInt(doubleArray.length);
for (int i = 0; i < doubleArray.length; i++) {
diff --git a/luni/src/main/java/java/io/ObjectStreamClass.java b/luni/src/main/java/java/io/ObjectStreamClass.java
index 2fe31f0..2f7fa41 100644
--- a/luni/src/main/java/java/io/ObjectStreamClass.java
+++ b/luni/src/main/java/java/io/ObjectStreamClass.java
@@ -24,7 +24,6 @@
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;
import java.util.ArrayList;
@@ -35,7 +34,6 @@
import java.util.WeakHashMap;
import libcore.util.EmptyArray;
import org.apache.harmony.luni.platform.OSMemory;
-import org.apache.harmony.luni.util.PriviAction;
/**
* Represents a descriptor for identifying a class during serialization and
@@ -333,7 +331,7 @@
if (!useReflectFields) {
// The user declared a collection of emulated fields. Use them.
// We have to be able to fetch its value, even if it is private
- AccessController.doPrivileged(new PriviAction<Object>(f));
+ f.setAccessible(true);
try {
// static field, pass null
_fields = (ObjectStreamField[]) f.get(null);
@@ -395,7 +393,7 @@
*/
for (int i = 0; i < fields.length; i++) {
final Field field = fields[i];
- if (Long.TYPE == field.getType()) {
+ if (field.getType() == long.class) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
if (UID_FIELD_NAME.equals(field.getName())) {
@@ -404,8 +402,7 @@
* visibility. That is why we set accessible first (new
* API in reflect 1.2)
*/
- AccessController.doPrivileged(new PriviAction<Object>(
- field));
+ field.setAccessible(true);
try {
// Static field, parameter is ignored
return field.getLong(null);
@@ -1139,7 +1136,7 @@
Class<?>[] param) {
try {
Method method = cl.getDeclaredMethod(methodName, param);
- if (Modifier.isPrivate(method.getModifiers()) && method.getReturnType() == Void.TYPE) {
+ if (Modifier.isPrivate(method.getModifiers()) && method.getReturnType() == void.class) {
method.setAccessible(true);
return method;
}
@@ -1279,19 +1276,19 @@
}
private int primitiveSize(Class<?> type) {
- if (type == Byte.TYPE || type == Boolean.TYPE) {
+ if (type == byte.class || type == boolean.class) {
return 1;
}
- if (type == Short.TYPE || type == Character.TYPE) {
+ if (type == short.class || type == char.class) {
return 2;
}
- if (type == Integer.TYPE || type == Float.TYPE) {
+ if (type == int.class || type == float.class) {
return 4;
}
- if (type == Long.TYPE || type == Double.TYPE) {
+ if (type == long.class || type == double.class) {
return 8;
}
- return 0;
+ throw new AssertionError();
}
/**
diff --git a/luni/src/main/java/java/io/ObjectStreamField.java b/luni/src/main/java/java/io/ObjectStreamField.java
index 3ae34e6..db450e0 100644
--- a/luni/src/main/java/java/io/ObjectStreamField.java
+++ b/luni/src/main/java/java/io/ObjectStreamField.java
@@ -159,9 +159,7 @@
*
* @return A Class object representing the type of the field
*/
- // BEGIN android-note
// Changed from private to default visibility for usage in ObjectStreamClass
- // END android-note
/* package */ Class<?> getTypeInternal() {
if (type instanceof WeakReference) {
return (Class<?>) ((WeakReference<?>) type).get();
@@ -206,21 +204,21 @@
}
private char typeCodeOf(Class<?> type) {
- if (type == Integer.TYPE) {
+ if (type == int.class) {
return 'I';
- } else if (type == Byte.TYPE) {
+ } else if (type == byte.class) {
return 'B';
- } else if (type == Character.TYPE) {
+ } else if (type == char.class) {
return 'C';
- } else if (type == Short.TYPE) {
+ } else if (type == short.class) {
return 'S';
- } else if (type == Boolean.TYPE) {
+ } else if (type == boolean.class) {
return 'Z';
- } else if (type == Long.TYPE) {
+ } else if (type == long.class) {
return 'J';
- } else if (type == Float.TYPE) {
+ } else if (type == float.class) {
return 'F';
- } else if (type == Double.TYPE) {
+ } else if (type == double.class) {
return 'D';
} else if (type.isArray()) {
return '[';
@@ -333,28 +331,28 @@
private boolean defaultResolve() {
switch (typeString.charAt(0)) {
case 'I':
- type = Integer.TYPE;
+ type = int.class;
return true;
case 'B':
- type = Byte.TYPE;
+ type = byte.class;
return true;
case 'C':
- type = Character.TYPE;
+ type = char.class;
return true;
case 'S':
- type = Short.TYPE;
+ type = short.class;
return true;
case 'Z':
- type = Boolean.TYPE;
+ type = boolean.class;
return true;
case 'J':
- type = Long.TYPE;
+ type = long.class;
return true;
case 'F':
- type = Float.TYPE;
+ type = float.class;
return true;
case 'D':
- type = Double.TYPE;
+ type = double.class;
return true;
default:
type = Object.class;
diff --git a/luni/src/main/java/java/io/OutputStream.java b/luni/src/main/java/java/io/OutputStream.java
index 95f6102..5b40b44 100644
--- a/luni/src/main/java/java/io/OutputStream.java
+++ b/luni/src/main/java/java/io/OutputStream.java
@@ -76,9 +76,6 @@
* if an error occurs while writing to this stream.
*/
public void write(byte[] buffer) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
write(buffer, 0, buffer.length);
}
diff --git a/luni/src/main/java/java/io/OutputStreamWriter.java b/luni/src/main/java/java/io/OutputStreamWriter.java
index 699263d..62f825d 100644
--- a/luni/src/main/java/java/io/OutputStreamWriter.java
+++ b/luni/src/main/java/java/io/OutputStreamWriter.java
@@ -126,8 +126,8 @@
* Closes this writer. This implementation flushes the buffer as well as the
* target stream. The target stream is then closed and the resources for the
* buffer and converter are released.
- * <p>
- * Only the first invocation of this method has any effect. Subsequent calls
+ *
+ * <p>Only the first invocation of this method has any effect. Subsequent calls
* do nothing.
*
* @throws IOException
@@ -137,9 +137,8 @@
public void close() throws IOException {
synchronized (lock) {
if (encoder != null) {
- encoder.flush(bytes);
- flush();
- out.flush();
+ drainEncoder();
+ flushBytes(false);
out.close();
encoder = null;
bytes = null;
@@ -157,15 +156,66 @@
*/
@Override
public void flush() throws IOException {
+ flushBytes(true);
+ }
+
+ private void flushBytes(boolean flushUnderlyingStream) throws IOException {
synchronized (lock) {
checkStatus();
- int position;
- if ((position = bytes.position()) > 0) {
+ int position = bytes.position();
+ if (position > 0) {
bytes.flip();
- out.write(bytes.array(), 0, position);
+ out.write(bytes.array(), bytes.arrayOffset(), position);
bytes.clear();
}
- out.flush();
+ if (flushUnderlyingStream) {
+ out.flush();
+ }
+ }
+ }
+
+ private void convert(CharBuffer chars) throws IOException {
+ while (true) {
+ CoderResult result = encoder.encode(chars, bytes, false);
+ if (result.isOverflow()) {
+ // Make room and try again.
+ flushBytes(false);
+ continue;
+ } else if (result.isError()) {
+ result.throwException();
+ }
+ break;
+ }
+ }
+
+ private void drainEncoder() throws IOException {
+ // Strictly speaking, I think it's part of the CharsetEncoder contract that you call
+ // encode with endOfInput true before flushing. Our ICU-based implementations don't
+ // actually need this, and you'd hope that any reasonable implementation wouldn't either.
+ // CharsetEncoder.encode doesn't actually pass the boolean through to encodeLoop anyway!
+ CharBuffer chars = CharBuffer.allocate(0);
+ while (true) {
+ CoderResult result = encoder.encode(chars, bytes, true);
+ if (result.isError()) {
+ result.throwException();
+ } else if (result.isOverflow()) {
+ flushBytes(false);
+ continue;
+ }
+ break;
+ }
+
+ // Some encoders (such as ISO-2022-JP) have stuff to write out after all the
+ // characters (such as shifting back into a default state). In our implementation,
+ // this is actually the first time ICU is told that we've run out of input.
+ CoderResult result = encoder.flush(bytes);
+ while (!result.isUnderflow()) {
+ if (result.isOverflow()) {
+ flushBytes(false);
+ result = encoder.flush(bytes);
+ } else {
+ result.throwException();
+ }
}
}
@@ -176,11 +226,10 @@
}
/**
- * Gets the name of the encoding that is used to convert characters to
- * bytes.
- *
- * @return the string describing the converter or {@code null} if this
- * writer is closed.
+ * Returns the historical name of the encoding used by this writer to convert characters to
+ * bytes, or null if this writer has been closed. Most callers should probably keep
+ * track of the String or Charset they passed in; this method may not return the same
+ * name.
*/
public String getEncoding() {
if (encoder == null) {
@@ -219,21 +268,6 @@
}
}
- private void convert(CharBuffer chars) throws IOException {
- 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
- flush();
- result = encoder.encode(chars, bytes, true);
- continue;
- }
- break;
- }
- }
-
/**
* Writes the character {@code oneChar} to this writer. The lowest two bytes
* of the integer {@code oneChar} are immediately converted to bytes by the
diff --git a/luni/src/main/java/java/io/PipedOutputStream.java b/luni/src/main/java/java/io/PipedOutputStream.java
index 6df3fa2..4fa70fa 100644
--- a/luni/src/main/java/java/io/PipedOutputStream.java
+++ b/luni/src/main/java/java/io/PipedOutputStream.java
@@ -15,12 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// We've made several changes including:
-// - avoid shallow concurrency problems
-// - improved consistency with PipedWriter
-// END android-note
-
package java.io;
/**
diff --git a/luni/src/main/java/java/io/PrintStream.java b/luni/src/main/java/java/io/PrintStream.java
index 42e6750..5adf3ef 100644
--- a/luni/src/main/java/java/io/PrintStream.java
+++ b/luni/src/main/java/java/io/PrintStream.java
@@ -19,12 +19,10 @@
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
-import java.security.AccessController;
import java.util.Arrays;
import java.util.Formatter;
import java.util.IllegalFormatException;
import java.util.Locale;
-import org.apache.harmony.luni.util.PriviAction;
/**
* Wraps an existing {@link OutputStream} and provides convenience methods for
@@ -48,8 +46,7 @@
private String encoding;
- private final String lineSeparator = AccessController
- .doPrivileged(new PriviAction<String>("line.separator"));
+ private final String lineSeparator = System.getProperty("line.separator");
// private Formatter formatter;
@@ -136,9 +133,6 @@
* removed, otherwise a new file is created.
* @throws FileNotFoundException
* if an error occurs while opening or creating the target file.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
*/
public PrintStream(File file) throws FileNotFoundException {
super(new FileOutputStream(file));
@@ -157,9 +151,6 @@
* if an error occurs while opening or creating the target file.
* @throws NullPointerException
* if {@code csn} is {@code null}.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
* @throws UnsupportedEncodingException
* if the encoding specified by {@code csn} is not supported.
*/
@@ -185,9 +176,6 @@
* contents are removed, otherwise a new file is created.
* @throws FileNotFoundException
* if an error occurs while opening or creating the target file.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
*/
public PrintStream(String fileName) throws FileNotFoundException {
this(new File(fileName));
@@ -207,9 +195,6 @@
* if an error occurs while opening or creating the target file.
* @throws NullPointerException
* if {@code csn} is {@code null}.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
* @throws UnsupportedEncodingException
* if the encoding specified by {@code csn} is not supported.
*/
diff --git a/luni/src/main/java/java/io/PrintWriter.java b/luni/src/main/java/java/io/PrintWriter.java
index 3bc14b8..0c9c8fb 100644
--- a/luni/src/main/java/java/io/PrintWriter.java
+++ b/luni/src/main/java/java/io/PrintWriter.java
@@ -17,11 +17,9 @@
package java.io;
-import java.security.AccessController;
import java.util.Formatter;
import java.util.IllegalFormatException;
import java.util.Locale;
-import org.apache.harmony.luni.util.PriviAction;
/**
* Wraps either an existing {@link OutputStream} or an existing {@link Writer}
@@ -47,8 +45,7 @@
*/
private boolean autoflush;
- private final String lineSeparator = AccessController
- .doPrivileged(new PriviAction<String>("line.separator"));
+ private final String lineSeparator = System.getProperty("line.separator");
/**
* Constructs a new {@code PrintWriter} with {@code out} as its target
@@ -127,9 +124,6 @@
* removed, otherwise a new file is created.
* @throws FileNotFoundException
* if an error occurs while opening or creating the target file.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
*/
public PrintWriter(File file) throws FileNotFoundException {
this(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file))), false);
@@ -150,9 +144,6 @@
* if an error occurs while opening or creating the target file.
* @throws NullPointerException
* if {@code csn} is {@code null}.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
* @throws UnsupportedEncodingException
* if the encoding specified by {@code csn} is not supported.
*/
@@ -174,9 +165,6 @@
* contents are removed, otherwise a new file is created.
* @throws FileNotFoundException
* if an error occurs while opening or creating the target file.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
*/
public PrintWriter(String fileName) throws FileNotFoundException {
this(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(fileName))),
@@ -199,9 +187,6 @@
* if an error occurs while opening or creating the target file.
* @throws NullPointerException
* if {@code csn} is {@code null}.
- * @throws SecurityException
- * if a security manager exists and it denies writing to the
- * target file.
* @throws UnsupportedEncodingException
* if the encoding specified by {@code csn} is not supported.
*/
@@ -634,9 +619,6 @@
*/
@Override
public void write(char[] buf) {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
write(buf, 0, buf.length);
}
@@ -659,9 +641,6 @@
*/
@Override
public void write(char[] buf, int offset, int count) {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
doWrite(buf, offset, count);
}
@@ -681,9 +660,6 @@
}
private final void doWrite(char[] buf, int offset, int count) {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
synchronized (lock) {
if (out != null) {
try {
diff --git a/luni/src/main/java/java/io/RandomAccessFile.java b/luni/src/main/java/java/io/RandomAccessFile.java
index b5ac0b7..20f706c 100644
--- a/luni/src/main/java/java/io/RandomAccessFile.java
+++ b/luni/src/main/java/java/io/RandomAccessFile.java
@@ -95,11 +95,6 @@
* @throws IllegalArgumentException
* if {@code mode} is not {@code "r"}, {@code "rw"}, {@code
* "rws"} or {@code "rwd"}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies
- * access request according to {@code mode}.
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
- * @see java.lang.SecurityManager#checkWrite(FileDescriptor)
*/
public RandomAccessFile(File file, String mode) throws FileNotFoundException {
int options;
@@ -123,14 +118,6 @@
}
this.mode = options;
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(file.getPath());
- if (!mode.equals("r")) {
- security.checkWrite(file.getPath());
- }
- }
-
fd.descriptor = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), this.mode);
// if we are in "rws" mode, attempt to sync file+metadata
@@ -161,11 +148,6 @@
* @throws IllegalArgumentException
* if {@code mode} is not {@code "r"}, {@code "rw"}, {@code
* "rws"} or {@code "rwd"}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and it denies
- * access request according to {@code mode}.
- * @see java.lang.SecurityManager#checkRead(FileDescriptor)
- * @see java.lang.SecurityManager#checkWrite(FileDescriptor)
*/
public RandomAccessFile(String fileName, String mode) throws FileNotFoundException {
this(new File(fileName), mode);
diff --git a/luni/src/main/java/java/io/Reader.java b/luni/src/main/java/java/io/Reader.java
index 82f3ac5..8c37436 100644
--- a/luni/src/main/java/java/io/Reader.java
+++ b/luni/src/main/java/java/io/Reader.java
@@ -143,9 +143,6 @@
* if this reader is closed or some other I/O error occurs.
*/
public int read(char[] buf) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
return read(buf, 0, buf.length);
}
@@ -167,11 +164,7 @@
* @throws IOException
* if this reader is closed or some other I/O error occurs.
*/
- public abstract int read(char[] buf, int offset, int count)
- throws IOException;
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
+ public abstract int read(char[] buf, int offset, int count) throws IOException;
/**
* Indicates whether this reader is ready to be read without blocking.
diff --git a/luni/src/main/java/java/io/StreamTokenizer.java b/luni/src/main/java/java/io/StreamTokenizer.java
index 36c42bf..0522be6 100644
--- a/luni/src/main/java/java/io/StreamTokenizer.java
+++ b/luni/src/main/java/java/io/StreamTokenizer.java
@@ -17,6 +17,8 @@
package java.io;
+import java.util.Locale;
+
/**
* Parses a stream into a set of defined tokens, one at a time. The different
* types of tokens that can be found are numbers, identifiers, quoted strings,
@@ -346,8 +348,10 @@
}
}
peekChar = currentChar;
- sval = forceLowercase ? word.toString().toLowerCase() : word
- .toString();
+ sval = word.toString();
+ if (forceLowercase) {
+ sval = sval.toLowerCase(Locale.getDefault());
+ }
return (ttype = TT_WORD);
}
// Check for quoted character
diff --git a/luni/src/main/java/java/io/Writer.java b/luni/src/main/java/java/io/Writer.java
index d1ff429..a766137 100644
--- a/luni/src/main/java/java/io/Writer.java
+++ b/luni/src/main/java/java/io/Writer.java
@@ -92,9 +92,6 @@
* if this writer is closed or another I/O error occurs.
*/
public void write(char[] buf) throws IOException {
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
write(buf, 0, buf.length);
}
@@ -114,11 +111,7 @@
* @throws IOException
* if this writer is closed or another I/O error occurs.
*/
- public abstract void write(char[] buf, int offset, int count)
- throws IOException;
- // BEGIN android-note
- // changed array notation to be consistent with the rest of harmony
- // END android-note
+ public abstract void write(char[] buf, int offset, int count) throws IOException;
/**
* Writes one character to the target. Only the two least significant bytes
diff --git a/luni/src/main/java/java/lang/AbstractStringBuilder.java b/luni/src/main/java/java/lang/AbstractStringBuilder.java
index 4a7410d..f36ea10 100644
--- a/luni/src/main/java/java/lang/AbstractStringBuilder.java
+++ b/luni/src/main/java/java/lang/AbstractStringBuilder.java
@@ -86,9 +86,7 @@
count = string.length();
shared = false;
value = new char[count + INITIAL_CAPACITY];
- // BEGIN android-changed
string._getChars(0, count, value, 0);
- // END android-changed
}
private void enlargeBuffer(int min) {
@@ -355,9 +353,7 @@
int min = string.length();
if (min != 0) {
move(min, index);
- // BEGIN android-changed
string._getChars(0, min, value, index);
- // END android-changed
count += min;
}
} else {
@@ -434,9 +430,7 @@
value = value.clone();
shared = false;
}
- // BEGIN android-changed
string._getChars(0, stringLength, value, start);
- // END android-changed
count -= diff;
return;
}
diff --git a/luni/src/main/java/java/lang/Boolean.java b/luni/src/main/java/java/lang/Boolean.java
index 8b1cc7a..f017aad 100644
--- a/luni/src/main/java/java/lang/Boolean.java
+++ b/luni/src/main/java/java/lang/Boolean.java
@@ -40,7 +40,7 @@
@SuppressWarnings("unchecked")
public static final Class<Boolean> TYPE
= (Class<Boolean>) boolean[].class.getComponentType();
- // Note: This can't be set to "boolean.class", since *that* is
+ // Note: Boolean.TYPE can't be set to "boolean.class", since *that* is
// defined to be "java.lang.Boolean.TYPE";
/**
diff --git a/luni/src/main/java/java/lang/Byte.java b/luni/src/main/java/java/lang/Byte.java
index ff36aac..e1224f3 100644
--- a/luni/src/main/java/java/lang/Byte.java
+++ b/luni/src/main/java/java/lang/Byte.java
@@ -55,7 +55,7 @@
@SuppressWarnings("unchecked")
public static final Class<Byte> TYPE
= (Class<Byte>) byte[].class.getComponentType();
- // Note: This can't be set to "byte.class", since *that* is
+ // Note: Byte.TYPE can't be set to "byte.class", since *that* is
// defined to be "java.lang.Byte.TYPE";
/**
@@ -219,6 +219,14 @@
}
/**
+ * Returns a two-digit hex string. That is, -1 becomes "ff" or "FF" and 2 becomes "02".
+ * @hide internal use only
+ */
+ public static String toHexString(byte b, boolean upperCase) {
+ return IntegralToString.byteToHexString(b, upperCase);
+ }
+
+ /**
* Returns a string containing a concise, human-readable description of the
* specified byte value.
*
diff --git a/luni/src/main/java/java/lang/Character.java b/luni/src/main/java/java/lang/Character.java
index 0caabba..046502f 100644
--- a/luni/src/main/java/java/lang/Character.java
+++ b/luni/src/main/java/java/lang/Character.java
@@ -127,8 +127,7 @@
@SuppressWarnings("unchecked")
public static final Class<Character> TYPE
= (Class<Character>) char[].class.getComponentType();
-
- // Note: This can't be set to "char.class", since *that* is
+ // Note: Character.TYPE can't be set to "char.class", since *that* is
// defined to be "java.lang.Character.TYPE";
/**
@@ -2694,9 +2693,7 @@
* {@code false} otherwise.
*/
public static boolean isJavaIdentifierPart(char c) {
- // BEGIN android-changed
return isJavaIdentifierPart((int) c);
- // END android-changed
}
/**
@@ -2709,8 +2706,7 @@
* {@code false} otherwise.
*/
public static boolean isJavaIdentifierPart(int codePoint) {
- // BEGIN android-changed: use precomputed bitmasks for the ASCII range.
- // Optimized case for ASCII
+ // Use precomputed bitmasks to optimize the ASCII range.
if (codePoint < 64) {
return (0x3ff00100fffc1ffL & (1L << codePoint)) != 0;
} else if (codePoint < 128) {
@@ -2723,7 +2719,6 @@
|| type == COMBINING_SPACING_MARK || type == NON_SPACING_MARK
|| (codePoint >= 0 && codePoint <= 8) || (codePoint >= 0xe && codePoint <= 0x1b)
|| (codePoint >= 0x7f && codePoint <= 0x9f) || type == FORMAT;
- // END android-changed
}
/**
@@ -2736,9 +2731,7 @@
* identifier; {@code false} otherwise.
*/
public static boolean isJavaIdentifierStart(char c) {
- // BEGIN android-changed
return isJavaIdentifierStart((int) c);
- // END android-changed
}
/**
@@ -2751,8 +2744,7 @@
* identifier; {@code false} otherwise.
*/
public static boolean isJavaIdentifierStart(int codePoint) {
- // BEGIN android-changed: use precomputed bitmasks for the ASCII range.
- // Optimized case for ASCII
+ // Use precomputed bitmasks to optimize the ASCII range.
if (codePoint < 64) {
return (codePoint == '$'); // There's only one character in this range.
} else if (codePoint < 128) {
@@ -2761,7 +2753,6 @@
int type = getType(codePoint);
return (type >= UPPERCASE_LETTER && type <= OTHER_LETTER) || type == CURRENCY_SYMBOL
|| type == CONNECTOR_PUNCTUATION || type == LETTER_NUMBER;
- // END android-changed
}
/**
diff --git a/luni/src/main/java/java/lang/Class.java b/luni/src/main/java/java/lang/Class.java
index ea29737..8c4b947 100644
--- a/luni/src/main/java/java/lang/Class.java
+++ b/luni/src/main/java/java/lang/Class.java
@@ -206,14 +206,6 @@
ClassLoader classLoader) throws ClassNotFoundException {
if (classLoader == null) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- ClassLoader calling = VMStack.getCallingClassLoader();
- if (calling != null) {
- smgr.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
classLoader = ClassLoader.getSystemClassLoader();
}
// Catch an Exception thrown by the underlying native code. It wraps
@@ -257,12 +249,8 @@
* of length 0 is returned.
*
* @return the public class members of the class represented by this object.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
*/
public Class<?>[] getClasses() {
- checkPublicMemberAccess();
return getFullListOfClasses(true);
}
@@ -377,37 +365,24 @@
* representation of the bootstrap class loader.
*
* @return the class loader for the represented class.
- * @throws SecurityException
- * if a security manager exists and it does not allow accessing
- * the class loader.
* @see ClassLoader
*/
public ClassLoader getClassLoader() {
- SecurityManager smgr = System.getSecurityManager();
- ClassLoader loader = getClassLoaderImpl();
- if (smgr != null && loader != null) {
- ClassLoader calling = VMStack.getCallingClassLoader();
-
- if (calling != null && !calling.isAncestorOf(loader)) {
- smgr.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
if (this.isPrimitive()) {
return null;
}
+ ClassLoader loader = getClassLoaderImpl();
if (loader == null) {
loader = BootClassLoader.getInstance();
}
-
return loader;
}
/**
* This must be provided by the VM vendor, as it is used by other provided
* class implementations in this package. Outside of this class, it is used
- * by SecurityManager.checkMemberAccess(), classLoaderDepth(),
+ * by SecurityManager.classLoaderDepth(),
* currentClassLoader() and currentLoadedClass(). Return the ClassLoader for
* this Class without doing any security checks. The bootstrap ClassLoader
* is returned, unlike getClassLoader() which returns null in place of the
@@ -449,15 +424,10 @@
* @return the constructor described by {@code parameterTypes}.
* @throws NoSuchMethodException
* if the constructor can not be found.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getDeclaredConstructor(Class[])
*/
@SuppressWarnings("unchecked")
- public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,
- SecurityException {
- checkPublicMemberAccess();
+ public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException {
return getMatchingConstructor(getDeclaredConstructors(this, true), parameterTypes);
}
@@ -469,13 +439,9 @@
*
* @return an array with the public constructors of the class represented by
* this {@code Class}.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getDeclaredConstructors()
*/
- public Constructor<?>[] getConstructors() throws SecurityException {
- checkPublicMemberAccess();
+ public Constructor<?>[] getConstructors() {
return getDeclaredConstructors(this, true);
}
@@ -500,12 +466,8 @@
*
* @return an array with {@code Class} objects for all the classes and
* interfaces that are used in member declarations.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
*/
- public Class<?>[] getDeclaredClasses() throws SecurityException {
- checkDeclaredMemberAccess();
+ public Class<?>[] getDeclaredClasses() {
return getDeclaredClasses(this, false);
}
@@ -556,15 +518,11 @@
* @return the constructor described by {@code parameterTypes}.
* @throws NoSuchMethodException
* if the requested constructor can not be found.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getConstructor(Class[])
*/
@SuppressWarnings("unchecked")
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
- throws NoSuchMethodException, SecurityException {
- checkDeclaredMemberAccess();
+ throws NoSuchMethodException {
return getMatchingConstructor(getDeclaredConstructors(this, false), parameterTypes);
}
@@ -576,14 +534,9 @@
*
* @return an array with the constructors declared in the class represented
* by this {@code Class}.
- *
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getConstructors()
*/
- public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
- checkDeclaredMemberAccess();
+ public Constructor<?>[] getDeclaredConstructors() {
return getDeclaredConstructors(this, false);
}
@@ -614,7 +567,6 @@
}
}
- // BEGIN android-changed
StringBuilder sb = new StringBuilder();
sb.append(getSimpleName());
sb.append('(');
@@ -630,7 +582,6 @@
}
sb.append(')');
throw new NoSuchMethodException(sb.toString());
- // END android-changed
}
/**
@@ -642,14 +593,9 @@
* @return the requested field in the class represented by this class.
* @throws NoSuchFieldException
* if the requested field can not be found.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getField(String)
*/
- public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException {
- checkDeclaredMemberAccess();
-
+ public Field getDeclaredField(String name) throws NoSuchFieldException {
Field[] fields = getClassMembers().getDeclaredFields();
Field field = findFieldByName(fields, name);
@@ -668,14 +614,9 @@
*
* @return an array with the fields declared in the class represented by
* this class.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getFields()
*/
- public Field[] getDeclaredFields() throws SecurityException {
- checkDeclaredMemberAccess();
-
+ public Field[] getDeclaredFields() {
// Return a copy of the private (to the package) array.
Field[] fields = getClassMembers().getDeclaredFields();
return ClassMembers.deepCopy(fields);
@@ -706,15 +647,10 @@
* if the requested constructor can not be found.
* @throws NullPointerException
* if {@code name} is {@code null}.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getMethod(String, Class[])
*/
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
- throws NoSuchMethodException, SecurityException {
- checkDeclaredMemberAccess();
-
+ throws NoSuchMethodException {
Method[] methods = getClassMembers().getDeclaredMethods();
Method method = findMethodByName(methods, name, parameterTypes);
@@ -733,14 +669,9 @@
*
* @return an array with the methods declared in the class represented by
* this {@code Class}.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getMethods()
*/
- public Method[] getDeclaredMethods() throws SecurityException {
- checkDeclaredMemberAccess();
-
+ public Method[] getDeclaredMethods() {
// Return a copy of the private (to the package) array.
Method[] methods = getClassMembers().getDeclaredMethods();
return ClassMembers.deepCopy(methods);
@@ -803,7 +734,6 @@
@SuppressWarnings("unchecked")
public T[] getEnumConstants() {
if (isEnum()) {
- checkPublicMemberAccess();
T[] values = getClassMembers().getEnumValuesInOrder();
// Copy the private (to the package) array.
@@ -824,14 +754,9 @@
* @return the public field specified by {@code name}.
* @throws NoSuchFieldException
* if the field can not be found.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getDeclaredField(String)
*/
- public Field getField(String name) throws NoSuchFieldException, SecurityException {
- checkPublicMemberAccess();
-
+ public Field getField(String name) throws NoSuchFieldException {
Field[] fields = getClassMembers().getAllPublicFields();
Field field = findFieldByName(fields, name);
@@ -867,21 +792,15 @@
* for the class C represented by this {@code Class}. Fields may be declared
* in C, the interfaces it implements or in the superclasses of C. The
* elements in the returned array are in no particular order.
- * <p>
- * If there are no public fields or if this class represents an array class,
+ *
+ * <p>If there are no public fields or if this class represents an array class,
* a primitive type or {@code void} then an empty array is returned.
- * </p>
*
* @return an array with the public fields of the class represented by this
* {@code Class}.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getDeclaredFields()
*/
- public Field[] getFields() throws SecurityException {
- checkPublicMemberAccess();
-
+ public Field[] getFields() {
// Return a copy of the private (to the package) array.
Field[] fields = getClassMembers().getAllPublicFields();
return ClassMembers.deepCopy(fields);
@@ -941,15 +860,9 @@
* @return the public field specified by {@code name}.
* @throws NoSuchMethodException
* if the method can not be found.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getDeclaredMethod(String, Class[])
*/
- public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException,
- SecurityException {
- checkPublicMemberAccess();
-
+ public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException {
Method[] methods = getClassMembers().getMethods();
Method method = findMethodByName(methods, name, parameterTypes);
@@ -972,65 +885,15 @@
*
* @return an array with the methods of the class represented by this
* {@code Class}.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
* @see #getDeclaredMethods()
*/
- public Method[] getMethods() throws SecurityException {
- checkPublicMemberAccess();
-
+ public Method[] getMethods() {
// Return a copy of the private (to the package) array.
Method[] methods = getClassMembers().getMethods();
return ClassMembers.deepCopy(methods);
}
/**
- * Performs the security checks regarding the access of a public
- * member of this {@code Class}.
- *
- * <p><b>Note:</b> Because of the {@code getCallingClassLoader2()}
- * check, this method must be called exactly one level deep into a
- * public method on this instance.</p>
- */
- /*package*/ void checkPublicMemberAccess() {
- SecurityManager smgr = System.getSecurityManager();
-
- if (smgr != null) {
- smgr.checkMemberAccess(this, Member.PUBLIC);
-
- ClassLoader calling = VMStack.getCallingClassLoader2();
- ClassLoader current = getClassLoader();
-
- if (calling != null && !calling.isAncestorOf(current)) {
- smgr.checkPackageAccess(this.getPackage().getName());
- }
- }
- }
-
- /**
- * Performs the security checks regarding the access of a declared
- * member of this {@code Class}.
- *
- * <p><b>Note:</b> Because of the {@code getCallingClassLoader2()}
- * check, this method must be called exactly one level deep into a
- * public method on this instance.</p>
- */
- private void checkDeclaredMemberAccess() {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkMemberAccess(this, Member.DECLARED);
-
- ClassLoader calling = VMStack.getCallingClassLoader2();
- ClassLoader current = getClassLoader();
-
- if (calling != null && !calling.isAncestorOf(current)) {
- smgr.checkPackageAccess(this.getPackage().getName());
- }
- }
- }
-
- /**
* Returns an integer that represents the modifiers of the class represented
* by this {@code Class}. The returned value is a combination of bits
* defined by constants in the {@link Modifier} class.
@@ -1116,17 +979,8 @@
*
* @return the {@code ProtectionDomain} of the class represented by this
* class.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
*/
public ProtectionDomain getProtectionDomain() {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- // Security check is independent of calling class loader.
- smgr.checkPermission(new RuntimePermission("getProtectionDomain"));
- }
-
return pd;
}
@@ -1392,22 +1246,17 @@
* if the default constructor is not visible.
* @throws InstantiationException
* if the instance can not be created.
- * @throws SecurityException
- * if a security manager exists and it does not allow creating
- * new instances.
*/
public T newInstance() throws InstantiationException, IllegalAccessException {
- checkPublicMemberAccess();
return newInstanceImpl();
}
- private native T newInstanceImpl() throws IllegalAccessException,
- InstantiationException;
+ private native T newInstanceImpl() throws IllegalAccessException, InstantiationException;
@Override
public String toString() {
if (isPrimitive()) {
- return getSimpleName().toLowerCase();
+ return getSimpleName();
} else {
return (isInterface() ? "interface " : "class ") + getName();
}
@@ -1498,8 +1347,7 @@
* @param ao non-null; the object to modify
* @param flag the new value for the accessible flag
*/
- /*package*/ static native void setAccessibleNoCheck(AccessibleObject ao,
- boolean flag);
+ /*package*/ static native void setAccessibleNoCheck(AccessibleObject ao, boolean flag);
/**
* Copies two arrays into one. Assumes that the destination array is large
@@ -1515,42 +1363,4 @@
System.arraycopy(tail, 0, result, head.length, tail.length);
return result;
}
-
- /**
- * This must be provided by the vm vendor, as it is used by other provided
- * class implementations in this package. This method is used by
- * SecurityManager.classDepth(), and getClassContext() which use the
- * parameters (-1, false) and SecurityManager.classLoaderDepth(),
- * currentClassLoader(), and currentLoadedClass() which use the parameters
- * (-1, true). Walk the stack and answer an array containing the maxDepth
- * most recent classes on the stack of the calling thread. Starting with the
- * caller of the caller of getStackClasses(), return an array of not more
- * than maxDepth Classes representing the classes of running methods on the
- * stack (including native methods). Frames representing the VM
- * implementation of java.lang.reflect are not included in the list. If
- * stopAtPrivileged is true, the walk will terminate at any frame running
- * one of the following methods: <code><ul>
- * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object;</li>
- * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;)Ljava/lang/Object;</li>
- * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;</li>
- * <li>java/security/AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;</li>
- * </ul></code> If one of the doPrivileged methods is found, the walk terminate
- * and that frame is NOT included in the returned array. Notes:
- * <ul>
- * <li>This method operates on the defining classes of methods on stack.
- * NOT the classes of receivers.</li>
- * <li>The item at index zero in the result array describes the caller of
- * the caller of this method.</li>
- * </ul>
- *
- * @param maxDepth
- * maximum depth to walk the stack, -1 for the entire stack
- * @param stopAtPrivileged
- * stop at privileged classes
- * @return the array of the most recent classes on the stack
- */
- static Class<?>[] getStackClasses(int maxDepth, boolean stopAtPrivileged) {
- return VMStack.getClasses(maxDepth, stopAtPrivileged);
- }
-
}
diff --git a/luni/src/main/java/java/lang/ClassLoader.java b/luni/src/main/java/java/lang/ClassLoader.java
index 43990cc..01d7198 100644
--- a/luni/src/main/java/java/lang/ClassLoader.java
+++ b/luni/src/main/java/java/lang/ClassLoader.java
@@ -64,19 +64,16 @@
*/
public abstract class ClassLoader {
- // BEGIN android-note
- /*
+ /**
+ * The 'System' ClassLoader - the one that is responsible for loading
+ * classes from the classpath. It is not equal to the bootstrap class loader -
+ * that one handles the built-in classes.
+ *
* Because of a potential class initialization race between ClassLoader and
* java.lang.System, reproducible when using JDWP with "suspend=y", we defer
* creation of the system class loader until first use. We use a static
* inner class to get synchronization at init time without having to sync on
* every access.
- */
- // END android-note
- /**
- * The 'System' ClassLoader - the one that is responsible for loading
- * classes from the classpath. It is not equal to the bootstrap class loader -
- * that one handles the built-in classes.
*
* @see #getSystemClassLoader()
*/
@@ -122,27 +119,9 @@
/**
* Returns the system class loader. This is the parent for new
* {@code ClassLoader} instances and is typically the class loader used to
- * start the application. If a security manager is present and the caller's
- * class loader is neither {@code null} nor the same as or an ancestor of
- * the system class loader, then this method calls the security manager's
- * checkPermission method with a RuntimePermission("getClassLoader")
- * permission to ensure that it is ok to access the system class loader. If
- * not, a {@code SecurityException} is thrown.
- *
- * @return the system class loader.
- * @throws SecurityException
- * if a security manager exists and it does not allow access to
- * the system class loader.
+ * start the application.
*/
public static ClassLoader getSystemClassLoader() {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- ClassLoader caller = VMStack.getCallingClassLoader();
- if (caller != null && !caller.isAncestorOf(SystemClassLoader.loader)) {
- smgr.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
return SystemClassLoader.loader;
}
@@ -194,10 +173,6 @@
/**
* Constructs a new instance of this class with the system class loader as
* its parent.
- *
- * @throws SecurityException
- * if a security manager exists and it does not allow the
- * creation of a new {@code ClassLoader}.
*/
protected ClassLoader() {
this(getSystemClassLoader(), false);
@@ -210,9 +185,6 @@
* @param parentLoader
* The {@code ClassLoader} to use as the new class loader's
* parent.
- * @throws SecurityException
- * if a security manager exists and it does not allow the
- * creation of new a new {@code ClassLoader}.
*/
protected ClassLoader(ClassLoader parentLoader) {
this(parentLoader, false);
@@ -222,16 +194,9 @@
* constructor for the BootClassLoader which needs parent to be null.
*/
ClassLoader(ClassLoader parentLoader, boolean nullAllowed) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkCreateClassLoader();
- }
-
if (parentLoader == null && !nullAllowed) {
- throw new NullPointerException(
- "Parent ClassLoader may not be null");
+ throw new NullPointerException("Parent ClassLoader may not be null");
}
-
parent = parentLoader;
}
@@ -408,16 +373,8 @@
* Returns this class loader's parent.
*
* @return this class loader's parent or {@code null}.
- * @throws SecurityException
- * if a security manager exists and it does not allow to
- * retrieve the parent class loader.
*/
public final ClassLoader getParent() {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkPermission(new RuntimePermission("getClassLoader"));
- }
-
return parent;
}
@@ -430,8 +387,7 @@
* @param resName
* the name of the resource to find.
* @return the {@code URL} object for the requested resource or {@code null}
- * if either the resource can not be found or a security manager
- * does not allow to access the resource.
+ * if the resource can not be found
* @see Class#getResource
*/
public URL getResource(String resName) {
@@ -469,9 +425,7 @@
* {@link #getResource(String)} for a description of the lookup algorithm
* used to find the resource.
*
- * @return a stream for the resource or {@code null} if either the resource
- * can not be found or a security manager does not allow to access
- * the resource.
+ * @return a stream for the resource or {@code null} if the resource can not be found
* @param resName
* the name of the resource to find.
* @see Class#getResourceAsStream
@@ -828,8 +782,6 @@
* the classloader in which to load the library
* @throws UnsatisfiedLinkError
* if the library could not be loaded
- * @throws SecurityException
- * if the library was not allowed to be loaded
* <p>
* <strong>Note: </strong>This method does nothing in the Android reference
* implementation.
diff --git a/luni/src/main/java/java/lang/Double.java b/luni/src/main/java/java/lang/Double.java
index 0edc4d7..1748128 100644
--- a/luni/src/main/java/java/lang/Double.java
+++ b/luni/src/main/java/java/lang/Double.java
@@ -77,7 +77,7 @@
public static final double MIN_NORMAL = 2.2250738585072014E-308;
/**
- * Maximum exponent that a finite value of the {@code double} type may have.
+ * Maximum base-2 exponent that a finite value of the {@code double} type may have.
* Equal to {@code Math.getExponent(Double.MAX_VALUE)}.
*
* @since 1.6
@@ -85,7 +85,7 @@
public static final int MAX_EXPONENT = 1023;
/**
- * Minimum exponent that a normal value of the {@code double} type may have.
+ * Minimum base-2 exponent that a normal value of the {@code double} type may have.
* Equal to {@code Math.getExponent(Double.MIN_NORMAL)}.
*
* @since 1.6
@@ -101,8 +101,7 @@
@SuppressWarnings("unchecked")
public static final Class<Double> TYPE
= (Class<Double>) double[].class.getComponentType();
-
- // Note: This can't be set to "double.class", since *that* is
+ // Note: Double.TYPE can't be set to "double.class", since *that* is
// defined to be "java.lang.Double.TYPE";
/**
diff --git a/luni/src/main/java/java/lang/Enum.java b/luni/src/main/java/java/lang/Enum.java
index 9a57fd8..7d1eb46 100644
--- a/luni/src/main/java/java/lang/Enum.java
+++ b/luni/src/main/java/java/lang/Enum.java
@@ -17,6 +17,7 @@
package java.lang;
import java.io.Serializable;
+import java.lang.reflect.Method;
/**
* The superclass of all enumerated types. Actual enumeration types inherit from
@@ -163,8 +164,6 @@
throw new NullPointerException("enumType == null || name == null");
}
- enumType.checkPublicMemberAccess();
-
T result = enumType.getClassMembers().getEnumValue(name);
if (result == null) {
if (!enumType.isEnum()) {
diff --git a/luni/src/main/java/java/lang/Float.java b/luni/src/main/java/java/lang/Float.java
index e641eb6..bbbb7f7 100644
--- a/luni/src/main/java/java/lang/Float.java
+++ b/luni/src/main/java/java/lang/Float.java
@@ -74,7 +74,7 @@
public static final float MIN_NORMAL = 1.1754943508222875E-38f;
/**
- * Maximum exponent that a finite value of the {@code float} type may have.
+ * Maximum base-2 exponent that a finite value of the {@code float} type may have.
* Equal to {@code Math.getExponent(Float.MAX_VALUE)}.
*
* @since 1.6
@@ -82,7 +82,7 @@
public static final int MAX_EXPONENT = 127;
/**
- * Minimum exponent that a normal value of the {@code float} type may have.
+ * Minimum base-2 exponent that a normal value of the {@code float} type may have.
* Equal to {@code Math.getExponent(Float.MIN_NORMAL)}.
*
* @since 1.6
@@ -98,8 +98,7 @@
@SuppressWarnings("unchecked")
public static final Class<Float> TYPE
= (Class<Float>) float[].class.getComponentType();
-
- // Note: This can't be set to "float.class", since *that* is
+ // Note: Float.TYPE can't be set to "float.class", since *that* is
// defined to be "java.lang.Float.TYPE";
/**
diff --git a/luni/src/main/java/java/lang/InheritableThreadLocal.java b/luni/src/main/java/java/lang/InheritableThreadLocal.java
index 7e12ac2..772c61b 100644
--- a/luni/src/main/java/java/lang/InheritableThreadLocal.java
+++ b/luni/src/main/java/java/lang/InheritableThreadLocal.java
@@ -51,7 +51,6 @@
return parentValue;
}
- // BEGIN android-added
@Override
Values values(Thread current) {
return current.inheritableValues;
@@ -61,5 +60,4 @@
Values initializeValues(Thread current) {
return current.inheritableValues = new Values();
}
- // END android-added
}
diff --git a/luni/src/main/java/java/lang/Integer.java b/luni/src/main/java/java/lang/Integer.java
index bec53c9..188f404 100644
--- a/luni/src/main/java/java/lang/Integer.java
+++ b/luni/src/main/java/java/lang/Integer.java
@@ -581,14 +581,7 @@
* @since 1.5
*/
public static int numberOfTrailingZeros(int i) {
- // Seal's algorithm - Hacker's Delight 5-18
- // BEGIN android-changed - Harmony version should be one-liner in comment below
- i &= -i;
- i = (i << 4) + i; // x *= 17
- i = (i << 6) + i; // x *= 65
- i = (i << 16) - i; // x *= 65535
- return NTZ_TABLE[i >>> 26]; // NTZ_TABLE[((i & -i) * 0x0450FBAF) >>> 26]
- // END android-changed
+ return NTZ_TABLE[((i & -i) * 0x0450FBAF) >>> 26];
}
/**
diff --git a/luni/src/main/java/java/lang/IntegralToString.java b/luni/src/main/java/java/lang/IntegralToString.java
index 8329a25..51d9523 100644
--- a/luni/src/main/java/java/lang/IntegralToString.java
+++ b/luni/src/main/java/java/lang/IntegralToString.java
@@ -108,6 +108,13 @@
'u', 'v', 'w', 'x', 'y', 'z'
};
+ private static final char[] UPPER_CASE_DIGITS = {
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
+ 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
+ 'U', 'V', 'W', 'X', 'Y', 'Z'
+ };
+
private IntegralToString() {
}
@@ -447,6 +454,14 @@
return new String(cursor, bufLen - cursor, buf);
}
+ public static String byteToHexString(byte b, boolean upperCase) {
+ char[] digits = upperCase ? UPPER_CASE_DIGITS : DIGITS;
+ char[] buf = new char[2]; // We always want two digits.
+ buf[0] = digits[(b >> 4) & 0xf];
+ buf[1] = digits[b & 0xf];
+ return new String(0, 2, buf);
+ }
+
public static String intToHexString(int i) {
int bufLen = 8; // Max number of hex digits in an int
char[] buf = new char[bufLen];
diff --git a/luni/src/main/java/java/lang/Long.java b/luni/src/main/java/java/lang/Long.java
index fa1ae6c..24f2810 100644
--- a/luni/src/main/java/java/lang/Long.java
+++ b/luni/src/main/java/java/lang/Long.java
@@ -700,11 +700,7 @@
* @since 1.5
*/
public static int signum(long v) {
- // BEGIN android-changed
return v < 0 ? -1 : (v == 0 ? 0 : 1);
- // END android-changed
-// The following branch-free version is faster on modern desktops/servers
-// return ((int)(v >> 63)) | (int) (-v >>> 63); // Hacker's delight 2-7
}
/**
diff --git a/luni/src/main/java/java/lang/Math.java b/luni/src/main/java/java/lang/Math.java
index b1179a3..8c3f0a8 100644
--- a/luni/src/main/java/java/lang/Math.java
+++ b/luni/src/main/java/java/lang/Math.java
@@ -1100,7 +1100,7 @@
}
/**
- * Returns the exponent of float {@code f}.
+ * Returns the unbiased base-2 exponent of float {@code f}.
* @since 1.6
*/
public static int getExponent(float f) {
@@ -1110,7 +1110,7 @@
}
/**
- * Returns the exponent of double {@code d}.
+ * Returns the unbiased base-2 exponent of double {@code d}.
* @since 1.6
*/
public static int getExponent(double d) {
diff --git a/luni/src/main/java/java/lang/Object.java b/luni/src/main/java/java/lang/Object.java
index 6a979bb..1729a81 100644
--- a/luni/src/main/java/java/lang/Object.java
+++ b/luni/src/main/java/java/lang/Object.java
@@ -191,30 +191,32 @@
}
/**
- * Called before the object's memory is reclaimed by the VM. This
- * can only happen once the garbage collector has detected that the
- * object is no longer reachable by any thread of the
- * running application.
- * <p>
- * The method can be used to free system resources or perform other cleanup
- * before the object is garbage collected. The default implementation of the
- * method is empty, which is also expected by the VM, but subclasses can
- * override {@code finalize()} as required. Uncaught exceptions which are
- * thrown during the execution of this method cause it to terminate
- * immediately but are otherwise ignored.
- * <p>
- * Note that the VM does guarantee that {@code finalize()} is called at most
- * once for any object, but it doesn't guarantee when (if at all) {@code
- * finalize()} will be called. For example, object B's {@code finalize()}
- * can delay the execution of object A's {@code finalize()} method and
- * therefore it can delay the reclamation of A's memory. To be safe, use a
- * {@link java.lang.ref.ReferenceQueue}, because it provides more control
- * over the way the VM deals with references during garbage collection.
- * </p>
+ * Invoked when the garbage collector has detected that this instance is no longer reachable.
+ * The default implementation does nothing, but this method can be overridden to free resources.
*
- * @throws Throwable
- * any exception which is raised during finalization; these are
- * ignored by the virtual machine.
+ * <p>Note that objects that override {@code finalize} are significantly more expensive than
+ * objects that don't. Finalizers may be run a long time after the object is no longer
+ * reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
+ * Note also that finalizers are run on a single VM-wide finalizer thread,
+ * so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
+ * for a class that has a native peer and needs to call a native method to destroy that peer.
+ * Even then, it's better to provide an explicit {@code close} method (and implement
+ * {@link java.io.Closeable}), and insist that callers manually dispose of instances. This
+ * works well for something like files, but less well for something like a {@code BigInteger}
+ * where typical calling code would have to deal with lots of temporaries. Unfortunately,
+ * code that creates lots of temporaries is the worst kind of code from the point of view of
+ * the single finalizer thread.
+ *
+ * <p>If you <i>must</i> use finalizers, consider at least providing your own
+ * {@link java.lang.ref.ReferenceQueue} and having your own thread process that queue.
+ *
+ * <p>Unlike constructors, finalizers are not automatically chained. You are responsible for
+ * calling {@code super.finalize()} yourself.
+ *
+ * <p>Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
+ * thread.
+ *
+ * See <i>Effective Java</i> Item 7, "Avoid finalizers" for more.
*/
protected void finalize() throws Throwable {
}
diff --git a/luni/src/main/java/java/lang/ProcessBuilder.java b/luni/src/main/java/java/lang/ProcessBuilder.java
index d63af8b..7b8c0c4 100644
--- a/luni/src/main/java/java/lang/ProcessBuilder.java
+++ b/luni/src/main/java/java/lang/ProcessBuilder.java
@@ -182,14 +182,11 @@
* if any of the elements of {@link #command()} is {@code null}.
* @throws IndexOutOfBoundsException
* if {@link #command()} is empty.
- * @throws SecurityException
- * if {@link SecurityManager#checkExec(String)} doesn't allow
- * process creation.
* @throws IOException
* if an I/O error happens.
*/
public Process start() throws IOException {
- // BEGIN android-changed: push responsibility for argument checking into ProcessManager
+ // We push responsibility for argument checking into ProcessManager.
String[] cmdArray = command.toArray(new String[command.size()]);
String[] envArray = new String[environment.size()];
int i = 0;
@@ -197,7 +194,5 @@
envArray[i++] = entry.getKey() + "=" + entry.getValue();
}
return ProcessManager.getInstance().exec(cmdArray, envArray, directory, redirectErrorStream);
- // END android-changed
}
-
}
diff --git a/luni/src/main/java/java/lang/ProcessManager.java b/luni/src/main/java/java/lang/ProcessManager.java
index 5d8c059..52f1038 100644
--- a/luni/src/main/java/java/lang/ProcessManager.java
+++ b/luni/src/main/java/java/lang/ProcessManager.java
@@ -186,10 +186,7 @@
// Handle security and safety by copying mutable inputs and checking them.
String[] command = taintedCommand.clone();
String[] environment = taintedEnvironment != null ? taintedEnvironment.clone() : null;
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkExec(command[0]);
- }
+
// Check we're not passing null Strings to the native exec.
for (String arg : command) {
if (arg == null) {
diff --git a/luni/src/main/java/java/lang/Runtime.java b/luni/src/main/java/java/lang/Runtime.java
index 7a98c45..893ebfb 100644
--- a/luni/src/main/java/java/lang/Runtime.java
+++ b/luni/src/main/java/java/lang/Runtime.java
@@ -123,10 +123,6 @@
* process.
* @throws IOException
* if the requested program can not be executed.
- * @throws SecurityException
- * if the current {@code SecurityManager} disallows program
- * execution.
- * @see SecurityManager#checkExec
*/
public Process exec(String[] progArray) throws java.io.IOException {
return exec(progArray, null, null);
@@ -148,10 +144,6 @@
* process.
* @throws IOException
* if the requested program can not be executed.
- * @throws SecurityException
- * if the current {@code SecurityManager} disallows program
- * execution.
- * @see SecurityManager#checkExec
*/
public Process exec(String[] progArray, String[] envp) throws java.io.IOException {
return exec(progArray, envp, null);
@@ -175,15 +167,10 @@
* process.
* @throws IOException
* if the requested program can not be executed.
- * @throws SecurityException
- * if the current {@code SecurityManager} disallows program
- * execution.
- * @see SecurityManager#checkExec
*/
public Process exec(String[] progArray, String[] envp, File directory) throws IOException {
- // BEGIN android-changed: push responsibility for argument checking into ProcessManager
+ // ProcessManager is responsible for all argument checking.
return ProcessManager.getInstance().exec(progArray, envp, directory, false);
- // END android-changed
}
/**
@@ -197,10 +184,6 @@
* process.
* @throws IOException
* if the requested program can not be executed.
- * @throws SecurityException
- * if the current {@code SecurityManager} disallows program
- * execution.
- * @see SecurityManager#checkExec
*/
public Process exec(String prog) throws java.io.IOException {
return exec(prog, null, null);
@@ -220,10 +203,6 @@
* process.
* @throws IOException
* if the requested program can not be executed.
- * @throws SecurityException
- * if the current {@code SecurityManager} disallows program
- * execution.
- * @see SecurityManager#checkExec
*/
public Process exec(String prog, String[] envp) throws java.io.IOException {
return exec(prog, envp, null);
@@ -246,10 +225,6 @@
* process.
* @throws IOException
* if the requested program can not be executed.
- * @throws SecurityException
- * if the current {@code SecurityManager} disallows program
- * execution.
- * @see SecurityManager#checkExec
*/
public Process exec(String prog, String[] envp, File directory) throws java.io.IOException {
// Sanity checks
@@ -280,18 +255,8 @@
* @param code
* the return code. By convention, non-zero return codes indicate
* abnormal terminations.
- * @throws SecurityException
- * if the current {@code SecurityManager} does not allow the
- * running thread to terminate the virtual machine.
- * @see SecurityManager#checkExit
*/
public void exit(int code) {
- // Security checks
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkExit(code);
- }
-
// Make sure we don't try this several times
synchronized(this) {
if (!shuttingDown) {
@@ -363,18 +328,8 @@
* the absolute (platform dependent) path to the library to load.
* @throws UnsatisfiedLinkError
* if the library can not be loaded.
- * @throws SecurityException
- * if the current {@code SecurityManager} does not allow to load
- * the library.
- * @see SecurityManager#checkLink
*/
public void load(String pathName) {
- // Security checks
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkLink(pathName);
- }
-
load(pathName, VMStack.getCallingClassLoader());
}
@@ -400,18 +355,8 @@
* the name of the library to load.
* @throws UnsatisfiedLinkError
* if the library can not be loaded.
- * @throws SecurityException
- * if the current {@code SecurityManager} does not allow to load
- * the library.
- * @see SecurityManager#checkLink
*/
public void loadLibrary(String libName) {
- // Security checks
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkLink(libName);
- }
-
loadLibrary(libName, VMStack.getCallingClassLoader());
}
@@ -488,10 +433,6 @@
*/
@Deprecated
public static void runFinalizersOnExit(boolean run) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkExit(0);
- }
finalizeOnExit = run;
}
@@ -606,9 +547,6 @@
* been registered.
* @throws IllegalStateException
* if the virtual machine is already shutting down.
- * @throws SecurityException
- * if a SecurityManager is registered and the calling code
- * doesn't have the RuntimePermission("shutdownHooks").
*/
public void addShutdownHook(Thread hook) {
// Sanity checks
@@ -624,11 +562,6 @@
throw new IllegalArgumentException("Hook has already been started");
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("shutdownHooks"));
- }
-
synchronized (shutdownHooks) {
if (shutdownHooks.contains(hook)) {
throw new IllegalArgumentException("Hook already registered.");
@@ -647,9 +580,6 @@
* false} otherwise.
* @throws IllegalStateException
* if the virtual machine is already shutting down.
- * @throws SecurityException
- * if a SecurityManager is registered and the calling code
- * doesn't have the RuntimePermission("shutdownHooks").
*/
public boolean removeShutdownHook(Thread hook) {
// Sanity checks
@@ -661,11 +591,6 @@
throw new IllegalStateException("VM already shutting down");
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("shutdownHooks"));
- }
-
synchronized (shutdownHooks) {
return shutdownHooks.remove(hook);
}
@@ -678,21 +603,11 @@
* @param code
* the return code. By convention, non-zero return codes indicate
* abnormal terminations.
- * @throws SecurityException
- * if the current {@code SecurityManager} does not allow the
- * running thread to terminate the virtual machine.
- * @see SecurityManager#checkExit
* @see #addShutdownHook(Thread)
* @see #removeShutdownHook(Thread)
* @see #runFinalizersOnExit(boolean)
*/
public void halt(int code) {
- // Security checks
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkExit(code);
- }
-
// Get out of here...
nativeExit(code, false);
}
@@ -714,4 +629,4 @@
*/
public native long maxMemory();
-}
\ No newline at end of file
+}
diff --git a/luni/src/main/java/java/lang/RuntimePermission.java b/luni/src/main/java/java/lang/RuntimePermission.java
index a6714e8..752c74a 100644
--- a/luni/src/main/java/java/lang/RuntimePermission.java
+++ b/luni/src/main/java/java/lang/RuntimePermission.java
@@ -20,63 +20,13 @@
import java.security.BasicPermission;
/**
- * Represents the permission to execute a runtime-related function. There is no
- * action list associated with a {@code RuntimePermission}; the user either has
- * the permission or he doesn't.
+ * Legacy security code; this class exists for compatibility only.
*/
public final class RuntimePermission extends BasicPermission {
private static final long serialVersionUID = 7399184964622342223L;
/**
- * Constants for runtime permissions used in this package.
- */
- static final RuntimePermission permissionToSetSecurityManager = new RuntimePermission(
- "setSecurityManager");
-
- static final RuntimePermission permissionToCreateSecurityManager = new RuntimePermission(
- "createSecurityManager");
-
- static final RuntimePermission permissionToGetProtectionDomain = new RuntimePermission(
- "getProtectionDomain");
-
- static final RuntimePermission permissionToGetClassLoader = new RuntimePermission(
- "getClassLoader");
-
- static final RuntimePermission permissionToCreateClassLoader = new RuntimePermission(
- "createClassLoader");
-
- static final RuntimePermission permissionToModifyThread = new RuntimePermission(
- "modifyThread");
-
- static final RuntimePermission permissionToModifyThreadGroup = new RuntimePermission(
- "modifyThreadGroup");
-
- static final RuntimePermission permissionToExitVM = new RuntimePermission(
- "exitVM");
-
- static final RuntimePermission permissionToReadFileDescriptor = new RuntimePermission(
- "readFileDescriptor");
-
- static final RuntimePermission permissionToWriteFileDescriptor = new RuntimePermission(
- "writeFileDescriptor");
-
- static final RuntimePermission permissionToQueuePrintJob = new RuntimePermission(
- "queuePrintJob");
-
- static final RuntimePermission permissionToSetFactory = new RuntimePermission(
- "setFactory");
-
- static final RuntimePermission permissionToSetIO = new RuntimePermission(
- "setIO");
-
- static final RuntimePermission permissionToStopThread = new RuntimePermission(
- "stopThread");
-
- static final RuntimePermission permissionToSetContextClassLoader = new RuntimePermission(
- "setContextClassLoader");
-
- /**
* Creates an instance of {@code RuntimePermission} with the specified name.
*
* @param permissionName
diff --git a/luni/src/main/java/java/lang/SecurityManager.java b/luni/src/main/java/java/lang/SecurityManager.java
index 1daf1ac..9b85514 100644
--- a/luni/src/main/java/java/lang/SecurityManager.java
+++ b/luni/src/main/java/java/lang/SecurityManager.java
@@ -17,8 +17,6 @@
package java.lang;
-// BEGIN android-added
-
import dalvik.system.VMStack;
import java.io.File;
import java.io.FileDescriptor;
@@ -28,38 +26,21 @@
import java.lang.reflect.Member;
import java.net.InetAddress;
import java.net.SocketPermission;
-import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.AllPermission;
import java.security.Permission;
import java.security.Security;
import java.security.SecurityPermission;
import java.util.PropertyPermission;
-import org.apache.harmony.luni.util.PriviAction;
/**
- * <strong>Warning:</strong> security managers do <strong>not</strong> provide a
+ * Legacy security code; this class exists for compatibility only.
+ *
+ * <p>Security managers do <strong>not</strong> provide a
* secure environment for executing untrusted code. Untrusted code cannot be
* safely isolated within the Dalvik VM.
- *
- * <p>Provides security verification facilities for applications. {@code
- * SecurityManager} contains a set of {@code checkXXX} methods which determine
- * if it is safe to perform a specific operation such as establishing network
- * connections, modifying files, and many more. In general, these methods simply
- * return if they allow the application to perform the operation; if an
- * operation is not allowed, then they throw a {@link SecurityException}. The
- * only exception is {@link #checkTopLevelWindow(Object)}, which returns a
- * boolean to indicate permission.
*/
public class SecurityManager {
-
- private static final PropertyPermission READ_WRITE_ALL_PROPERTIES_PERMISSION = new PropertyPermission(
- "*", "read,write");
-
- private static final String PKG_ACC_KEY = "package.access";
-
- private static final String PKG_DEF_KEY = "package.definition";
-
/**
* Flag to indicate whether a security check is in progress.
*
@@ -70,589 +51,185 @@
/**
* Constructs a new {@code SecurityManager} instance.
- * <p>
- * The {@code RuntimePermission("createSecurityManager")} is checked if a
- * security manager is installed.
*/
public SecurityManager() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security
- .checkPermission(RuntimePermission.permissionToCreateSecurityManager);
- }
- Class<?> type = Security.class; // initialize Security properties
- if (type == null) {
- throw new AssertionError();
- }
}
/**
- * Checks whether the calling thread is allowed to accept socket
- * connections.
- *
- * @param host
- * the address of the host that attempts to connect.
- * @param port
- * the port number to check.
- * @throws NullPointerException
- * if {@code host} is {@code null}.
- * @throws SecurityException
- * if the calling thread is not allowed to accept socket
- * connections from {@code host} through {@code port}.
+ * Does nothing.
*/
public void checkAccept(String host, int port) {
- if (host == null) {
- throw new NullPointerException();
- }
- checkPermission(new SocketPermission(host + ':' + port, "accept"));
}
/**
- * Checks whether the calling thread is allowed to modify the specified
- * thread.
- *
- * @param thread
- * the thread to access.
- * @throws SecurityException
- * if the calling thread is not allowed to access {@code thread}.
+ * Does nothing.
*/
public void checkAccess(Thread thread) {
- // Only worry about system threads. Dead threads have a null group.
- ThreadGroup group = thread.getThreadGroup();
- if ((group != null) && (group.parent == null)) {
- checkPermission(RuntimePermission.permissionToModifyThread);
- }
}
/**
- * Checks whether the calling thread is allowed to modify the specified
- * thread group.
- *
- * @param group
- * the thread group to access.
- * @throws NullPointerException
- * if {@code group} is {@code null}.
- * @throws SecurityException
- * if the calling thread is not allowed to access {@code group}.
+ * Does nothing.
*/
public void checkAccess(ThreadGroup group) {
- // Only worry about system threads.
- if (group == null) {
- throw new NullPointerException();
- }
- if (group.parent == null) {
- checkPermission(RuntimePermission.permissionToModifyThreadGroup);
- }
}
/**
- * Checks whether the calling thread is allowed to establish socket
- * connections. A -1 port indicates the caller is trying to resolve the
- * hostname.
- *
- * @param host
- * the address of the host to connect to.
- * @param port
- * the port number to check, or -1 for resolve.
- * @throws NullPointerException
- * if {@code host} is {@code null}.
- * @throws SecurityException
- * if the calling thread is not allowed to connect to {@code
- * host} through {@code port}.
+ * Does nothing.
*/
public void checkConnect(String host, int port) {
- if (host == null) {
- throw new NullPointerException();
- }
- if (port > 0) {
- checkPermission(new SocketPermission(host + ':' + port, "connect"));
- } else {
- checkPermission(new SocketPermission(host, "resolve"));
- }
}
/**
- * Checks whether the specified security context is allowed to establish
- * socket connections. A -1 port indicates the caller is trying to resolve
- * the hostname.
- *
- * @param host
- * the address of the host to connect to.
- * @param port
- * the port number to check, or -1 for resolve.
- * @param context
- * the security context to use for the check.
- * @throws NullPointerException
- * if {@code host} is {@code null}.
- * @throws SecurityException
- * if {@code context} is not allowed to connect to {@code host}
- * through {@code port}.
+ * Does nothing.
*/
public void checkConnect(String host, int port, Object context) {
- // BEGIN android-added
- if (host == null) {
- throw new NullPointerException();
- }
- // END android-added
- if (port > 0) {
- checkPermission(new SocketPermission(host + ':' + port, "connect"),
- context);
- } else {
- checkPermission(new SocketPermission(host, "resolve"), context);
- }
}
/**
- * Checks whether the calling thread is allowed to create a class loader.
- *
- * @throws SecurityException
- * if the calling thread is not allowed to create a class
- * loader.
+ * Does nothing.
*/
public void checkCreateClassLoader() {
- checkPermission(RuntimePermission.permissionToCreateClassLoader);
}
/**
- * Checks whether the calling thread is allowed to delete the file with the
- * specified name, which should be passed in canonical form.
- *
- * @param file
- * the name of the file to delete.
- * @throws SecurityException
- * if the calling thread is not allowed to delete {@code file}.
+ * Does nothing.
*/
public void checkDelete(String file) {
- checkPermission(new FilePermission(file, "delete"));
}
/**
- * Checks whether the calling thread is allowed to execute the specified
- * platform specific command.
- *
- * @param cmd
- * the command line to execute.
- * @throws SecurityException
- * if the calling thread is not allowed to execute {@code cmd}.
+ * Does nothing.
*/
public void checkExec(String cmd) {
- checkPermission(new FilePermission(new File(cmd).isAbsolute() ? cmd
- : "<<ALL FILES>>", "execute"));
}
/**
- * Checks whether the calling thread is allowed to terminate the virtual
- * machine.
- *
- * @param status
- * the status that the virtual machine returns when it is
- * terminated.
- * @throws SecurityException
- * if the calling thread is not allowed to terminate the virtual
- * machine with {@code status}.
+ * Does nothing.
*/
public void checkExit(int status) {
- checkPermission(RuntimePermission.permissionToExitVM);
}
/**
- * Checks whether the calling thread is allowed to load the specified native
- * library.
- *
- * @param libName
- * the name of the library to load.
- * @throws SecurityException
- * if the calling thread is not allowed to load {@code libName}.
+ * Does nothing.
*/
public void checkLink(String libName) {
- if (libName == null) {
- throw new NullPointerException();
- }
- checkPermission(new RuntimePermission("loadLibrary." + libName));
}
/**
- * Checks whether the calling thread is allowed to listen on the specified
- * port.
- *
- * @param port
- * the port number to check.
- * @throws SecurityException
- * if the calling thread is not allowed listen on {@code port}.
+ * Does nothing.
*/
public void checkListen(int port) {
- if (port == 0) {
- checkPermission(new SocketPermission("localhost:1024-", "listen"));
- } else {
- checkPermission(new SocketPermission("localhost:" + port, "listen"));
- }
}
/**
- * Checks whether the calling thread is allowed to access members. The
- * default is to allow access to public members (that is, {@code
- * java.lang.reflect.Member.PUBLIC}) and to classes loaded by the same
- * loader as the original caller (that is, the method that called the
- * reflect API). Due to the nature of the check, overriding implementations
- * cannot call {@code super.checkMemberAccess()} since the stack would no
- * longer be of the expected shape.
- *
- * @param cls
- * the class of which members are accessed.
- * @param type
- * the access type, either {@code
- * java.lang.reflect.Member.PUBLIC} or {@code
- * java.lang.reflect.Member.DECLARED}.
- * @throws SecurityException
- * if the calling thread is not allowed to access members of
- * {@code cls}.
+ * Does nothing.
*/
public void checkMemberAccess(Class<?> cls, int type) {
- if (cls == null) {
- throw new NullPointerException();
- }
- if (type == Member.PUBLIC) {
- return;
- }
- //
- // Need to compare the classloaders.
- // Stack shape is
- // <user code> <- want this class
- // Class.getDeclared*();
- // Class.checkMemberAccess();
- // SecurityManager.checkMemberAccess(); <- current frame
- //
- // Use getClassLoaderImpl() since getClassLoader()
- // returns null for the bootstrap class loader.
- if (ClassLoader.getStackClassLoader(3) == cls.getClassLoaderImpl()) {
- return;
- }
-
- // Forward off to the permission mechanism.
- checkPermission(new RuntimePermission("accessDeclaredMembers"));
}
/**
- * Checks whether the calling thread is allowed to use the specified IP
- * multicast group address.
- *
- * @param maddr
- * the internet group address to use.
- * @throws SecurityException
- * if the calling thread is not allowed to use {@code maddr}.
+ * Does nothing.
*/
public void checkMulticast(InetAddress maddr) {
- checkPermission(new SocketPermission(maddr.getHostAddress(),
- "accept,connect"));
}
/**
- * Checks whether the calling thread is allowed to use the specified IP
- * multicast group address.
- *
- * @param maddr
- * the internet group address to use.
- * @param ttl
- * the value in use for multicast send. This parameter is
- * ignored.
- * @throws SecurityException
- * if the calling thread is not allowed to use {@code maddr}.
+ * Does nothing.
* @deprecated use {@link #checkMulticast(java.net.InetAddress)}
*/
@Deprecated
public void checkMulticast(InetAddress maddr, byte ttl) {
- checkPermission(new SocketPermission(maddr.getHostAddress(),
- "accept,connect"));
}
/**
- * Checks whether the calling thread is allowed to access the specified
- * package.
- *
- * @param packageName
- * the name of the package to access.
- * @throws SecurityException
- * if the calling thread is not allowed to access {@code
- * packageName}.
+ * Does nothing.
*/
public void checkPackageAccess(String packageName) {
- if (packageName == null) {
- throw new NullPointerException();
- }
- if (checkPackageProperty(PKG_ACC_KEY, packageName)) {
- checkPermission(new RuntimePermission("accessClassInPackage."
- + packageName));
- }
}
/**
- * Checks whether the calling thread is allowed to define new classes in the
- * specified package.
- *
- * @param packageName
- * the name of the package to add a class to.
- * @throws SecurityException
- * if the calling thread is not allowed to add classes to
- * {@code packageName}.
+ * Does nothing.
*/
public void checkPackageDefinition(String packageName) {
- if (packageName == null) {
- throw new NullPointerException();
- }
- if (checkPackageProperty(PKG_DEF_KEY, packageName)) {
- checkPermission(new RuntimePermission("defineClassInPackage."
- + packageName));
- }
}
/**
- * Returns true if the package name is restricted by the specified security
- * property.
- */
- private static boolean checkPackageProperty(final String property,
- final String pkg) {
- String list = AccessController.doPrivileged(PriviAction
- .getSecurityProperty(property));
- if (list != null) {
- int plen = pkg.length();
- String[] tokens = list.split(", *");
- for (String token : tokens) {
- int tlen = token.length();
- if (plen > tlen
- && pkg.startsWith(token)
- && (token.charAt(tlen - 1) == '.' || pkg.charAt(tlen) == '.')) {
- return true;
- } else if (plen == tlen && token.startsWith(pkg)) {
- return true;
- } else if (plen + 1 == tlen && token.startsWith(pkg)
- && token.charAt(tlen - 1) == '.') {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Checks whether the calling thread is allowed to access the system
- * properties.
- *
- * @throws SecurityException
- * if the calling thread is not allowed to access system
- * properties.
+ * Does nothing.
*/
public void checkPropertiesAccess() {
- checkPermission(READ_WRITE_ALL_PROPERTIES_PERMISSION);
}
/**
- * Checks whether the calling thread is allowed to access a particular
- * system property.
- *
- * @param key
- * the name of the property to access.
- * @throws SecurityException
- * if the calling thread is not allowed to access the {@code
- * key} system property.
+ * Does nothing.
*/
public void checkPropertyAccess(String key) {
- checkPermission(new PropertyPermission(key, "read"));
}
/**
- * Checks whether the calling thread is allowed to read from the file with
- * the specified file descriptor.
- *
- * @param fd
- * the file descriptor of the file to read from.
- * @throws SecurityException
- * if the calling thread is not allowed to read from {@code fd}.
+ * Does nothing.
*/
public void checkRead(FileDescriptor fd) {
- if (fd == null) {
- throw new NullPointerException();
- }
- checkPermission(RuntimePermission.permissionToReadFileDescriptor);
}
/**
- * Checks whether the calling thread is allowed to read from the file with
- * the specified name, which should be passed in canonical form.
- *
- * @param file
- * the name of the file or directory to read from.
- * @throws SecurityException
- * if the calling thread is not allowed to read from {@code
- * file}.
+ * Does nothing.
*/
public void checkRead(String file) {
- checkPermission(new FilePermission(file, "read"));
}
/**
- * Checks whether the given security context is allowed to read from the
- * file named by the argument, which should be passed in canonical form.
- *
- * @param file
- * the name of the file or directory to check.
- * @param context
- * the security context to use for the check.
- * @throws SecurityException
- * if {@code context} is not allowed to read from {@code file}.
+ * Does nothing.
*/
public void checkRead(String file, Object context) {
- checkPermission(new FilePermission(file, "read"), context);
}
/**
- * Checks whether the calling thread is allowed to perform the security
- * operation named by the target.
- *
- * @param target
- * the name of the operation to perform.
- * @throws SecurityException
- * if the calling thread is not allowed to perform
- * {@code target}.
+ * Does nothing.
*/
public void checkSecurityAccess(String target) {
- checkPermission(new SecurityPermission(target));
}
/**
- * Checks whether the calling thread is allowed to set the net object
- * factories.
- *
- * @throws SecurityException
- * if the calling thread is not allowed to set the net object
- * factories.
+ * Does nothing.
*/
public void checkSetFactory() {
- checkPermission(RuntimePermission.permissionToSetFactory);
}
/**
- * Checks whether the calling thread is trusted to show the specified top
- * level window.
- *
- * @param window
- * the window to show.
- * @return {@code true} if the calling thread is allowed to show {@code
- * window}; {@code false} otherwise.
- * @throws NullPointerException
- * if {@code window} is {@code null}.
+ * Returns true.
*/
public boolean checkTopLevelWindow(Object window) {
- if (window == null) {
- throw new NullPointerException();
- }
- try {
- Class<?> awtPermission = Class.forName("java.awt.AWTPermission");
- Constructor<?> constructor = awtPermission
- .getConstructor(String.class);
- Object perm = constructor
- .newInstance("showWindowWithoutWarningBanner");
- checkPermission((Permission) perm);
- } catch (ClassNotFoundException e) {
- } catch (NoSuchMethodException e) {
- } catch (InstantiationException e) {
- } catch (IllegalAccessException e) {
- } catch (InvocationTargetException e) {
- } catch (SecurityException e) {
- return false;
- }
return true;
}
/**
- * Checks whether the calling thread is allowed to access the system
- * clipboard.
- *
- * @throws SecurityException
- * if the calling thread is not allowed to access the system
- * clipboard.
+ * Does nothing.
*/
public void checkSystemClipboardAccess() {
- try {
- Class<?> awtPermission = Class.forName("java.awt.AWTPermission");
- Constructor<?> constructor = awtPermission
- .getConstructor(String.class);
- Object perm = constructor.newInstance("accessClipboard");
- checkPermission((Permission) perm);
- return;
- } catch (ClassNotFoundException e) {
- } catch (NoSuchMethodException e) {
- } catch (InstantiationException e) {
- } catch (IllegalAccessException e) {
- } catch (InvocationTargetException e) {
- }
- throw new SecurityException();
}
/**
- * Checks whether the calling thread is allowed to access the AWT event
- * queue.
- *
- * @throws SecurityException
- * if the calling thread is not allowed to access the AWT event
- * queue.
+ * Does nothing.
*/
public void checkAwtEventQueueAccess() {
- try {
- Class<?> awtPermission = Class.forName("java.awt.AWTPermission");
- Constructor<?> constructor = awtPermission
- .getConstructor(String.class);
- Object perm = constructor.newInstance("accessEventQueue");
- checkPermission((Permission) perm);
- return;
- } catch (ClassNotFoundException e) {
- } catch (NoSuchMethodException e) {
- } catch (InstantiationException e) {
- } catch (IllegalAccessException e) {
- } catch (InvocationTargetException e) {
- }
- throw new SecurityException();
}
/**
- * Checks whether the calling thread is allowed to start a new print job.
- *
- * @throws SecurityException
- * if the calling thread is not allowed to start a new print
- * job.
+ * Does nothing.
*/
public void checkPrintJobAccess() {
- checkPermission(RuntimePermission.permissionToQueuePrintJob);
}
/**
- * Checks whether the calling thread is allowed to write to the file with
- * the specified file descriptor.
- *
- * @param fd
- * the file descriptor of the file to write to.
- * @throws SecurityException
- * if the calling thread is not allowed to write to {@code fd}.
+ * Does nothing.
*/
public void checkWrite(FileDescriptor fd) {
- if (fd == null) {
- throw new NullPointerException();
- }
- checkPermission(RuntimePermission.permissionToWriteFileDescriptor);
}
/**
- * Checks whether the calling thread is allowed to write to the file with
- * the specified name, which should be passed in canonical form.
- *
- * @param file
- * the name of the file or directory to write to.
- * @throws SecurityException
- * if the calling thread is not allowed to write to
- * {@code file}.
+ * Does nothing.
*/
public void checkWrite(String file) {
- checkPermission(new FilePermission(file, "write"));
}
/**
@@ -704,7 +281,7 @@
* Now, check if there are any non-system class loaders in the stack up
* to the first privileged method (or the end of the stack.
*/
- Class<?>[] classes = Class.getStackClasses(-1, true);
+ Class<?>[] classes = VMStack.getClasses(-1, true);
for (int i = 0; i < classes.length; i++) {
ClassLoader cl = classes[i].getClassLoaderImpl();
if (!cl.isSystemClassLoader()) {
@@ -739,7 +316,7 @@
* Now, check if there are any non-system class loaders in the stack up
* to the first privileged method (or the end of the stack.
*/
- Class<?>[] classes = Class.getStackClasses(-1, true);
+ Class<?>[] classes = VMStack.getClasses(-1, true);
for (int i = 0; i < classes.length; i++) {
ClassLoader cl = classes[i].getClassLoaderImpl();
if (!cl.isSystemClassLoader()) {
@@ -750,36 +327,11 @@
}
/**
- * Returns the first class in the call stack that was loaded by a class
- * loader which is not a system class loader.
- *
- * @return the most recent class loaded by a non-system class loader.
+ * Returns null.
* @deprecated Use {@link #checkPermission}.
*/
@Deprecated
protected Class<?> currentLoadedClass() {
- /*
- * First, check if AllPermission is allowed. If so, then we are
- * effectively running in an unsafe environment, so just answer null
- * (==> everything is a system class).
- */
- try {
- checkPermission(new AllPermission());
- return null;
- } catch (SecurityException ex) {
- }
-
- /*
- * Now, check if there are any non-system class loaders in the stack up
- * to the first privileged method (or the end of the stack.
- */
- Class<?>[] classes = Class.getStackClasses(-1, true);
- for (int i = 0; i < classes.length; i++) {
- ClassLoader cl = classes[i].getClassLoaderImpl();
- if (!cl.isSystemClassLoader()) {
- return classes[i];
- }
- }
return null;
}
@@ -796,7 +348,7 @@
*/
@Deprecated
protected int classDepth(String name) {
- Class<?>[] classes = Class.getStackClasses(-1, false);
+ Class<?>[] classes = VMStack.getClasses(-1, false);
for (int i = 0; i < classes.length; i++) {
if (classes[i].getName().equals(name)) {
return i;
@@ -846,8 +398,7 @@
/**
* Returns an object which encapsulates the security state of the current
- * point in the execution. In our case, this is an {@link
- * java.security.AccessControlContext}.
+ * point in the execution.
*
* @return an object that encapsulates information about the current
* execution environment.
@@ -857,51 +408,14 @@
}
/**
- * Checks whether the calling thread is allowed to access the resource being
- * guarded by the specified permission object.
- *
- * @param permission
- * the permission to check.
- * @throws SecurityException
- * if the requested {@code permission} is denied according to
- * the current security policy.
+ * Does nothing.
*/
public void checkPermission(Permission permission) {
- try {
- inCheck = true;
- AccessController.checkPermission(permission);
- } finally {
- inCheck = false;
- }
}
/**
- * Checks whether the specified security context is allowed to access the
- * resource being guarded by the specified permission object.
- *
- * @param permission
- * the permission to check.
- * @param context
- * the security context for which to check permission.
- * @throws SecurityException
- * if {@code context} is not an instance of {@code
- * AccessControlContext} or if the requested {@code permission}
- * is denied for {@code context} according to the current
- * security policy.
+ * Does nothing.
*/
public void checkPermission(Permission permission, Object context) {
- try {
- inCheck = true;
- // Must be an AccessControlContext. If we don't check
- // this, then applications could pass in an arbitrary
- // object which circumvents the security check.
- if (context instanceof AccessControlContext) {
- ((AccessControlContext) context).checkPermission(permission);
- } else {
- throw new SecurityException();
- }
- } finally {
- inCheck = false;
- }
}
}
diff --git a/luni/src/main/java/java/lang/StackTraceElement.java b/luni/src/main/java/java/lang/StackTraceElement.java
index a899a92..78579f8 100644
--- a/luni/src/main/java/java/lang/StackTraceElement.java
+++ b/luni/src/main/java/java/lang/StackTraceElement.java
@@ -30,9 +30,7 @@
private static final long serialVersionUID = 6992337162326171013L;
- // BEGIN android-added
private static final int NATIVE_LINE_NUMBER = -2;
- // END android-added
String declaringClass;
@@ -200,9 +198,7 @@
* executing is a native method; {@code false} otherwise.
*/
public boolean isNativeMethod() {
- // BEGIN android-changed
return lineNumber == NATIVE_LINE_NUMBER;
- // END android-changed
}
@Override
diff --git a/luni/src/main/java/java/lang/StrictMath.java b/luni/src/main/java/java/lang/StrictMath.java
index 426fc2d..c2c4889 100644
--- a/luni/src/main/java/java/lang/StrictMath.java
+++ b/luni/src/main/java/java/lang/StrictMath.java
@@ -38,13 +38,13 @@
/**
* The double value closest to e, the base of the natural logarithm.
*/
- public final static double E = Math.E;
+ public static final double E = Math.E;
/**
* The double value closest to pi, the ratio of a circle's circumference to
* its diameter.
*/
- public final static double PI = Math.PI;
+ public static final double PI = Math.PI;
/**
* Prevents this class from being instantiated.
diff --git a/luni/src/main/java/java/lang/String.java b/luni/src/main/java/java/lang/String.java
index 4bf0af7..294aa7b 100644
--- a/luni/src/main/java/java/lang/String.java
+++ b/luni/src/main/java/java/lang/String.java
@@ -602,8 +602,11 @@
throw new StringIndexOutOfBoundsException("array length=" + arrayLength + " offset=" + offset + " count=" + count);
}
- // Optimized for ASCII
- private char compareValue(char ch) {
+ /**
+ * This isn't equivalent to either of ICU's u_foldCase case folds, and thus any of the Unicode
+ * case folds, but it's what the RI uses.
+ */
+ private char foldCase(char ch) {
if (ch < 128) {
if ('A' <= ch && ch <= 'Z') {
return (char) (ch + ('a' - 'A'));
@@ -675,8 +678,8 @@
if ((c1 = value[o1++]) == (c2 = target[o2++])) {
continue;
}
- c1 = compareValue(c1);
- c2 = compareValue(c2);
+ c1 = foldCase(c1);
+ c2 = foldCase(c2);
if ((result = c1 - c2) != 0) {
return result;
}
@@ -772,11 +775,9 @@
}
if (object instanceof String) {
String s = (String) object;
- // BEGIN android-changed
int hashCode1 = hashCode;
int hashCode2 = s.hashCode;
- if (count != s.count
- || (hashCode1 != hashCode2 && hashCode1 != 0 && hashCode2 != 0)) {
+ if (count != s.count || (hashCode1 != hashCode2 && hashCode1 != 0 && hashCode2 != 0)) {
return false;
}
// inline 'return regionMatches(0, s, 0, count)'
@@ -790,7 +791,6 @@
}
}
return true;
- // END android-changed
}
return false;
}
@@ -811,16 +811,13 @@
if (string == null || count != string.count) {
return false;
}
-
int o1 = offset, o2 = string.offset;
int end = offset + count;
- char c1, c2;
char[] target = string.value;
while (o1 < end) {
- if ((c1 = value[o1++]) != (c2 = target[o2++])
- && Character.toUpperCase(c1) != Character.toUpperCase(c2)
- // Required for unicode that we test both cases
- && Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
+ char c1 = value[o1++];
+ char c2 = target[o2++];
+ if (c1 != c2 && foldCase(c1) != foldCase(c2)) {
return false;
}
}
@@ -1009,7 +1006,6 @@
}
private int fastIndexOf(int c, int start) {
- // BEGIN android-changed
int _count = count;
if (start < _count) {
if (start < 0) {
@@ -1025,7 +1021,6 @@
}
}
return -1;
- // END android-changed
}
private int indexOfSupplementary(int c, int start) {
@@ -1050,7 +1045,6 @@
* if {@code string} is {@code null}.
*/
public int indexOf(String string) {
- // BEGIN android-changed
int start = 0;
int subCount = string.count;
int _count = count;
@@ -1079,7 +1073,6 @@
}
}
return start < _count ? start : _count;
- // END android-changed
}
/**
@@ -1097,7 +1090,6 @@
* if {@code subString} is {@code null}.
*/
public int indexOf(String subString, int start) {
- // BEGIN android-changed
if (start < 0) {
start = 0;
}
@@ -1128,18 +1120,22 @@
}
}
return start < _count ? start : _count;
- // END android-changed
}
/**
- * Searches an internal table of strings for a string equal to this string.
- * If the string is not in the table, it is added. Returns the string
- * contained in the table which is equal to this string. The same string
- * object is always returned for strings which are equal.
+ * Returns an interned string equal to this string. The VM maintains an internal set of
+ * unique strings. All string literals found in loaded classes'
+ * constant pools are automatically interned. Manually-interned strings are only weakly
+ * referenced, so calling {@code intern} won't lead to unwanted retention.
*
- * @return the interned string equal to this string.
+ * <p>Interning is typically used because it guarantees that for interned strings
+ * {@code a} and {@code b}, {@code a.equals(b)} can be simplified to
+ * {@code a == b}. (This is not true of non-interned strings.)
+ *
+ * <p>Many applications find it simpler and more convenient to use an explicit
+ * {@link java.util.HashMap} to implement their own pools.
*/
- native public String intern();
+ public native String intern();
/**
* Returns true if the length of this string is 0.
@@ -1151,20 +1147,14 @@
}
/**
- * Searches in this string for the last index of the specified character.
+ * Returns the last index of the code point {@code c}, or -1.
* The search for the character starts at the end and moves towards the
* beginning of this string.
- *
- * @param c
- * the character to find.
- * @return the index in this string of the specified character, -1 if the
- * character isn't found.
*/
public int lastIndexOf(int c) {
if (c > 0xffff) {
return lastIndexOfSupplementary(c, Integer.MAX_VALUE);
}
- // BEGIN android-changed
int _count = count;
int _offset = offset;
char[] _value = value;
@@ -1174,26 +1164,17 @@
}
}
return -1;
- // END android-changed
}
/**
- * Searches in this string for the index of the specified character. The
- * search for the character starts at the specified offset and moves towards
+ * Returns the last index of the code point {@code c}, or -1.
+ * The search for the character starts at offset {@code start} and moves towards
* the beginning of this string.
- *
- * @param c
- * the character to find.
- * @param start
- * the starting offset.
- * @return the index in this string of the specified character, -1 if the
- * character isn't found.
*/
public int lastIndexOf(int c, int start) {
if (c > 0xffff) {
return lastIndexOfSupplementary(c, start);
}
- // BEGIN android-changed
int _count = count;
int _offset = offset;
char[] _value = value;
@@ -1208,7 +1189,6 @@
}
}
return -1;
- // END android-changed
}
private int lastIndexOfSupplementary(int c, int start) {
@@ -1309,8 +1289,7 @@
* @throws NullPointerException
* if {@code string} is {@code null}.
*/
- public boolean regionMatches(int thisStart, String string, int start,
- int length) {
+ public boolean regionMatches(int thisStart, String string, int start, int length) {
if (string == null) {
throw new NullPointerException();
}
@@ -1324,7 +1303,6 @@
return true;
}
int o1 = offset + thisStart, o2 = string.offset + start;
- // BEGIN android-changed
char[] value1 = value;
char[] value2 = string.value;
for (int i = 0; i < length; ++i) {
@@ -1332,7 +1310,6 @@
return false;
}
}
- // END android-changed
return true;
}
@@ -1356,36 +1333,31 @@
* @throws NullPointerException
* if {@code string} is {@code null}.
*/
- public boolean regionMatches(boolean ignoreCase, int thisStart,
- String string, int start, int length) {
+ public boolean regionMatches(boolean ignoreCase, int thisStart, String string, int start, int length) {
if (!ignoreCase) {
return regionMatches(thisStart, string, start, length);
}
-
- if (string != null) {
- if (thisStart < 0 || length > count - thisStart) {
- return false;
- }
- if (start < 0 || length > string.count - start) {
- return false;
- }
-
- thisStart += offset;
- start += string.offset;
- int end = thisStart + length;
- char c1, c2;
- char[] target = string.value;
- while (thisStart < end) {
- if ((c1 = value[thisStart++]) != (c2 = target[start++])
- && Character.toUpperCase(c1) != Character.toUpperCase(c2)
- // Required for unicode that we test both cases
- && Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
- return false;
- }
- }
- return true;
+ if (string == null) {
+ throw new NullPointerException("string == null");
}
- throw new NullPointerException();
+ if (thisStart < 0 || length > count - thisStart) {
+ return false;
+ }
+ if (start < 0 || length > string.count - start) {
+ return false;
+ }
+ thisStart += offset;
+ start += string.offset;
+ int end = thisStart + length;
+ char[] target = string.value;
+ while (thisStart < end) {
+ char c1 = value[thisStart++];
+ char c2 = target[start++];
+ if (c1 != c2 && foldCase(c1) != foldCase(c2)) {
+ return false;
+ }
+ }
+ return true;
}
/**
@@ -1573,17 +1545,17 @@
}
/**
- * Converts this string to lowercase, using the rules of the user's default locale.
+ * Converts this string to lower case, using the rules of the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*
- * @return a new lowercase string, or {@code this} if it's already all-lowercase.
+ * @return a new lower case string, or {@code this} if it's already all lower case.
*/
public String toLowerCase() {
return CaseMapper.toLowerCase(Locale.getDefault(), this, value, offset, count);
}
/**
- * Converts this string to lowercase, using the rules of {@code locale}.
+ * Converts this string to lower case, using the rules of {@code locale}.
*
* <p>Most case mappings are unaffected by the language of a {@code Locale}. Exceptions include
* dotted and dotless I in Azeri and Turkish locales, and dotted and dotless I and J in
@@ -1593,7 +1565,7 @@
* <p>See <a href="http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt">http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt</a>
* for full details of context- and language-specific special cases.
*
- * @return a new lowercase string, or {@code this} if it's already all-lowercase.
+ * @return a new lower case string, or {@code this} if it's already all lower case.
*/
public String toLowerCase(Locale locale) {
return CaseMapper.toLowerCase(locale, this, value, offset, count);
@@ -1601,8 +1573,6 @@
/**
* Returns this string.
- *
- * @return this string.
*/
@Override
public String toString() {
@@ -1610,17 +1580,17 @@
}
/**
- * Converts this this string to uppercase, using the rules of the user's default locale.
+ * Converts this this string to upper case, using the rules of the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*
- * @return a new uppercase string, or {@code this} if it's already all-uppercase.
+ * @return a new upper case string, or {@code this} if it's already all upper case.
*/
public String toUpperCase() {
return CaseMapper.toUpperCase(Locale.getDefault(), this, value, offset, count);
}
/**
- * Converts this this string to uppercase, using the rules of {@code locale}.
+ * Converts this this string to upper case, using the rules of {@code locale}.
*
* <p>Most case mappings are unaffected by the language of a {@code Locale}. Exceptions include
* dotted and dotless I in Azeri and Turkish locales, and dotted and dotless I and J in
@@ -1630,7 +1600,7 @@
* <p>See <a href="http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt">http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt</a>
* for full details of context- and language-specific special cases.
*
- * @return a new uppercase string, or {@code this} if it's already all-uppercase.
+ * @return a new upper case string, or {@code this} if it's already all upper case.
*/
public String toUpperCase(Locale locale) {
return CaseMapper.toUpperCase(locale, this, value, offset, count);
diff --git a/luni/src/main/java/java/lang/StringBuffer.java b/luni/src/main/java/java/lang/StringBuffer.java
index 471c008..d5280d2 100644
--- a/luni/src/main/java/java/lang/StringBuffer.java
+++ b/luni/src/main/java/java/lang/StringBuffer.java
@@ -47,10 +47,11 @@
private static final long serialVersionUID = 3388685877147921107L;
- private static final ObjectStreamField serialPersistentFields[] = {
- new ObjectStreamField("count", int.class),
- new ObjectStreamField("shared", boolean.class),
- new ObjectStreamField("value", char[].class), };
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("count", int.class),
+ new ObjectStreamField("shared", boolean.class),
+ new ObjectStreamField("value", char[].class),
+ };
/**
* Constructs a new StringBuffer using the default capacity which is 16.
diff --git a/luni/src/main/java/java/lang/System.java b/luni/src/main/java/java/lang/System.java
index 8ba0472..f584729 100644
--- a/luni/src/main/java/java/lang/System.java
+++ b/luni/src/main/java/java/lang/System.java
@@ -32,6 +32,7 @@
package java.lang;
+import dalvik.system.VMRuntime;
import dalvik.system.VMStack;
import java.io.Console;
import java.io.FileDescriptor;
@@ -49,6 +50,7 @@
import java.util.Properties;
import java.util.PropertyPermission;
import java.util.Set;
+import libcore.icu.ICU;
/**
* Provides access to system-related information and resources including
@@ -75,20 +77,10 @@
*/
public static final PrintStream err;
- /**
- * The System Properties table.
- */
private static Properties systemProperties;
- /**
- * Initialize all the slots in System on first use.
- */
static {
- /*
- * Set up standard in, out, and err. TODO err and out are
- * String.ConsolePrintStream. All three are buffered in Harmony. Check
- * and possibly change this later.
- */
+ // TODO: all three streams are buffered in Harmony.
err = new PrintStream(new FileOutputStream(FileDescriptor.err));
out = new PrintStream(new FileOutputStream(FileDescriptor.out));
in = new FileInputStream(FileDescriptor.in);
@@ -100,16 +92,8 @@
* @param newIn
* the user defined input stream to set as the standard input
* stream.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPermission()} method does not allow the change of the
- * stream.
*/
public static void setIn(InputStream newIn) {
- SecurityManager secMgr = System.getSecurityManager();
- if(secMgr != null) {
- secMgr.checkPermission(RuntimePermission.permissionToSetIO);
- }
setFieldImpl("in", "Ljava/io/InputStream;", newIn);
}
@@ -119,16 +103,8 @@
* @param newOut
* the user defined output stream to set as the standard output
* stream.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPermission()} method does not allow the change of the
- * stream.
*/
public static void setOut(java.io.PrintStream newOut) {
- SecurityManager secMgr = System.getSecurityManager();
- if(secMgr != null) {
- secMgr.checkPermission(RuntimePermission.permissionToSetIO);
- }
setFieldImpl("out", "Ljava/io/PrintStream;", newOut);
}
@@ -139,16 +115,8 @@
* @param newErr
* the user defined output stream to set as the standard error
* output stream.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPermission()} method does not allow the change of the
- * stream.
*/
public static void setErr(java.io.PrintStream newErr) {
- SecurityManager secMgr = System.getSecurityManager();
- if(secMgr != null) {
- secMgr.checkPermission(RuntimePermission.permissionToSetIO);
- }
setFieldImpl("err", "Ljava/io/PrintStream;", newErr);
}
@@ -204,10 +172,6 @@
*
* @param code
* the return code.
- * @throws SecurityException
- * if the running thread has not enough permission to exit the
- * virtual machine.
- * @see SecurityManager#checkExit
*/
public static void exit(int code) {
Runtime.getRuntime().exit(code);
@@ -230,23 +194,19 @@
* the name of the environment variable.
* @return the value of the specified environment variable or {@code null}
* if no variable exists with the given name.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPermission()} method does not allow the querying of
- * single environment variables.
*/
public static String getenv(String name) {
if (name == null) {
throw new NullPointerException();
}
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPermission(new RuntimePermission("getenv." + name));
- }
-
return getEnvByName(name);
}
+ private static String getenv(String name, String defaultValue) {
+ String value = getEnvByName(name);
+ return (value != null) ? value : defaultValue;
+ }
+
/*
* Returns an environment variable. No security checks are performed.
* @param var the name of the environment variable
@@ -258,17 +218,8 @@
* Returns an unmodifiable map of all available environment variables.
*
* @return the map representing all environment variables.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPermission()} method does not allow the querying of
- * all environment variables.
*/
public static Map<String, String> getenv() {
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPermission(new RuntimePermission("getenv.*"));
- }
-
Map<String, String> map = new HashMap<String, String>();
int index = 0;
@@ -315,34 +266,77 @@
* subsequent calls to getProperty and getProperties.
*
* @return the system properties.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertiesAccess()} method does not allow the operation.
*/
public static Properties getProperties() {
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPropertiesAccess();
+ if (systemProperties == null) {
+ initSystemProperties();
}
-
- return internalGetProperties();
+ return systemProperties;
}
- /**
- * Returns the system properties without any security checks. This is used
- * for access from within java.lang.
- *
- * @return the system properties
- */
- static Properties internalGetProperties() {
- if (System.systemProperties == null) {
- SystemProperties props = new SystemProperties();
- props.preInit();
- props.postInit();
- System.systemProperties = props;
+ private static void initSystemProperties() {
+ VMRuntime runtime = VMRuntime.getRuntime();
+ Properties p = new Properties();
+
+ String projectUrl = "http://www.android.com/";
+ String projectName = "The Android Project";
+
+ p.put("java.boot.class.path", runtime.bootClassPath());
+ p.put("java.class.path", runtime.classPath());
+
+ p.put("java.class.version", "46.0");
+ p.put("java.compiler", "");
+ p.put("java.ext.dirs", "");
+
+ p.put("java.home", getenv("JAVA_HOME", "/system"));
+
+ p.put("java.io.tmpdir", "/tmp");
+ p.put("java.library.path", getenv("LD_LIBRARY_PATH"));
+
+ p.put("java.net.preferIPv6Addresses", "true");
+
+ p.put("java.specification.name", "Dalvik Core Library");
+ p.put("java.specification.vendor", projectName);
+ p.put("java.specification.version", "0.9");
+
+ p.put("java.vendor", projectName);
+ p.put("java.vendor.url", projectUrl);
+ p.put("java.version", "0");
+ p.put("java.vm.name", "Dalvik");
+ p.put("java.vm.specification.name", "Dalvik Virtual Machine Specification");
+ p.put("java.vm.specification.vendor", projectName);
+ p.put("java.vm.specification.version", "0.9");
+ p.put("java.vm.vendor", projectName);
+ p.put("java.vm.version", runtime.vmVersion());
+
+ p.put("file.separator", "/");
+ p.put("line.separator", "\n");
+ p.put("path.separator", ":");
+
+ p.put("java.runtime.name", "Android Runtime");
+ p.put("java.runtime.version", "0.9");
+ p.put("java.vm.vendor.url", projectUrl);
+
+ p.put("file.encoding", "UTF-8");
+ p.put("user.language", "en");
+ p.put("user.region", "US");
+
+ p.put("user.home", getenv("HOME", ""));
+ p.put("user.name", getenv("USER", ""));
+
+ // Undocumented Android-only properties.
+ p.put("android.icu.library.version", ICU.getIcuVersion());
+ p.put("android.icu.unicode.version", ICU.getUnicodeVersion());
+
+ // Override built-in properties with settings from the command line.
+ for (String arg : runtime.properties()) {
+ int split = arg.indexOf('=');
+ String key = arg.substring(0, split);
+ String value = arg.substring(split + 1);
+ p.put(key, value);
}
- return systemProperties;
+ systemProperties = p;
}
/**
@@ -394,9 +388,6 @@
* the name of the system property to look up.
* @return the value of the specified system property or {@code null} if the
* property doesn't exist.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertyAccess()} method does not allow the operation.
*/
public static String getProperty(String propertyName) {
return getProperty(propertyName, null);
@@ -413,20 +404,12 @@
* does not exist.
* @return the value of the specified system property or the {@code
* defaultValue} if the property does not exist.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertyAccess()} method does not allow the operation.
*/
public static String getProperty(String prop, String defaultValue) {
- if (prop.length() == 0) {
+ if (prop.isEmpty()) {
throw new IllegalArgumentException();
}
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPropertyAccess(prop);
- }
-
- return internalGetProperties().getProperty(prop, defaultValue);
+ return getProperties().getProperty(prop, defaultValue);
}
/**
@@ -438,19 +421,12 @@
* the value to associate with the given property {@code prop}.
* @return the old value of the property or {@code null} if the property
* didn't exist.
- * @throws SecurityException
- * if a security manager exists and write access to the
- * specified property is not allowed.
*/
public static String setProperty(String prop, String value) {
- if (prop.length() == 0) {
+ if (prop.isEmpty()) {
throw new IllegalArgumentException();
}
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPermission(new PropertyPermission(prop, "write"));
- }
- return (String)internalGetProperties().setProperty(prop, value);
+ return (String) getProperties().setProperty(prop, value);
}
/**
@@ -463,23 +439,15 @@
* if the argument {@code key} is {@code null}.
* @throws IllegalArgumentException
* if the argument {@code key} is empty.
- * @throws SecurityException
- * if a security manager exists and write access to the
- * specified property is not allowed.
*/
public static String clearProperty(String key) {
if (key == null) {
throw new NullPointerException();
}
- if (key.length() == 0) {
+ if (key.isEmpty()) {
throw new IllegalArgumentException();
}
-
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPermission(new PropertyPermission(key, "write"));
- }
- return (String)internalGetProperties().remove(key);
+ return (String) getProperties().remove(key);
}
/**
@@ -523,14 +491,8 @@
*
* @param pathName
* the path of the file to be loaded.
- * @throws SecurityException
- * if the library was not allowed to be loaded.
*/
public static void load(String pathName) {
- SecurityManager smngr = System.getSecurityManager();
- if (smngr != null) {
- smngr.checkLink(pathName);
- }
Runtime.getRuntime().load(pathName, VMStack.getCallingClassLoader());
}
@@ -543,14 +505,8 @@
* the name of the library to load.
* @throws UnsatisfiedLinkError
* if the library could not be loaded.
- * @throws SecurityException
- * if the library was not allowed to be loaded.
*/
public static void loadLibrary(String libName) {
- SecurityManager smngr = System.getSecurityManager();
- if (smngr != null) {
- smngr.checkLink(libName);
- }
Runtime.getRuntime().loadLibrary(libName, VMStack.getCallingClassLoader());
}
@@ -578,20 +534,11 @@
}
/**
- * Sets all system properties.
- *
- * @param p
- * the new system property.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertiesAccess()} method does not allow the operation.
+ * Sets all system properties. This does not take a copy; the passed-in object is used
+ * directly. Passing null causes the VM to reinitialize the properties to how they were
+ * when the VM was started.
*/
public static void setProperties(Properties p) {
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPropertiesAccess();
- }
-
systemProperties = p;
}
@@ -668,16 +615,3 @@
}
}
}
-
-/**
- * Internal class holding the System properties. Needed by the Dalvik VM for the
- * two native methods. Must not be a local class, since we don't have a System
- * instance.
- */
-class SystemProperties extends Properties {
- // Dummy, just to make the compiler happy.
-
- native void preInit();
-
- native void postInit();
-}
diff --git a/luni/src/main/java/java/lang/Thread.java b/luni/src/main/java/java/lang/Thread.java
index e26ecf0..7834395 100644
--- a/luni/src/main/java/java/lang/Thread.java
+++ b/luni/src/main/java/java/lang/Thread.java
@@ -33,10 +33,8 @@
package java.lang;
import dalvik.system.VMStack;
-import java.security.AccessController;
import java.util.HashMap;
import java.util.Map;
-import org.apache.harmony.security.fortress.SecurityUtils;
/**
* A {@code Thread} is a concurrent unit of execution. It has its own call stack
@@ -119,17 +117,17 @@
/**
* The maximum priority value allowed for a thread.
*/
- public final static int MAX_PRIORITY = 10;
+ public static final int MAX_PRIORITY = 10;
/**
* The minimum priority value allowed for a thread.
*/
- public final static int MIN_PRIORITY = 1;
+ public static final int MIN_PRIORITY = 1;
/**
* The normal (default) priority value assigned to threads.
*/
- public final static int NORM_PRIORITY = 5;
+ public static final int NORM_PRIORITY = 5;
/* some of these are accessed directly by the VM; do not rename them */
volatile VMThread vmThread;
@@ -275,15 +273,10 @@
* @param runnable
* a {@code Runnable} whose method <code>run</code> will be
* executed by the new {@code Thread}
- * @throws SecurityException
- * if <code>group.checkAccess()</code> fails with a
- * SecurityException
* @throws IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, Runnable runnable) {
create(group, runnable, null, 0);
@@ -300,15 +293,10 @@
* executed by the new {@code Thread}
* @param threadName
* the name for the {@code Thread} being created
- * @throws SecurityException
- * if <code>group.checkAccess()</code> fails with a
- * SecurityException
* @throws IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, Runnable runnable, String threadName) {
if (threadName == null) {
@@ -326,15 +314,10 @@
* {@code ThreadGroup} to which the new {@code Thread} will belong
* @param threadName
* the name for the {@code Thread} being created
- * @throws SecurityException
- * if <code>group.checkAccess()</code> fails with a
- * SecurityException
* @throws IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, String threadName) {
if (threadName == null) {
@@ -360,15 +343,10 @@
* a stack size for the new {@code Thread}. This has a highly
* platform-dependent interpretation. It may even be ignored
* completely.
- * @throws SecurityException
- * if <code>group.checkAccess()</code> fails with a
- * SecurityException
* @throws IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
if (threadName == null) {
@@ -420,53 +398,17 @@
* be executed by the new Thread
* @param threadName Name for the Thread being created
* @param stackSize Platform dependent stack size
- * @throws SecurityException if <code>group.checkAccess()</code> fails
- * with a SecurityException
* @throws IllegalThreadStateException if <code>group.destroy()</code> has
* already been done
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
*/
private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- if (group == null) {
- group = smgr.getThreadGroup();
- }
-
- /*
- * Freaky security requirement: If the Thread's class is actually
- * a subclass of Thread and it tries to override either
- * getContextClassLoader() or setContextClassLoader(), the
- * SecurityManager has to allow this.
- */
- if (getClass() != Thread.class) {
- Class[] signature = new Class[] { ClassLoader.class };
-
- try {
- getClass().getDeclaredMethod("getContextClassLoader", signature);
- smgr.checkPermission(new RuntimePermission("enableContextClassLoaderOverride"));
- } catch (NoSuchMethodException ex) {
- // Ignore. Just interested in the method's existence.
- }
-
- try {
- getClass().getDeclaredMethod("setContextClassLoader", signature);
- smgr.checkPermission(new RuntimePermission("enableContextClassLoaderOverride"));
- } catch (NoSuchMethodException ex) {
- // Ignore. Just interested in the method's existence.
- }
- }
- }
-
Thread currentThread = Thread.currentThread();
if (group == null) {
group = currentThread.getThreadGroup();
}
- group.checkAccess();
if (group.isDestroyed()) {
throw new IllegalThreadStateException("Group already destroyed");
}
@@ -492,13 +434,9 @@
// Transfer over InheritableThreadLocals.
if (currentThread.inheritableValues != null) {
- inheritableValues
- = new ThreadLocal.Values(currentThread.inheritableValues);
+ inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues);
}
- // store current AccessControlContext as inherited context for this thread
- SecurityUtils.putContext(this, AccessController.getContext());
-
// add ourselves to our ThreadGroup of choice
this.group.addThread(this);
}
@@ -514,26 +452,9 @@
}
/**
- * Is used for operations that require approval from a SecurityManager. If
- * there's none installed, this method is a no-op. If there's a
- * SecurityManager installed, {@link SecurityManager#checkAccess(Thread)} is
- * called for that SecurityManager.
- *
- * @throws SecurityException
- * if a SecurityManager is installed and it does not allow
- * access to the Thread.
- *
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
+ * Does nothing.
*/
public final void checkAccess() {
- // Forwards the message to the SecurityManager (if there's one) passing
- // the receiver as parameter
-
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkAccess(this);
- }
}
/**
@@ -587,37 +508,16 @@
* @param threads
* array into which the Threads will be copied
* @return How many Threads were copied over
- * @throws SecurityException
- * if the installed SecurityManager fails
- * {@link SecurityManager#checkAccess(Thread)}
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
*/
public static int enumerate(Thread[] threads) {
Thread thread = Thread.currentThread();
- thread.checkAccess();
return thread.getThreadGroup().enumerate(threads);
}
/**
- * <p>
- * Returns the stack traces of all the currently live threads and puts them
- * into the given map.
- * </p>
- *
- * @return A Map of current Threads to StackTraceElement arrays.
- * @throws SecurityException
- * if the current SecurityManager fails the
- * {@link SecurityManager#checkPermission(java.security.Permission)}
- * call.
+ * Returns a map of all the currently live threads to their stack traces.
*/
public static Map<Thread, StackTraceElement[]> getAllStackTraces() {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkPermission(new RuntimePermission("getStackTrace"));
- securityManager.checkPermission(new RuntimePermission("modifyThreadGroup"));
- }
-
Map<Thread, StackTraceElement[]> map = new HashMap<Thread, StackTraceElement[]>();
// Find out how many live threads we have. Allocate a bit more
@@ -636,40 +536,12 @@
/**
* Returns the context ClassLoader for this Thread.
- * <p>
- * If the conditions
- * <ol>
- * <li>there is a security manager
- * <li>the caller's class loader is not null
- * <li>the caller's class loader is not the same as the requested
- * context class loader and not an ancestor thereof
- * </ol>
- * are satisfied, a security check for
- * <code>RuntimePermission("getClassLoader")</code> is performed first.
*
* @return ClassLoader The context ClassLoader
* @see java.lang.ClassLoader
* @see #getContextClassLoader()
- *
- * @throws SecurityException
- * if the aforementioned security check fails.
*/
public ClassLoader getContextClassLoader() {
- // First, if the conditions
- // 1) there is a security manager
- // 2) the caller's class loader is not null
- // 3) the caller's class loader is not the same as the context
- // class loader and not an ancestor thereof
- // are satisfied we should perform a security check.
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- ClassLoader calling = VMStack.getCallingClassLoader();
-
- if (calling != null && !calling.isAncestorOf(contextClassLoader)) {
- sm.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
return contextClassLoader;
}
@@ -716,25 +588,9 @@
}
/**
- * Returns the a stack trace representing the current execution state of
- * this Thread.
- * <p>
- * The <code>RuntimePermission("getStackTrace")</code> is checked before
- * returning a result.
- * </p>
- *
- * @return an array of StackTraceElements.
- * @throws SecurityException
- * if the current SecurityManager fails the
- * {@link SecurityManager#checkPermission(java.security.Permission)}
- * call.
+ * Returns an array of {@link StackTraceElement} representing the current thread's stack.
*/
public StackTraceElement[] getStackTrace() {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkPermission(new RuntimePermission("getStackTrace"));
- }
-
StackTraceElement ste[] = VMStack.getThreadStackTrace(this);
return ste != null ? ste : EMPTY_STACK_TRACE;
}
@@ -792,10 +648,7 @@
}
/**
- * Posts an interrupt request to this {@code Thread}. Unless the caller is
- * the {@link #currentThread()}, the method {@code checkAccess()} is called
- * for the installed {@code SecurityManager}, if any. This may result in a
- * {@code SecurityException} being thrown. The further behavior depends on
+ * Posts an interrupt request to this {@code Thread}. The behavior depends on
* the state of this {@code Thread}:
* <ul>
* <li>
@@ -815,16 +668,10 @@
* exception in this case.
* <ul>
*
- * @throws SecurityException
- * if <code>checkAccess()</code> fails with a SecurityException
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
* @see Thread#interrupted
* @see Thread#isInterrupted
*/
public void interrupt() {
- checkAccess();
-
if (interruptAction != null) {
interruptAction.run();
}
@@ -994,15 +841,11 @@
* suspended, however, makes it resume to the point where it was when it was
* suspended.
*
- * @throws SecurityException
- * if <code>checkAccess()</code> fails with a SecurityException
* @see Thread#suspend()
* @deprecated Used with deprecated method {@link Thread#suspend}
*/
@Deprecated
public final void resume() {
- checkAccess();
-
VMThread vmt = this.vmThread;
if (vmt != null) {
vmt.resume();
@@ -1023,23 +866,11 @@
/**
* Set the context ClassLoader for the receiver.
- * <p>
- * The <code>RuntimePermission("setContextClassLoader")</code>
- * is checked prior to setting the handler.
- * </p>
*
* @param cl The context ClassLoader
- * @throws SecurityException if the current SecurityManager fails the
- * checkPermission call.
- * @see java.lang.ClassLoader
* @see #getContextClassLoader()
*/
public void setContextClassLoader(ClassLoader cl) {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkPermission(new RuntimePermission("setContextClassLoader"));
- }
-
contextClassLoader = cl;
}
@@ -1049,13 +880,9 @@
*
* @param isDaemon
* indicates whether the Thread should be daemon or not
- * @throws SecurityException
- * if <code>checkAccess()</code> fails with a SecurityException
* @see Thread#isDaemon
*/
public final void setDaemon(boolean isDaemon) {
- checkAccess();
-
if (hasBeenStarted) {
throw new IllegalThreadStateException("Thread already started."); // TODO Externalize?
}
@@ -1066,27 +893,13 @@
}
/**
- * <p>
* Sets the default uncaught exception handler. This handler is invoked in
* case any Thread dies due to an unhandled exception.
- * </p>
- * <p>
- * The <code>RuntimePermission("setDefaultUncaughtExceptionHandler")</code>
- * is checked prior to setting the handler.
- * </p>
*
* @param handler
- * The handler to set or <code>null</code>.
- * @throws SecurityException
- * if the current SecurityManager fails the checkPermission
- * call.
+ * The handler to set or null.
*/
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkPermission(new RuntimePermission ("setDefaultUncaughtExceptionHandler"));
- }
-
Thread.defaultUncaughtHandler = handler;
}
@@ -1110,8 +923,6 @@
* Sets the name of the Thread.
*
* @param threadName the new name for the Thread
- * @throws SecurityException if <code>checkAccess()</code> fails with a
- * SecurityException
* @see Thread#getName
*/
public final void setName(String threadName) {
@@ -1119,8 +930,6 @@
throw new NullPointerException();
}
- checkAccess();
-
name = threadName;
VMThread vmt = this.vmThread;
if (vmt != null) {
@@ -1137,16 +946,12 @@
*
* @param priority
* new priority for the Thread
- * @throws SecurityException
- * if <code>checkAccess()</code> fails with a SecurityException
* @throws IllegalArgumentException
* if the new priority is greater than Thread.MAX_PRIORITY or
* less than Thread.MIN_PRIORITY
* @see Thread#getPriority
*/
public final void setPriority(int priority) {
- checkAccess();
-
if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
throw new IllegalArgumentException("Priority out of range"); // TODO Externalize?
}
@@ -1171,12 +976,8 @@
*
* @param handler
* The handler to set or <code>null</code>.
- * @throws SecurityException
- * if the current SecurityManager fails the checkAccess call.
*/
public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
- checkAccess();
-
uncaughtHandler = handler;
}
@@ -1238,8 +1039,6 @@
* resumed if it was suspended and awakened if it was sleeping, so that it
* can proceed to throw ThreadDeath.
*
- * @throws SecurityException if <code>checkAccess()</code> fails with a
- * SecurityException
* @deprecated because stopping a thread in this manner is unsafe and can
* leave your application and the VM in an unpredictable state.
*/
@@ -1255,8 +1054,6 @@
* <code>throwable()</code>.
*
* @param throwable Throwable object to be thrown by the Thread
- * @throws SecurityException if <code>checkAccess()</code> fails with a
- * SecurityException
* @throws NullPointerException if <code>throwable()</code> is
* <code>null</code>
* @deprecated because stopping a thread in this manner is unsafe and can
@@ -1264,14 +1061,6 @@
*/
@Deprecated
public final synchronized void stop(Throwable throwable) {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkAccess(this);
- if (Thread.currentThread() != this) {
- securityManager.checkPermission(new RuntimePermission("stopThread"));
- }
- }
-
if (throwable == null) {
throw new NullPointerException();
}
@@ -1289,15 +1078,11 @@
* means that N requests are equivalent to just one - only one resume
* request is needed in this case.
*
- * @throws SecurityException
- * if <code>checkAccess()</code> fails with a SecurityException
* @see Thread#resume()
* @deprecated May cause deadlocks.
*/
@Deprecated
public final void suspend() {
- checkAccess();
-
VMThread vmt = this.vmThread;
if (vmt != null) {
vmt.suspend();
diff --git a/luni/src/main/java/java/lang/ThreadGroup.java b/luni/src/main/java/java/lang/ThreadGroup.java
index 599b0c4..d0e593f 100644
--- a/luni/src/main/java/java/lang/ThreadGroup.java
+++ b/luni/src/main/java/java/lang/ThreadGroup.java
@@ -27,7 +27,6 @@
* {@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.
* @see Thread
- * @see SecurityManager
*/
public class ThreadGroup implements Thread.UncaughtExceptionHandler {
@@ -74,8 +73,6 @@
* will be child of the {@code ThreadGroup} to which the calling thread belongs.
*
* @param name the name
- * @throws SecurityException if {@code checkAccess()} for the parent
- * group fails with a SecurityException
* @see Thread#currentThread
*/
@@ -90,18 +87,13 @@
* @param parent the parent
* @param name the name
* @throws NullPointerException if {@code parent == null}
- * @throws SecurityException if {@code checkAccess()} for the parent
- * group fails with a SecurityException
* @throws IllegalThreadStateException if {@code parent} has been
* destroyed already
*/
public ThreadGroup(ThreadGroup parent, String name) {
- if (Thread.currentThread() != null) {
- // If parent is null we must throw NullPointerException, but that
- // will be done "for free" with the message send below
- parent.checkAccess();
+ if (parent == null) {
+ throw new NullPointerException("parent == null");
}
-
this.name = name;
this.parent = parent;
if (parent != null) {
@@ -163,24 +155,6 @@
}
/**
- * 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(Thread)
- */
- final void add(Thread thread) throws IllegalThreadStateException {
- synchronized (threadRefs) {
- if (isDestroyed) {
- throw new IllegalThreadStateException();
- }
- threadRefs.add(new WeakReference<Thread>(thread));
- }
- }
-
- /**
* Adds a {@code ThreadGroup} to this thread group.
*
* @param g ThreadGroup to add
@@ -212,16 +186,9 @@
}
/**
- * Checks the accessibility of this {@code ThreadGroup} from the perspective of the
- * caller. If there is a {@code SecurityManager} installed, calls
- * {@code checkAccess} with this thread group as a parameter, otherwise does
- * nothing.
+ * Does nothing.
*/
public final void checkAccess() {
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkAccess(this);
- }
}
/**
@@ -233,12 +200,8 @@
* @throws IllegalThreadStateException if this thread group or any of its
* subgroups has been destroyed already or if it still contains
* threads.
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
*/
public final void destroy() {
- checkAccess();
-
synchronized (threadRefs) {
synchronized (groups) {
if (isDestroyed) {
@@ -373,8 +336,6 @@
*/
private int enumerateGeneric(Object[] enumeration, boolean recurse, int enumerationIndex,
boolean enumeratingThreads) {
- checkAccess();
-
if (enumeratingThreads) {
synchronized (threadRefs) {
// walk the references directly so we can iterate in reverse order
@@ -440,9 +401,6 @@
* @return the parent
*/
public final ThreadGroup getParent() {
- if (parent != null) {
- parent.checkAccess();
- }
return parent;
}
@@ -450,13 +408,9 @@
* Interrupts every {@code Thread} in this group and recursively in all its
* subgroups.
*
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
* @see Thread#interrupt
*/
public final void interrupt() {
- checkAccess();
synchronized (threadRefs) {
for (Thread thread : threads) {
thread.interrupt();
@@ -553,26 +507,6 @@
}
/**
- * Removes a {@code Thread} from this group. This should only be visible to class
- * Thread, and should only be called when a Thread dies.
- *
- * @param thread Thread to remove
- *
- * @see #add(Thread)
- */
- final void remove(Thread thread) {
- synchronized (threadRefs) {
- for (Iterator<Thread> i = threads.iterator(); i.hasNext(); ) {
- if (i.next().equals(thread)) {
- i.remove();
- break;
- }
- }
- }
- destroyIfEmptyDaemon();
- }
-
- /**
* Removes an immediate subgroup.
*
* @param g ThreadGroup to remove
@@ -597,9 +531,6 @@
* Resumes every thread in this group and recursively in all its
* subgroups.
*
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
* @see Thread#resume
* @see #suspend
*
@@ -608,7 +539,6 @@
@SuppressWarnings("deprecation")
@Deprecated
public final void resume() {
- checkAccess();
synchronized (threadRefs) {
for (Thread thread : threads) {
thread.resume();
@@ -626,14 +556,10 @@
* thread groups are automatically destroyed when they become empty.
*
* @param isDaemon the new value
- * @throws SecurityException if {@code checkAccess()} for the parent
- * group fails with a SecurityException
- *
* @see #isDaemon
* @see #destroy
*/
public final void setDaemon(boolean isDaemon) {
- checkAccess();
this.isDaemon = isDaemon;
}
@@ -647,16 +573,12 @@
*
* @param newMax the new maximum priority to be set
*
- * @throws SecurityException if {@code checkAccess()} fails with a
- * SecurityException
* @throws IllegalArgumentException if the new priority is greater than
* Thread.MAX_PRIORITY or less than Thread.MIN_PRIORITY
*
* @see #getMaxPriority
*/
public final void setMaxPriority(int newMax) {
- checkAccess();
-
if (newMax <= this.maxPriority) {
if (newMax < Thread.MIN_PRIORITY) {
newMax = Thread.MIN_PRIORITY;
@@ -675,9 +597,6 @@
/**
* Stops every thread in this group and recursively in all its subgroups.
*
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
* @see Thread#stop()
* @see Thread#stop(Throwable)
* @see ThreadDeath
@@ -694,8 +613,6 @@
@SuppressWarnings("deprecation")
private boolean stopHelper() {
- checkAccess();
-
boolean stopCurrent = false;
synchronized (threadRefs) {
Thread current = Thread.currentThread();
@@ -719,9 +636,6 @@
* Suspends every thread in this group and recursively in all its
* subgroups.
*
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
* @see Thread#suspend
* @see #resume
*
@@ -737,8 +651,6 @@
@SuppressWarnings("deprecation")
private boolean suspendHelper() {
- checkAccess();
-
boolean suspendCurrent = false;
synchronized (threadRefs) {
Thread current = Thread.currentThread();
@@ -787,32 +699,29 @@
}
/**
- * Non-standard method for adding a thread to a group, required by Dalvik.
- *
- * @param thread Thread to add
- *
- * @throws IllegalThreadStateException if the thread has been destroyed
- * already
- *
- * @see #add(Thread)
- * @see #removeThread(Thread)
+ * Called by the Thread constructor.
*/
- void addThread(Thread thread) throws IllegalThreadStateException {
- add(thread);
+ final void addThread(Thread thread) throws IllegalThreadStateException {
+ synchronized (threadRefs) {
+ if (isDestroyed) {
+ throw new IllegalThreadStateException();
+ }
+ threadRefs.add(new WeakReference<Thread>(thread));
+ }
}
/**
- * Non-standard method for adding a thread to a group, required by Dalvik.
- *
- * @param thread Thread to add
- *
- * @throws IllegalThreadStateException if the thread has been destroyed
- * already
- *
- * @see #remove(Thread)
- * @see #addThread(Thread)
+ * Called by the VM when a Thread dies.
*/
- void removeThread(Thread thread) throws IllegalThreadStateException {
- remove(thread);
+ final void removeThread(Thread thread) throws IllegalThreadStateException {
+ synchronized (threadRefs) {
+ for (Iterator<Thread> i = threads.iterator(); i.hasNext(); ) {
+ if (i.next().equals(thread)) {
+ i.remove();
+ break;
+ }
+ }
+ }
+ destroyIfEmptyDaemon();
}
}
diff --git a/luni/src/main/java/java/lang/Void.java b/luni/src/main/java/java/lang/Void.java
index 1773d43..19f267a 100644
--- a/luni/src/main/java/java/lang/Void.java
+++ b/luni/src/main/java/java/lang/Void.java
@@ -31,8 +31,7 @@
* The {@link Class} object that represents the primitive type {@code void}.
*/
public static final Class<Void> TYPE = lookupType();
-
- // Note: This can't be set to "void.class", since *that* is
+ // Note: Void.TYPE can't be set to "void.class", since *that* is
// defined to be "java.lang.Void.TYPE";
@SuppressWarnings("unchecked")
diff --git a/luni/src/main/java/java/lang/ref/ReferenceQueue.java b/luni/src/main/java/java/lang/ref/ReferenceQueue.java
index ac6d695..b59d4f5 100644
--- a/luni/src/main/java/java/lang/ref/ReferenceQueue.java
+++ b/luni/src/main/java/java/lang/ref/ReferenceQueue.java
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// This implementation is quite different from Harmony. Changes are not marked.
-// END android-note
-
package java.lang.ref;
/**
diff --git a/luni/src/main/java/java/lang/reflect/AccessibleObject.java b/luni/src/main/java/java/lang/reflect/AccessibleObject.java
index 33abc08..a5ae2c3 100644
--- a/luni/src/main/java/java/lang/reflect/AccessibleObject.java
+++ b/luni/src/main/java/java/lang/reflect/AccessibleObject.java
@@ -52,11 +52,10 @@
* @see Field
* @see Constructor
* @see Method
- * @see ReflectPermission
*/
public class AccessibleObject implements AnnotatedElement {
- // If true, object is accessible, bypassing normal security checks
+ // If true, object is accessible, bypassing normal access checks
boolean flag = false;
// Holds a mapping from Java type names to native type codes.
@@ -77,29 +76,18 @@
/**
* Attempts to set the value of the accessible flag for all the objects in
- * the array provided. Only one security check is performed. Setting this
+ * the array provided. Setting this
* flag to {@code false} will enable access checks, setting to {@code true}
- * will disable them. If there is a security manager, checkPermission is
- * called with a {@code ReflectPermission("suppressAccessChecks")}.
+ * will disable them.
*
* @param objects
* the accessible objects
* @param flag
* the new value for the accessible flag
*
- * @throws SecurityException
- * if the request is denied
- *
* @see #setAccessible(boolean)
- * @see ReflectPermission
*/
- public static void setAccessible(AccessibleObject[] objects, boolean flag)
- throws SecurityException {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkPermission(new ReflectPermission("suppressAccessChecks"));
- }
-
+ public static void setAccessible(AccessibleObject[] objects, boolean flag) {
synchronized(AccessibleObject.class) {
for (int i = 0; i < objects.length; i++) {
objects[i].flag = flag;
@@ -117,10 +105,10 @@
}
/**
- * Indicates whether this object is accessible without security checks being
+ * Indicates whether this object is accessible without access checks being
* performed. Returns the accessible flag.
*
- * @return {@code true} if this object is accessible without security
+ * @return {@code true} if this object is accessible without access
* checks, {@code false} otherwise
*/
public boolean isAccessible() {
@@ -130,23 +118,12 @@
/**
* Attempts to set the value of the accessible flag. Setting this flag to
* {@code false} will enable access checks, setting to {@code true} will
- * disable them. If there is a security manager, checkPermission is called
- * with a {@code ReflectPermission("suppressAccessChecks")}.
+ * disable them.
*
* @param flag
* the new value for the accessible flag
- *
- * @throws SecurityException
- * if the request is denied
- *
- * @see ReflectPermission
*/
- public void setAccessible(boolean flag) throws SecurityException {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkPermission(new ReflectPermission("suppressAccessChecks"));
- }
-
+ public void setAccessible(boolean flag) {
this.flag = flag;
}
diff --git a/luni/src/main/java/java/lang/reflect/Array.java b/luni/src/main/java/java/lang/reflect/Array.java
index db0d426..3ecfae0 100644
--- a/luni/src/main/java/java/lang/reflect/Array.java
+++ b/luni/src/main/java/java/lang/reflect/Array.java
@@ -411,7 +411,7 @@
if (dimensions.length <= 0 || dimensions.length > 255)
throw new IllegalArgumentException("Bad number of dimensions");
- if (componentType == Void.TYPE)
+ if (componentType == void.class)
throw new IllegalArgumentException();
if (componentType == null)
@@ -444,37 +444,37 @@
*/
public static Object newInstance(Class<?> componentType, int size)
throws NegativeArraySizeException {
- if (!componentType.isPrimitive())
+ if (!componentType.isPrimitive()) {
return createObjectArray(componentType, size);
-
- if (componentType == Boolean.TYPE)
+ }
+ if (componentType == boolean.class) {
return new boolean[size];
-
- if (componentType == Byte.TYPE)
+ }
+ if (componentType == byte.class) {
return new byte[size];
-
- if (componentType == Character.TYPE)
+ }
+ if (componentType == char.class) {
return new char[size];
-
- if (componentType == Short.TYPE)
+ }
+ if (componentType == short.class) {
return new short[size];
-
- if (componentType == Integer.TYPE)
+ }
+ if (componentType == int.class) {
return new int[size];
-
- if (componentType == Long.TYPE)
+ }
+ if (componentType == long.class) {
return new long[size];
-
- if (componentType == Float.TYPE)
+ }
+ if (componentType == float.class) {
return new float[size];
-
- if (componentType == Double.TYPE)
+ }
+ if (componentType == double.class) {
return new double[size];
-
- if (componentType == Void.TYPE)
+ }
+ if (componentType == void.class) {
throw new IllegalArgumentException();
-
- throw new RuntimeException(); // should be impossible
+ }
+ throw new AssertionError();
}
/*
diff --git a/luni/src/main/java/java/lang/reflect/Field.java b/luni/src/main/java/java/lang/reflect/Field.java
index 1d2726c..8877cc5 100644
--- a/luni/src/main/java/java/lang/reflect/Field.java
+++ b/luni/src/main/java/java/lang/reflect/Field.java
@@ -517,9 +517,7 @@
*/
@Override
public int hashCode() {
- // BEGIN android-changed
return name.hashCode() ^ getDeclaringClass().getName().hashCode();
- // END android-changed
}
/**
diff --git a/luni/src/main/java/java/lang/reflect/Member.java b/luni/src/main/java/java/lang/reflect/Member.java
index 0600588..a43ac6e 100644
--- a/luni/src/main/java/java/lang/reflect/Member.java
+++ b/luni/src/main/java/java/lang/reflect/Member.java
@@ -29,16 +29,12 @@
/**
* Designates all public members of a class or interface (including
* inherited members).
- *
- * @see java.lang.SecurityManager#checkMemberAccess
*/
public static final int PUBLIC = 0;
/**
* Designates all declared members of a class or interface (without
* inherited members).
- *
- * @see java.lang.SecurityManager#checkMemberAccess
*/
public static final int DECLARED = 1;
diff --git a/luni/src/main/java/java/lang/reflect/Modifier.java b/luni/src/main/java/java/lang/reflect/Modifier.java
index 4ae460b..28e98614 100644
--- a/luni/src/main/java/java/lang/reflect/Modifier.java
+++ b/luni/src/main/java/java/lang/reflect/Modifier.java
@@ -277,7 +277,6 @@
* the modifiers to print
* @return a printable representation of the modifiers
*/
- @SuppressWarnings("nls")
public static java.lang.String toString(int modifiers) {
StringBuilder buf = new StringBuilder();
diff --git a/luni/src/main/java/java/lang/reflect/Proxy.java b/luni/src/main/java/java/lang/reflect/Proxy.java
index 92b04f6..a24514d 100644
--- a/luni/src/main/java/java/lang/reflect/Proxy.java
+++ b/luni/src/main/java/java/lang/reflect/Proxy.java
@@ -23,10 +23,6 @@
import java.util.Map;
import java.util.WeakHashMap;
-// BEGIN android-removed
-// import org.apache.harmony.luni.internal.reflect.ProxyClassFile;
-// END android-removed
-
/**
* {@code Proxy} defines methods for creating dynamic proxy classes and instances.
* A proxy class implements a declared set of interfaces and delegates method
@@ -91,9 +87,6 @@
*/
public static Class<?> getProxyClass(ClassLoader loader,
Class<?>... interfaces) throws IllegalArgumentException {
- // BEGIN android-note
- // Changed parameter to be closer to the RI
- // END android-note
// check that interfaces are a valid array of visible interfaces
if (interfaces == null) {
throw new NullPointerException();
@@ -165,21 +158,13 @@
if (commonPackageName != null && commonPackageName.length() > 0) {
nextClassName = commonPackageName + "." + nextClassName;
}
- // BEGIN android-changed
- // byte[] classFileBytes = ProxyClassFile.generateBytes(
- // nextClassName, interfaces);
- // newClass = defineClassImpl(loader, nextClassName.replace('.',
- // '/'), classFileBytes);
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
- newClass = generateProxy(nextClassName.replace('.', '/'),
- interfaces, loader);
- // END android-changed
+ newClass = generateProxy(nextClassName.replace('.', '/'), interfaces, loader);
// Need a weak reference to the class so it can
// be unloaded if the class loader is discarded
- interfaceCache.put(interfaceKey, new WeakReference<Class<?>>(
- newClass));
+ interfaceCache.put(interfaceKey, new WeakReference<Class<?>>(newClass));
synchronized (proxyCache) {
// the value is unused
proxyCache.put(newClass, "");
@@ -282,9 +267,6 @@
throw new IllegalArgumentException("not a proxy instance");
}
- // BEGIN android-changed
- //private static native Class<?> defineClassImpl(ClassLoader classLoader,
- // String className, byte[] classFileBytes);
native private static Class generateProxy(String name, Class[] interfaces,
ClassLoader loader);
@@ -293,6 +275,4 @@
* There is no implementation.
*/
native private static void constructorPrototype(InvocationHandler h);
- // END android-changed
-
}
diff --git a/luni/src/main/java/java/math/BigDecimal.java b/luni/src/main/java/java/math/BigDecimal.java
index dd3fb84..0ef3bf5 100644
--- a/luni/src/main/java/java/math/BigDecimal.java
+++ b/luni/src/main/java/java/math/BigDecimal.java
@@ -514,12 +514,10 @@
if(bitLength < 64) {
smallValue = mantissa << (-scale);
} else {
- // BEGIN android-changed
BigInt bi = new BigInt();
bi.putLongInt(mantissa);
bi.shift(-scale);
intVal = new BigInteger(bi);
- // END android-changed
}
scale = 0;
} else if (scale > 0) {
@@ -809,7 +807,6 @@
}
private static BigDecimal addAndMult10(BigDecimal thisValue,BigDecimal augend, int diffScale) {
- // BEGIN android-changed
if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
Math.max(thisValue.bitLength,augend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) {
return valueOf(thisValue.smallValue+augend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],thisValue.scale);
@@ -818,7 +815,6 @@
bi.add(thisValue.getUnscaledValue().getBigInt());
return new BigDecimal(new BigInteger(bi), thisValue.scale);
}
- // END android-changed
}
/**
@@ -1742,11 +1738,9 @@
* @return {@code abs(this)}
*/
public BigDecimal abs(MathContext mc) {
- // BEGIN android-changed
BigDecimal result = abs();
result.inplaceRound(mc);
return result;
- // END android-changed
}
/**
@@ -1771,11 +1765,9 @@
* @return {@code -this}
*/
public BigDecimal negate(MathContext mc) {
- // BEGIN android-changed
BigDecimal result = negate();
result.inplaceRound(mc);
return result;
- // END android-changed
}
/**
@@ -2100,10 +2092,9 @@
long newScale = scale;
if (isZero()) {
- // BEGIN android-changed: preserve RI compatibility, so BigDecimal.equals (which checks
+ // Preserve RI compatibility, so BigDecimal.equals (which checks
// value *and* scale) continues to work.
return this;
- // END android-changed
}
BigInteger strippedBI = getUnscaledValue();
BigInteger[] quotAndRem;
@@ -2751,11 +2742,9 @@
*/
private void inplaceRound(MathContext mc) {
int mcPrecision = mc.getPrecision();
- // BEGIN android-changed
if (approxPrecision() < mcPrecision || mcPrecision == 0) {
return;
}
- // END android-changed
int discardedPrecision = precision() - mcPrecision;
// If no rounding is necessary it returns immediately
if ((discardedPrecision <= 0)) {
@@ -2925,11 +2914,9 @@
* @return an approximation of {@code precision()} value
*/
private int approxPrecision() {
- // BEGIN android-changed
return precision > 0
? precision
: (int) ((this.bitLength - 1) * LOG10_2) + 1;
- // END android-changed
}
private static int safeLongToInt(long longValue) {
diff --git a/luni/src/main/java/java/math/BigInteger.java b/luni/src/main/java/java/math/BigInteger.java
index e75c8f2..cd56afa 100644
--- a/luni/src/main/java/java/math/BigInteger.java
+++ b/luni/src/main/java/java/math/BigInteger.java
@@ -15,12 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// Since the original Harmony Code of the BigInteger class was strongly modified,
-// in order to use the more efficient OpenSSL BIGNUM implementation,
-// no android-modification-tags were placed, at all.
-// END android-note
-
package java.math;
import java.io.IOException;
diff --git a/luni/src/main/java/java/math/MathContext.java b/luni/src/main/java/java/math/MathContext.java
index 1231bc6..1455b5c 100644
--- a/luni/src/main/java/java/math/MathContext.java
+++ b/luni/src/main/java/java/math/MathContext.java
@@ -82,7 +82,7 @@
* @see #MathContext(String)
* @see #toString()
*/
- private final static char[] chPrecision = { 'p', 'r', 'e', 'c', 'i', 's',
+ private static final char[] chPrecision = { 'p', 'r', 'e', 'c', 'i', 's',
'i', 'o', 'n', '=' };
/**
@@ -93,7 +93,7 @@
* @see #MathContext(String)
* @see #toString()
*/
- private final static char[] chRoundingMode = { 'r', 'o', 'u', 'n', 'd',
+ private static final char[] chRoundingMode = { 'r', 'o', 'u', 'n', 'd',
'i', 'n', 'g', 'M', 'o', 'd', 'e', '=' };
/**
@@ -173,9 +173,7 @@
if (digit == -1) {
throw new IllegalArgumentException("Bad string format");
}
- // BEGIN android-changed
this.precision = digit;
- // END android-changed
i++;
do {
diff --git a/luni/src/main/java/java/math/Multiplication.java b/luni/src/main/java/java/math/Multiplication.java
index babca06..98cabee 100644
--- a/luni/src/main/java/java/math/Multiplication.java
+++ b/luni/src/main/java/java/math/Multiplication.java
@@ -79,8 +79,7 @@
}
}
- // BEGIN android-note
- // The method multiply has been removed in favor of using OpenSSL BIGNUM
+ // BEGIN android-note: multiply has been removed in favor of using OpenSSL BIGNUM
// END android-note
/**
diff --git a/luni/src/main/java/java/math/Primality.java b/luni/src/main/java/java/math/Primality.java
index fa7e67a..eacc893 100644
--- a/luni/src/main/java/java/math/Primality.java
+++ b/luni/src/main/java/java/math/Primality.java
@@ -15,12 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// Since the original Harmony Code of the BigInteger class was strongly modified,
-// in order to use the more efficient OpenSSL BIGNUM implementation,
-// no android-modification-tags were placed, at all.
-// END android-note
-
package java.math;
import java.util.Arrays;
diff --git a/luni/src/main/java/java/net/AddressCache.java b/luni/src/main/java/java/net/AddressCache.java
index 7117aba..08f5d81 100644
--- a/luni/src/main/java/java/net/AddressCache.java
+++ b/luni/src/main/java/java/net/AddressCache.java
@@ -16,9 +16,7 @@
package java.net;
-import java.security.AccessController;
import libcore.util.BasicLruCache;
-import org.apache.harmony.luni.util.PriviAction;
/**
* Implements caching for {@code InetAddress}. We use a unified cache for both positive and negative
@@ -106,15 +104,7 @@
// Calculate the expiry time.
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...
long expiryNanos = System.nanoTime() + defaultTtlNanos;
- if (System.getSecurityManager() != null || System.getProperty(propertyName, null) != null) {
- // ...and let those using a SecurityManager or custom properties pay full price.
- expiryNanos = customTtl(propertyName, defaultTtlNanos);
- if (expiryNanos == Long.MIN_VALUE) {
- return;
- }
- }
// Update the cache.
cache.put(hostname, new AddressCacheEntry(value, expiryNanos));
}
@@ -128,7 +118,7 @@
}
private long customTtl(String propertyName, long defaultTtlNanos) {
- String ttlString = AccessController.doPrivileged(new PriviAction<String>(propertyName, null));
+ String ttlString = System.getProperty(propertyName, null);
if (ttlString == null) {
return System.nanoTime() + defaultTtlNanos;
}
diff --git a/luni/src/main/java/java/net/Authenticator.java b/luni/src/main/java/java/net/Authenticator.java
index 3b5fd8c..fc66c89 100644
--- a/luni/src/main/java/java/net/Authenticator.java
+++ b/luni/src/main/java/java/net/Authenticator.java
@@ -118,8 +118,7 @@
}
/**
- * If the permission check of the security manager does not result in a
- * security exception, this method invokes the methods of the registered
+ * Invokes the methods of the registered
* authenticator to get the authentication info.
*
* @return password authentication info or {@code null} if no authenticator
@@ -134,17 +133,10 @@
* realm of the connection that requests authentication.
* @param rScheme
* scheme of the connection that requests authentication.
- * @throws SecurityException
- * if a security manager denies the password authentication
- * permission.
*/
public static synchronized PasswordAuthentication requestPasswordAuthentication(
InetAddress rAddr, int rPort, String rProtocol, String rPrompt,
String rScheme) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(requestPasswordAuthenticationPermission);
- }
if (thisAuthenticator == null) {
return null;
}
@@ -164,27 +156,17 @@
/**
* Sets {@code a} as the default authenticator. It will be called whenever
- * the realm that the URL is pointing to requires authorization. If there is
- * a security manager set then the caller must have the appropriate {@code
- * NetPermission}.
+ * the realm that the URL is pointing to requires authorization.
*
* @param a
* authenticator which has to be set as default.
- * @throws SecurityException
- * if a security manager denies the password authentication
- * permission.
*/
public static void setDefault(Authenticator a) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(setDefaultAuthenticatorPermission);
- }
thisAuthenticator = a;
}
/**
- * If the permission check of the security manager does not result in a
- * security exception, this method invokes the methods of the registered
+ * Invokes the methods of the registered
* authenticator to get the authentication info.
*
* @return password authentication info or {@code null} if no authenticator
@@ -201,17 +183,10 @@
* realm of the connection that requests authentication.
* @param rScheme
* scheme of the connection that requests authentication.
- * @throws SecurityException
- * if a security manager denies the password authentication
- * permission.
*/
public static synchronized PasswordAuthentication requestPasswordAuthentication(
String rHost, InetAddress rAddr, int rPort, String rProtocol,
String rPrompt, String rScheme) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(requestPasswordAuthenticationPermission);
- }
if (thisAuthenticator == null) {
return null;
}
@@ -241,8 +216,7 @@
}
/**
- * If the permission check of the security manager does not result in a
- * security exception, this method invokes the methods of the registered
+ * Invokes the methods of the registered
* authenticator to get the authentication info.
*
* @return password authentication info or {@code null} if no authenticator
@@ -263,18 +237,11 @@
* url of the connection that requests authentication.
* @param reqType
* requestor type of the connection that requests authentication.
- * @throws SecurityException
- * if a security manager denies the password authentication
- * permission.
*/
public static PasswordAuthentication requestPasswordAuthentication(
String rHost, InetAddress rAddr, int rPort, String rProtocol,
String rPrompt, String rScheme, URL rURL,
Authenticator.RequestorType reqType) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(requestPasswordAuthenticationPermission);
- }
if (thisAuthenticator == null) {
return null;
}
diff --git a/luni/src/main/java/java/net/CookieHandler.java b/luni/src/main/java/java/net/CookieHandler.java
index 918c34a..8063ace 100644
--- a/luni/src/main/java/java/net/CookieHandler.java
+++ b/luni/src/main/java/java/net/CookieHandler.java
@@ -27,36 +27,17 @@
private static CookieHandler systemWideCookieHandler;
- private final static NetPermission getCookieHandlerPermission = new NetPermission(
- "getCookieHandler");
-
- private final static NetPermission setCookieHandlerPermission = new NetPermission(
- "setCookieHandler");
-
/**
* Returns the system-wide cookie handler or {@code null} if not set.
- *
- * @return the system-wide cookie handler.
*/
public static CookieHandler getDefault() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(getCookieHandlerPermission);
- }
return systemWideCookieHandler;
}
/**
* Sets the system-wide cookie handler.
- *
- * @param cHandler
- * a cookie handler to set as the system-wide default handler.
*/
public static void setDefault(CookieHandler cHandler) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(setCookieHandlerPermission);
- }
systemWideCookieHandler = cHandler;
}
diff --git a/luni/src/main/java/java/net/DatagramSocket.java b/luni/src/main/java/java/net/DatagramSocket.java
index 5237e49..5143455 100644
--- a/luni/src/main/java/java/net/DatagramSocket.java
+++ b/luni/src/main/java/java/net/DatagramSocket.java
@@ -92,22 +92,10 @@
createSocket(aPort, (addr == null) ? Inet4Address.ANY : addr);
}
- /**
- * Sends prior to attempting to bind the socket, checks whether the port is
- * within the valid port range and verifies with the security manager that
- * the port may be bound by the current context.
- *
- * @param aPort
- * the port on the localhost that is to be bound.
- */
- void checkListen(int aPort) {
+ private void checkListen(int aPort) {
if (aPort < 0 || aPort > 65535) {
throw new IllegalArgumentException("Port out of range: " + aPort);
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkListen(aPort);
- }
}
/**
@@ -147,15 +135,6 @@
// Ignored
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- if (anAddress.isMulticastAddress()) {
- security.checkMulticast(anAddress);
- } else {
- security.checkConnect(anAddress.getHostName(), aPort);
- }
- }
-
try {
impl.connect(anAddress, aPort);
} catch (SocketException e) {
@@ -220,16 +199,7 @@
if (!isBound()) {
return Inet4Address.ANY;
}
- InetAddress anAddr = impl.getLocalAddress();
- try {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkConnect(anAddr.getHostName(), -1);
- }
- } catch (SecurityException e) {
- return Inet4Address.ANY;
- }
- return anAddr;
+ return impl.getLocalAddress();
}
/**
@@ -299,9 +269,7 @@
* pack}. All fields of {@code pack} must be set according to the data
* received. If the received data is longer than the packet buffer size it
* is truncated. This method blocks until a packet is received or a timeout
- * has expired. If a security manager exists, its {@code checkAccept} method
- * determines whether or not a packet is discarded. Any packets from
- * unacceptable origins are silently discarded.
+ * has expired.
*
* @param pack
* the {@code DatagramPacket} to store the received data.
@@ -318,11 +286,8 @@
// means that we have received the packet into the temporary buffer
boolean copy = false;
- SecurityManager security = System.getSecurityManager();
-
- if (address != null || security != null) {
- // The socket is connected or we need to check security permissions
-
+ if (address != null) {
+ // The socket is connected.
// Check pack before peeking
if (pack == null) {
throw new NullPointerException();
@@ -353,21 +318,7 @@
}
}
- if (address == null) {
- // if we are not connected let's check if we are allowed to
- // receive packets from sender's address and port
- try {
- security.checkAccept(senderAddr.getHostName(),
- senderPort);
- // address & port are valid
- break;
- } catch (SecurityException e) {
- if (!copy) {
- // drop this packet and continue
- impl.receive(tempPack);
- }
- }
- } else if (port == senderPort && address.equals(senderAddr)) {
+ if (port == senderPort && address.equals(senderAddr)) {
// we are connected and the packet came
// from the address & port we are connected to
break;
@@ -379,8 +330,8 @@
}
if (copy) {
- System.arraycopy(tempPack.getData(), 0, pack.getData(), pack
- .getOffset(), tempPack.getLength());
+ System.arraycopy(tempPack.getData(), 0, pack.getData(), pack.getOffset(),
+ tempPack.getLength());
// we shouldn't update the pack's capacity field in order to be
// compatible with RI
pack.setLengthOnly(tempPack.getLength());
@@ -395,10 +346,7 @@
}
/**
- * Sends a packet over this socket. The packet must satisfy the security
- * policy before it may be sent. If a security manager is installed, this
- * method checks whether it is allowed to send this packet to the specified
- * address.
+ * Sends a packet over this socket.
*
* @param pack
* the {@code DatagramPacket} which has to be sent.
@@ -423,14 +371,6 @@
if (packAddr == null) {
throw new NullPointerException("Destination address is null");
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- if (packAddr.isMulticastAddress()) {
- security.checkMulticast(packAddr);
- } else {
- security.checkConnect(packAddr.getHostName(), pack.getPort());
- }
- }
}
impl.send(pack);
}
@@ -497,10 +437,7 @@
/**
* Sets the socket implementation factory. This may only be invoked once
* over the lifetime of the application. This factory is used to create
- * a new datagram socket implementation. If a security manager is set its
- * method {@code checkSetFactory()} is called to check if the operation is
- * allowed. A {@code SecurityException} is thrown if the operation is not
- * allowed.
+ * a new datagram socket implementation.
*
* @param fac
* the socket factory to use.
@@ -508,12 +445,8 @@
* if the factory has already been set.
* @see DatagramSocketImplFactory
*/
- public static synchronized void setDatagramSocketImplFactory(
- DatagramSocketImplFactory fac) throws IOException {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkSetFactory();
- }
+ public static synchronized void setDatagramSocketImplFactory(DatagramSocketImplFactory fac)
+ throws IOException {
if (factory != null) {
throw new SocketException("Factory already set");
}
@@ -645,16 +578,6 @@
// make sure the socket is open
checkClosedAndBind(true);
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- if (inetAddr.getAddress().isMulticastAddress()) {
- security.checkMulticast(inetAddr.getAddress());
- } else {
- security.checkConnect(inetAddr.getAddress().getHostName(),
- inetAddr.getPort());
- }
- }
-
// now try to do the connection at the native level. To be
// compatible for the case when the address is inaddr_any we just
// eat the exception an act as if we are connected at the java level
diff --git a/luni/src/main/java/java/net/DefaultFileNameMap.java b/luni/src/main/java/java/net/DefaultFileNameMap.java
index a502a88..2f254d9 100644
--- a/luni/src/main/java/java/net/DefaultFileNameMap.java
+++ b/luni/src/main/java/java/net/DefaultFileNameMap.java
@@ -16,6 +16,7 @@
package java.net;
+import java.util.Locale;
import libcore.net.MimeUtils;
/**
@@ -36,6 +37,6 @@
if (firstCharInExtension > filename.lastIndexOf('/')) {
ext = filename.substring(firstCharInExtension, lastCharInExtension);
}
- return MimeUtils.guessMimeTypeFromExtension(ext.toLowerCase());
+ return MimeUtils.guessMimeTypeFromExtension(ext.toLowerCase(Locale.US));
}
}
diff --git a/luni/src/main/java/java/net/HttpURLConnection.java b/luni/src/main/java/java/net/HttpURLConnection.java
index 8e33d51c..e42caf1 100644
--- a/luni/src/main/java/java/net/HttpURLConnection.java
+++ b/luni/src/main/java/java/net/HttpURLConnection.java
@@ -293,152 +293,152 @@
/**
* Numeric status code, 202: Accepted
*/
- public final static int HTTP_ACCEPTED = 202;
+ public static final int HTTP_ACCEPTED = 202;
/**
* Numeric status code, 502: Bad Gateway
*/
- public final static int HTTP_BAD_GATEWAY = 502;
+ public static final int HTTP_BAD_GATEWAY = 502;
/**
* Numeric status code, 405: Bad Method
*/
- public final static int HTTP_BAD_METHOD = 405;
+ public static final int HTTP_BAD_METHOD = 405;
/**
* Numeric status code, 400: Bad Request
*/
- public final static int HTTP_BAD_REQUEST = 400;
+ public static final int HTTP_BAD_REQUEST = 400;
/**
* Numeric status code, 408: Client Timeout
*/
- public final static int HTTP_CLIENT_TIMEOUT = 408;
+ public static final int HTTP_CLIENT_TIMEOUT = 408;
/**
* Numeric status code, 409: Conflict
*/
- public final static int HTTP_CONFLICT = 409;
+ public static final int HTTP_CONFLICT = 409;
/**
* Numeric status code, 201: Created
*/
- public final static int HTTP_CREATED = 201;
+ public static final int HTTP_CREATED = 201;
/**
* Numeric status code, 413: Entity too large
*/
- public final static int HTTP_ENTITY_TOO_LARGE = 413;
+ public static final int HTTP_ENTITY_TOO_LARGE = 413;
/**
* Numeric status code, 403: Forbidden
*/
- public final static int HTTP_FORBIDDEN = 403;
+ public static final int HTTP_FORBIDDEN = 403;
/**
* Numeric status code, 504: Gateway timeout
*/
- public final static int HTTP_GATEWAY_TIMEOUT = 504;
+ public static final int HTTP_GATEWAY_TIMEOUT = 504;
/**
* Numeric status code, 410: Gone
*/
- public final static int HTTP_GONE = 410;
+ public static final int HTTP_GONE = 410;
/**
* Numeric status code, 500: Internal error
*/
- public final static int HTTP_INTERNAL_ERROR = 500;
+ public static final int HTTP_INTERNAL_ERROR = 500;
/**
* Numeric status code, 411: Length required
*/
- public final static int HTTP_LENGTH_REQUIRED = 411;
+ public static final int HTTP_LENGTH_REQUIRED = 411;
/**
* Numeric status code, 301 Moved permanently
*/
- public final static int HTTP_MOVED_PERM = 301;
+ public static final int HTTP_MOVED_PERM = 301;
/**
* Numeric status code, 302: Moved temporarily
*/
- public final static int HTTP_MOVED_TEMP = 302;
+ public static final int HTTP_MOVED_TEMP = 302;
/**
* Numeric status code, 300: Multiple choices
*/
- public final static int HTTP_MULT_CHOICE = 300;
+ public static final int HTTP_MULT_CHOICE = 300;
/**
* Numeric status code, 204: No content
*/
- public final static int HTTP_NO_CONTENT = 204;
+ public static final int HTTP_NO_CONTENT = 204;
/**
* Numeric status code, 406: Not acceptable
*/
- public final static int HTTP_NOT_ACCEPTABLE = 406;
+ public static final int HTTP_NOT_ACCEPTABLE = 406;
/**
* Numeric status code, 203: Not authoritative
*/
- public final static int HTTP_NOT_AUTHORITATIVE = 203;
+ public static final int HTTP_NOT_AUTHORITATIVE = 203;
/**
* Numeric status code, 404: Not found
*/
- public final static int HTTP_NOT_FOUND = 404;
+ public static final int HTTP_NOT_FOUND = 404;
/**
* Numeric status code, 501: Not implemented
*/
- public final static int HTTP_NOT_IMPLEMENTED = 501;
+ public static final int HTTP_NOT_IMPLEMENTED = 501;
/**
* Numeric status code, 304: Not modified
*/
- public final static int HTTP_NOT_MODIFIED = 304;
+ public static final int HTTP_NOT_MODIFIED = 304;
/**
* Numeric status code, 200: OK
*/
- public final static int HTTP_OK = 200;
+ public static final int HTTP_OK = 200;
/**
* Numeric status code, 206: Partial
*/
- public final static int HTTP_PARTIAL = 206;
+ public static final int HTTP_PARTIAL = 206;
/**
* Numeric status code, 402: Payment required
*/
- public final static int HTTP_PAYMENT_REQUIRED = 402;
+ public static final int HTTP_PAYMENT_REQUIRED = 402;
/**
* Numeric status code, 412: Precondition failed
*/
- public final static int HTTP_PRECON_FAILED = 412;
+ public static final int HTTP_PRECON_FAILED = 412;
/**
* Numeric status code, 407: Proxy authentication required
*/
- public final static int HTTP_PROXY_AUTH = 407;
+ public static final int HTTP_PROXY_AUTH = 407;
/**
* Numeric status code, 414: Request too long
*/
- public final static int HTTP_REQ_TOO_LONG = 414;
+ public static final int HTTP_REQ_TOO_LONG = 414;
/**
* Numeric status code, 205: Reset
*/
- public final static int HTTP_RESET = 205;
+ public static final int HTTP_RESET = 205;
/**
* Numeric status code, 303: See other
*/
- public final static int HTTP_SEE_OTHER = 303;
+ public static final int HTTP_SEE_OTHER = 303;
/**
* Numeric status code, 500: Internal error
@@ -446,32 +446,32 @@
* @deprecated Use {@link #HTTP_INTERNAL_ERROR}
*/
@Deprecated
- public final static int HTTP_SERVER_ERROR = 500;
+ public static final int HTTP_SERVER_ERROR = 500;
/**
* Numeric status code, 305: Use proxy
*/
- public final static int HTTP_USE_PROXY = 305;
+ public static final int HTTP_USE_PROXY = 305;
/**
* Numeric status code, 401: Unauthorized
*/
- public final static int HTTP_UNAUTHORIZED = 401;
+ public static final int HTTP_UNAUTHORIZED = 401;
/**
* Numeric status code, 415: Unsupported type
*/
- public final static int HTTP_UNSUPPORTED_TYPE = 415;
+ public static final int HTTP_UNSUPPORTED_TYPE = 415;
/**
* Numeric status code, 503: Unavailable
*/
- public final static int HTTP_UNAVAILABLE = 503;
+ public static final int HTTP_UNAVAILABLE = 503;
/**
* Numeric status code, 505: Version not supported
*/
- public final static int HTTP_VERSION = 505;
+ public static final int HTTP_VERSION = 505;
/**
* Constructs a new {@code HttpURLConnection} instance pointing to the
@@ -601,18 +601,12 @@
/**
* Sets the flag of whether this connection will follow redirects returned
- * by the remote server. This method can only be called with the permission
- * from the security manager.
+ * by the remote server.
*
* @param auto
* the value to enable or disable this option.
- * @see SecurityManager#checkSetFactory()
*/
public static void setFollowRedirects(boolean auto) {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkSetFactory();
- }
followRedirects = auto;
}
diff --git a/luni/src/main/java/java/net/Inet6Address.java b/luni/src/main/java/java/net/Inet6Address.java
index 7cd5cee..0880f3f 100644
--- a/luni/src/main/java/java/net/Inet6Address.java
+++ b/luni/src/main/java/java/net/Inet6Address.java
@@ -23,7 +23,6 @@
import java.io.ObjectStreamField;
import java.util.Arrays;
import java.util.Enumeration;
-import libcore.util.EmptyArray;
/**
* An IPv6 address. See {@link InetAddress}.
@@ -376,11 +375,12 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("ipaddress", EmptyArray.BYTE.getClass()),
- new ObjectStreamField("scope_id", Integer.TYPE),
- new ObjectStreamField("scope_id_set", Boolean.TYPE),
- new ObjectStreamField("scope_ifname_set", Boolean.TYPE),
- new ObjectStreamField("ifname", String.class), };
+ new ObjectStreamField("ipaddress", byte[].class),
+ new ObjectStreamField("scope_id", int.class),
+ new ObjectStreamField("scope_id_set", boolean.class),
+ new ObjectStreamField("scope_ifname_set", boolean.class),
+ new ObjectStreamField("ifname", String.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/net/InetAddress.java b/luni/src/main/java/java/net/InetAddress.java
index e4ca164..88d341d 100644
--- a/luni/src/main/java/java/net/InetAddress.java
+++ b/luni/src/main/java/java/net/InetAddress.java
@@ -26,7 +26,6 @@
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;
@@ -34,7 +33,6 @@
import java.util.List;
import org.apache.harmony.luni.platform.OSMemory;
import org.apache.harmony.luni.platform.Platform;
-import org.apache.harmony.luni.util.PriviAction;
/**
* An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and
@@ -273,11 +271,6 @@
return new InetAddress[] { makeInetAddress(bytes, null) };
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkConnect(host, -1);
- }
-
return lookupHostByName(host);
}
@@ -296,8 +289,7 @@
static native byte[] ipStringToByteArray(String address);
static boolean preferIPv6Addresses() {
- String propertyName = "java.net.preferIPv6Addresses";
- String propertyValue = AccessController.doPrivileged(new PriviAction<String>(propertyName));
+ String propertyValue = System.getProperty("java.net.preferIPv6Addresses");
return Boolean.parseBoolean(propertyValue);
}
@@ -353,25 +345,12 @@
} catch (UnknownHostException e) {
return hostName = byteArrayToIpString(ipaddress);
}
- SecurityManager security = System.getSecurityManager();
- try {
- // Only check host names, not addresses
- if (security != null && !isNumeric(hostName)) {
- security.checkConnect(hostName, -1);
- }
- } catch (SecurityException e) {
- return byteArrayToIpString(ipaddress);
- }
return hostName;
}
/**
- * Gets the fully qualified domain name for the host associated with this IP
- * address. If a security manager is set, it is checked if the method caller
- * is allowed to get the hostname. Otherwise, the textual representation in
- * a dotted-quad-notation is returned.
- *
- * @return the fully qualified domain name of this IP address.
+ * Returns the fully qualified domain name for the host associated with this IP
+ * address.
*/
public String getCanonicalHostName() {
String canonicalName;
@@ -387,15 +366,6 @@
} catch (UnknownHostException e) {
return byteArrayToIpString(ipaddress);
}
- SecurityManager security = System.getSecurityManager();
- try {
- // Only check host names, not addresses
- if (security != null && !isNumeric(canonicalName)) {
- security.checkConnect(canonicalName, -1);
- }
- } catch (SecurityException e) {
- return byteArrayToIpString(ipaddress);
- }
return canonicalName;
}
@@ -438,14 +408,6 @@
*/
public static InetAddress getLocalHost() throws UnknownHostException {
String host = gethostname();
- SecurityManager security = System.getSecurityManager();
- try {
- if (security != null) {
- security.checkConnect(host, -1);
- }
- } catch (SecurityException e) {
- return Inet4Address.LOOPBACK;
- }
return lookupHostByName(host)[0];
}
private static native String gethostname();
@@ -529,17 +491,11 @@
*/
private static native String getnameinfo(byte[] addr);
- static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException {
+ static String getHostNameInternal(String host) throws UnknownHostException {
if (host == null || host.isEmpty()) {
return Inet4Address.LOOPBACK.getHostAddress();
}
if (!isNumeric(host)) {
- if (isCheck) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkConnect(host, -1);
- }
- }
return lookupHostByName(host)[0].getHostAddress();
}
return host;
@@ -1019,9 +975,10 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("address", Integer.TYPE),
- new ObjectStreamField("family", Integer.TYPE),
- new ObjectStreamField("hostName", String.class) };
+ new ObjectStreamField("address", int.class),
+ new ObjectStreamField("family", int.class),
+ new ObjectStreamField("hostName", String.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/net/InetSocketAddress.java b/luni/src/main/java/java/net/InetSocketAddress.java
index f9f973b..31b369f 100644
--- a/luni/src/main/java/java/net/InetSocketAddress.java
+++ b/luni/src/main/java/java/net/InetSocketAddress.java
@@ -75,10 +75,6 @@
* the specified port number to which this socket is bound.
* @param host
* the specified hostname to which this socket is bound.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkConnect()} method does not allow the resolving of the
- * host name.
*/
public InetSocketAddress(String host, int port) {
this(host, port, true);
@@ -95,10 +91,6 @@
InetAddress addr = null;
if (needResolved) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkConnect(hostname, port);
- }
try {
addr = InetAddress.getByName(hostname);
hostname = null;
diff --git a/luni/src/main/java/java/net/MulticastSocket.java b/luni/src/main/java/java/net/MulticastSocket.java
index c853dc4..c717a00 100644
--- a/luni/src/main/java/java/net/MulticastSocket.java
+++ b/luni/src/main/java/java/net/MulticastSocket.java
@@ -204,8 +204,6 @@
* received.
* @throws IOException
* if the specified address is not a multicast address.
- * @throws SecurityException
- * if the caller is not authorized to join the group.
* @throws IllegalArgumentException
* if no multicast group is specified.
* @since 1.4
@@ -224,8 +222,6 @@
* if {@code groupAddr} is {@code null}.
* @throws IOException
* if the specified group address is not a multicast address.
- * @throws SecurityException
- * if the caller is not authorized to leave the group.
*/
public void leaveGroup(InetAddress groupAddr) throws IOException {
checkJoinOrLeave(groupAddr);
@@ -242,8 +238,6 @@
* dropped.
* @throws IOException
* if the specified group address is not a multicast address.
- * @throws SecurityException
- * if the caller is not authorized to leave the group.
* @throws IllegalArgumentException
* if {@code groupAddress} is {@code null}.
* @since 1.4
@@ -276,10 +270,6 @@
if (!groupAddr.isMulticastAddress()) {
throw new IOException("Not a multicast group: " + groupAddr);
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkMulticast(groupAddr);
- }
}
private void checkJoinOrLeave(InetAddress groupAddr) throws IOException {
@@ -287,10 +277,6 @@
if (!groupAddr.isMulticastAddress()) {
throw new IOException("Not a multicast group: " + groupAddr);
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkMulticast(groupAddr);
- }
}
/**
@@ -310,14 +296,6 @@
public void send(DatagramPacket pack, byte ttl) throws IOException {
checkClosedAndBind(false);
InetAddress packAddr = pack.getAddress();
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- if (packAddr.isMulticastAddress()) {
- security.checkMulticast(packAddr, ttl);
- } else {
- security.checkConnect(packAddr.getHostName(), pack.getPort());
- }
- }
int currTTL = getTimeToLive();
if (packAddr.isMulticastAddress() && (byte) currTTL != ttl) {
try {
diff --git a/luni/src/main/java/java/net/NetPermission.java b/luni/src/main/java/java/net/NetPermission.java
index cb8bcdd..e12a3bf 100644
--- a/luni/src/main/java/java/net/NetPermission.java
+++ b/luni/src/main/java/java/net/NetPermission.java
@@ -33,7 +33,6 @@
* </dl>
*
* @see java.security.BasicPermission
- * @see SecurityManager
*/
public final class NetPermission extends java.security.BasicPermission {
diff --git a/luni/src/main/java/java/net/NetworkInterface.java b/luni/src/main/java/java/net/NetworkInterface.java
index 70987ea..6ef248f 100644
--- a/luni/src/main/java/java/net/NetworkInterface.java
+++ b/luni/src/main/java/java/net/NetworkInterface.java
@@ -132,21 +132,7 @@
* @return the address list of the represented network interface.
*/
public Enumeration<InetAddress> getInetAddresses() {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null || addresses.isEmpty()) {
- return Collections.enumeration(addresses);
- }
- // TODO: Android should ditch SecurityManager and the associated pollution.
- List<InetAddress> result = new ArrayList<InetAddress>(addresses.size());
- for (InetAddress address : addresses) {
- try {
- sm.checkConnect(address.getHostName(), CHECK_CONNECT_NO_PORT);
- } catch (SecurityException e) {
- continue;
- }
- result.add(address);
- }
- return Collections.enumeration(result);
+ return Collections.enumeration(addresses);
}
/**
@@ -343,31 +329,11 @@
}
/**
- * Returns a List the InterfaceAddresses for this network interface.
- * <p>
- * If there is a security manager, its checkConnect method is called with
- * the InetAddress for each InterfaceAddress. Only InterfaceAddresses where
- * the checkConnect doesn't throw a SecurityException will be returned.
- *
- * @return a List of the InterfaceAddresses for this network interface.
+ * Returns a List of the InterfaceAddresses for this network interface.
* @since 1.6
*/
public List<InterfaceAddress> getInterfaceAddresses() {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null) {
- return Collections.unmodifiableList(interfaceAddresses);
- }
- // TODO: Android should ditch SecurityManager and the associated pollution.
- List<InterfaceAddress> result = new ArrayList<InterfaceAddress>(interfaceAddresses.size());
- for (InterfaceAddress ia : interfaceAddresses) {
- try {
- sm.checkConnect(ia.getAddress().getHostName(), CHECK_CONNECT_NO_PORT);
- } catch (SecurityException e) {
- continue;
- }
- result.add(ia);
- }
- return result;
+ return Collections.unmodifiableList(interfaceAddresses);
}
/**
diff --git a/luni/src/main/java/java/net/ProxySelector.java b/luni/src/main/java/java/net/ProxySelector.java
index 8455274..1166db7 100644
--- a/luni/src/main/java/java/net/ProxySelector.java
+++ b/luni/src/main/java/java/net/ProxySelector.java
@@ -93,37 +93,18 @@
private static ProxySelector defaultSelector = new ProxySelectorImpl();
- private final static NetPermission getProxySelectorPermission
- = new NetPermission("getProxySelector");
- private final static NetPermission setProxySelectorPermission
- = new NetPermission("setProxySelector");
-
/**
* Returns the default proxy selector, or null if none exists.
- *
- * @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 (sm != null) {
- sm.checkPermission(getProxySelectorPermission);
- }
return defaultSelector;
}
/**
* Sets the default proxy selector. If {@code selector} is null, the current
* proxy selector will be removed.
- *
- * @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 (sm != null) {
- sm.checkPermission(setProxySelectorPermission);
- }
defaultSelector = selector;
}
diff --git a/luni/src/main/java/java/net/ResponseCache.java b/luni/src/main/java/java/net/ResponseCache.java
index 5eeb551..cbb4f0f 100644
--- a/luni/src/main/java/java/net/ResponseCache.java
+++ b/luni/src/main/java/java/net/ResponseCache.java
@@ -35,10 +35,6 @@
* Returns the system's default response cache, or null.
*/
public static ResponseCache getDefault() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new NetPermission("getResponseCache"));
- }
return defaultResponseCache;
}
@@ -46,10 +42,6 @@
* Sets the system's default response cache. Use null to remove the response cache.
*/
public static void setDefault(ResponseCache responseCache) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new NetPermission("setResponseCache"));
- }
defaultResponseCache = responseCache;
}
diff --git a/luni/src/main/java/java/net/ServerSocket.java b/luni/src/main/java/java/net/ServerSocket.java
index edce448..3850c34 100644
--- a/luni/src/main/java/java/net/ServerSocket.java
+++ b/luni/src/main/java/java/net/ServerSocket.java
@@ -148,9 +148,6 @@
Socket aSocket = new Socket();
try {
implAccept(aSocket);
- } catch (SecurityException e) {
- aSocket.close();
- throw e;
} catch (IOException e) {
aSocket.close();
throw e;
@@ -158,22 +155,10 @@
return aSocket;
}
- /**
- * Checks whether the server may listen for connection requests on {@code
- * aport}. Throws an exception if the port is outside the valid range
- * {@code 0 <= aport <= 65535 }or does not satisfy the security policy.
- *
- * @param aPort
- * the candidate port to listen on.
- */
- void checkListen(int aPort) {
+ private void checkListen(int aPort) {
if (aPort < 0 || aPort > 65535) {
throw new IllegalArgumentException("Port out of range: " + aPort);
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkListen(aPort);
- }
}
/**
@@ -264,11 +249,6 @@
impl.accept(aSocket.impl);
aSocket.accepted();
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkAccept(aSocket.getInetAddress().getHostAddress(),
- aSocket.getPort());
- }
}
/**
@@ -284,10 +264,6 @@
*/
public static synchronized void setSocketFactory(SocketImplFactory aFactory)
throws IOException {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkSetFactory();
- }
if (factory != null) {
throw new SocketException("Factory already set");
}
@@ -384,10 +360,6 @@
}
port = inetAddr.getPort();
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkListen(port);
- }
synchronized (this) {
try {
diff --git a/luni/src/main/java/java/net/Socket.java b/luni/src/main/java/java/net/Socket.java
index 39abdbe..c9b3b34 100644
--- a/luni/src/main/java/java/net/Socket.java
+++ b/luni/src/main/java/java/net/Socket.java
@@ -73,9 +73,6 @@
* @throws IllegalArgumentException
* if the argument {@code proxy} is {@code null} or of an
* invalid type.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given proxy.
* @see SocketImplFactory
* @see SocketImpl
*/
@@ -94,7 +91,6 @@
host = address.getHostName();
}
int port = address.getPort();
- checkConnectPermission(host, port);
}
this.impl = factory != null ? factory.createSocketImpl() : new PlainSocketImpl(proxy);
}
@@ -117,9 +113,6 @@
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
*/
private void tryAllAddresses(String dstName, int dstPort, InetAddress
localAddress, int localPort, boolean streaming) throws IOException {
@@ -134,8 +127,7 @@
checkDestination(dstAddress, dstPort);
startupSocket(dstAddress, dstPort, localAddress, localPort, streaming);
return;
- } catch (SecurityException e1) {
- } catch (IOException e2) {
+ } catch (IOException ex) {
}
}
@@ -163,9 +155,6 @@
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
*/
public Socket(String dstName, int dstPort) throws UnknownHostException, IOException {
this(dstName, dstPort, null, 0);
@@ -195,9 +184,6 @@
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
*/
public Socket(String dstName, int dstPort, InetAddress localAddress, int localPort) throws IOException {
this();
@@ -224,9 +210,6 @@
* if the host name could not be resolved into an IP address.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
* @deprecated Use {@code Socket(String, int)} instead of this for streaming
* sockets or an appropriate constructor of {@code
* DatagramSocket} for UDP transport.
@@ -248,9 +231,6 @@
* the port on the target host to connect to.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
*/
public Socket(InetAddress dstAddress, int dstPort) throws IOException {
this();
@@ -274,9 +254,6 @@
* the port on the local host to bind to.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
*/
public Socket(InetAddress dstAddress, int dstPort,
InetAddress localAddress, int localPort) throws IOException {
@@ -299,9 +276,6 @@
* socket otherwise.
* @throws IOException
* if an error occurs while creating the socket.
- * @throws SecurityException
- * if a security manager exists and it denies the permission to
- * connect to the given address and port.
* @deprecated Use {@code Socket(InetAddress, int)} instead of this for
* streaming sockets or an appropriate constructor of {@code
* DatagramSocket} for UDP transport.
@@ -339,22 +313,6 @@
if (dstPort < 0 || dstPort > 65535) {
throw new IllegalArgumentException("Port out of range: " + dstPort);
}
- checkConnectPermission(destAddr.getHostAddress(), dstPort);
- }
-
- /**
- * Checks whether the connection destination satisfies the security policy.
- *
- * @param hostname
- * the destination hostname.
- * @param dstPort
- * the port on the destination host.
- */
- private void checkConnectPermission(String hostname, int dstPort) {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkConnect(hostname, dstPort);
- }
}
/**
@@ -519,10 +477,6 @@
*/
public static synchronized void setSocketImplFactory(SocketImplFactory fac)
throws IOException {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkSetFactory();
- }
if (factory != null) {
throw new SocketException("Factory already set");
}
diff --git a/luni/src/main/java/java/net/SocketImpl.java b/luni/src/main/java/java/net/SocketImpl.java
index e3d9c04..1031f08 100644
--- a/luni/src/main/java/java/net/SocketImpl.java
+++ b/luni/src/main/java/java/net/SocketImpl.java
@@ -212,12 +212,10 @@
*
* @return the textual representation of this socket.
*/
- @SuppressWarnings("nls")
@Override
public String toString() {
- return new StringBuilder(100).append("Socket[addr=").append(
- getInetAddress()).append(",port=").append(port).append(
- ",localport=").append(getLocalPort()).append("]").toString();
+ return "Socket[address=" + getInetAddress() +
+ ",port=" + port + ",localPort=" + getLocalPort() + "]";
}
/**
diff --git a/luni/src/main/java/java/net/SocketPermission.java b/luni/src/main/java/java/net/SocketPermission.java
index a4dd942..c63872e 100644
--- a/luni/src/main/java/java/net/SocketPermission.java
+++ b/luni/src/main/java/java/net/SocketPermission.java
@@ -23,6 +23,7 @@
import java.io.Serializable;
import java.security.Permission;
import java.security.PermissionCollection;
+import java.util.Locale;
/**
* Regulates the access to network operations available through sockets through
@@ -74,7 +75,6 @@
// list of actions permitted for socket permission in order, indexed by mask
// value
- @SuppressWarnings("nls")
private static final String[] actionNames = { "", "connect", "listen", "",
"accept", "", "", "", "resolve" };
@@ -219,7 +219,7 @@
if (pos == length) {
parsing = false;
}
- action = sb.toString().trim().toLowerCase();
+ action = sb.toString().trim().toLowerCase(Locale.US);
if (action.equals(actionNames[SP_CONNECT])) {
actionsMask |= SP_CONNECT;
} else if (action.equals(actionNames[SP_LISTEN])) {
@@ -376,7 +376,7 @@
private String getIPString(boolean isCheck) {
if (!resolved) {
try {
- ipString = InetAddress.getHostNameInternal(hostName, isCheck);
+ ipString = InetAddress.getHostNameInternal(hostName);
} catch (UnknownHostException e) {
// ignore
}
@@ -415,7 +415,7 @@
if (idx > -1) {
host = host.substring(0, idx);
}
- return host.toLowerCase();
+ return host.toLowerCase(Locale.US);
}
int lastIdx = host.lastIndexOf(':');
@@ -425,7 +425,7 @@
// only one colon, should be port
host = host.substring(0, idx);
}
- return host.toLowerCase();
+ return host.toLowerCase(Locale.US);
}
// maybe IPv6
boolean isFirstBracket = (host.charAt(0) == '[');
@@ -442,7 +442,7 @@
host = host.substring(0, lastIdx);
}
if (isIP6AddressInFullForm(host)) {
- return host.toLowerCase();
+ return host.toLowerCase(Locale.US);
}
throw new IllegalArgumentException("Invalid port number: " + host);
}
@@ -454,7 +454,7 @@
}
host = host.substring(0, bbracketIdx + 1);
if (isValidIP6Address(host)) {
- return host.toLowerCase();
+ return host.toLowerCase(Locale.US);
}
throw new IllegalArgumentException("Invalid port number: " + host);
}
diff --git a/luni/src/main/java/java/net/URI.java b/luni/src/main/java/java/net/URI.java
index da68970..0001236 100644
--- a/luni/src/main/java/java/net/URI.java
+++ b/luni/src/main/java/java/net/URI.java
@@ -21,10 +21,8 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
-import java.io.UnsupportedEncodingException;
-import java.util.StringTokenizer;
-import org.apache.harmony.luni.platform.INetworkSystem;
-import org.apache.harmony.luni.platform.Platform;
+import java.util.Locale;
+import libcore.net.UriCodec;
/**
* This class represents an instance of a URI as defined by RFC 2396.
@@ -35,9 +33,47 @@
static final String UNRESERVED = "_-!.~\'()*";
static final String PUNCTUATION = ",;:$&+=";
- static final String RESERVED = PUNCTUATION + "?/[]@";
- static final String SOME_LEGAL = UNRESERVED + PUNCTUATION;
- static final String ALL_LEGAL = UNRESERVED + RESERVED;
+
+ static final UriCodec USER_INFO_ENCODER = new PartEncoder("");
+ static final UriCodec PATH_ENCODER = new PartEncoder("/@");
+ static final UriCodec AUTHORITY_ENCODER = new PartEncoder("@[]");
+
+ /** for java.net.URL, which foolishly combines these two parts */
+ static final UriCodec FILE_AND_QUERY_ENCODER = new PartEncoder("/@?");
+
+ /** for query, fragment, and scheme-specific part */
+ static final UriCodec ALL_LEGAL_ENCODER = new PartEncoder("?/[]@");
+
+ /** Retains all ASCII chars including delimiters. */
+ private static final UriCodec ASCII_ONLY = new UriCodec() {
+ @Override protected boolean isRetained(char c) {
+ return c <= 127;
+ }
+ };
+
+ /**
+ * Encodes the unescaped characters of {@code s} that are not permitted.
+ * Permitted characters are:
+ * <ul>
+ * <li>Unreserved characters in RFC 2396.
+ * <li>{@code extraOkayChars},
+ * <li>non-ASCII, non-control, non-whitespace characters
+ * </ul>
+ */
+ private static class PartEncoder extends UriCodec {
+ private final String extraLegalCharacters;
+
+ PartEncoder(String extraLegalCharacters) {
+ this.extraLegalCharacters = extraLegalCharacters;
+ }
+
+ @Override protected boolean isRetained(char c) {
+ return UNRESERVED.indexOf(c) != -1
+ || PUNCTUATION.indexOf(c) != -1
+ || extraLegalCharacters.indexOf(c) != -1
+ || (c > 127 && !Character.isSpaceChar(c) && !Character.isISOControl(c));
+ }
+ }
private String string;
private transient String scheme;
@@ -95,13 +131,11 @@
uri.append(':');
}
if (ssp != null) {
- // QUOTE ILLEGAL CHARACTERS
- uri.append(quoteComponent(ssp, ALL_LEGAL));
+ ALL_LEGAL_ENCODER.appendEncoded(uri, ssp);
}
if (frag != null) {
uri.append('#');
- // QUOTE ILLEGAL CHARACTERS
- uri.append(quoteComponent(frag, ALL_LEGAL));
+ ALL_LEGAL_ENCODER.appendEncoded(uri, frag);
}
parseURI(uri.toString(), false);
@@ -160,8 +194,7 @@
}
if (userInfo != null) {
- // QUOTE ILLEGAL CHARACTERS in userInfo
- uri.append(quoteComponent(userInfo, SOME_LEGAL));
+ USER_INFO_ENCODER.appendEncoded(uri, userInfo);
uri.append('@');
}
@@ -181,20 +214,17 @@
}
if (path != null) {
- // QUOTE ILLEGAL CHARS
- uri.append(quoteComponent(path, "/@" + SOME_LEGAL));
+ PATH_ENCODER.appendEncoded(uri, path);
}
if (query != null) {
uri.append('?');
- // QUOTE ILLEGAL CHARS
- uri.append(quoteComponent(query, ALL_LEGAL));
+ ALL_LEGAL_ENCODER.appendEncoded(uri, query);
}
if (fragment != null) {
- // QUOTE ILLEGAL CHARS
uri.append('#');
- uri.append(quoteComponent(fragment, ALL_LEGAL));
+ ALL_LEGAL_ENCODER.appendEncoded(uri, fragment);
}
parseURI(uri.toString(), true);
@@ -260,23 +290,19 @@
}
if (authority != null) {
uri.append("//");
- // QUOTE ILLEGAL CHARS
- uri.append(quoteComponent(authority, "@[]" + SOME_LEGAL));
+ AUTHORITY_ENCODER.appendEncoded(uri, authority);
}
if (path != null) {
- // QUOTE ILLEGAL CHARS
- uri.append(quoteComponent(path, "/@" + SOME_LEGAL));
+ PATH_ENCODER.appendEncoded(uri, path);
}
if (query != null) {
- // QUOTE ILLEGAL CHARS
uri.append('?');
- uri.append(quoteComponent(query, ALL_LEGAL));
+ ALL_LEGAL_ENCODER.appendEncoded(uri, query);
}
if (fragment != null) {
- // QUOTE ILLEGAL CHARS
uri.append('#');
- uri.append(quoteComponent(fragment, ALL_LEGAL));
+ ALL_LEGAL_ENCODER.appendEncoded(uri, fragment);
}
parseURI(uri.toString(), false);
@@ -390,7 +416,7 @@
}
try {
- URIEncoderDecoder.validateSimple(scheme, "+-.");
+ UriCodec.validateSimple(scheme, "+-.");
} catch (URISyntaxException e) {
throw new URISyntaxException(uri, "Illegal character in scheme", index + e.getIndex());
}
@@ -399,7 +425,7 @@
private void validateSsp(String uri, String ssp, int index)
throws URISyntaxException {
try {
- URIEncoderDecoder.validate(ssp, ALL_LEGAL);
+ ALL_LEGAL_ENCODER.validate(ssp);
} catch (URISyntaxException e) {
throw new URISyntaxException(uri,
e.getReason() + " in schemeSpecificPart", index + e.getIndex());
@@ -409,7 +435,7 @@
private void validateAuthority(String uri, String authority, int index)
throws URISyntaxException {
try {
- URIEncoderDecoder.validate(authority, "@[]" + SOME_LEGAL);
+ AUTHORITY_ENCODER.validate(authority);
} catch (URISyntaxException e) {
throw new URISyntaxException(uri, e.getReason() + " in authority", index + e.getIndex());
}
@@ -418,7 +444,7 @@
private void validatePath(String uri, String path, int index)
throws URISyntaxException {
try {
- URIEncoderDecoder.validate(path, "/@" + SOME_LEGAL);
+ PATH_ENCODER.validate(path);
} catch (URISyntaxException e) {
throw new URISyntaxException(uri, e.getReason() + " in path", index + e.getIndex());
}
@@ -427,7 +453,7 @@
private void validateQuery(String uri, String query, int index)
throws URISyntaxException {
try {
- URIEncoderDecoder.validate(query, ALL_LEGAL);
+ ALL_LEGAL_ENCODER.validate(query);
} catch (URISyntaxException e) {
throw new URISyntaxException(uri, e.getReason() + " in query", index + e.getIndex());
@@ -437,7 +463,7 @@
private void validateFragment(String uri, String fragment, int index)
throws URISyntaxException {
try {
- URIEncoderDecoder.validate(fragment, ALL_LEGAL);
+ ALL_LEGAL_ENCODER.validate(fragment);
} catch (URISyntaxException e) {
throw new URISyntaxException(uri, e.getReason() + " in fragment", index + e.getIndex());
}
@@ -588,15 +614,14 @@
private boolean isValidDomainName(String host) {
try {
- URIEncoderDecoder.validateSimple(host, "-.");
+ UriCodec.validateSimple(host, "-.");
} catch (URISyntaxException e) {
return false;
}
String lastLabel = null;
- StringTokenizer st = new StringTokenizer(host, ".");
- while (st.hasMoreTokens()) {
- lastLabel = st.nextToken();
+ for (String token : host.split("\\.")) {
+ lastLabel = token;
if (lastLabel.startsWith("-") || lastLabel.endsWith("-")) {
return false;
}
@@ -616,27 +641,6 @@
}
/**
- * Quote illegal chars for each component, but not the others
- *
- * @param component java.lang.String the component to be converted
- * @param legalSet the legal character set allowed in the component
- * @return java.lang.String the converted string
- */
- private String quoteComponent(String component, String legalSet) {
- try {
- /*
- * Use a different encoder than URLEncoder since: 1. chars like "/",
- * "#", "@" etc needs to be preserved instead of being encoded, 2.
- * UTF-8 char set needs to be used for encoding instead of default
- * platform one
- */
- return URIEncoderDecoder.quoteIllegal(component, legalSet);
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e.toString());
- }
- }
-
- /**
* Compares this URI with the given argument {@code uri}. This method will
* return a negative value if this URI instance is less than the given
* argument and a positive value if this URI instance is greater than the
@@ -800,7 +804,7 @@
int index, prevIndex = 0;
while ((index = s.indexOf('%', prevIndex)) != -1) {
result.append(s.substring(prevIndex, index + 1));
- result.append(s.substring(index + 1, index + 3).toLowerCase());
+ result.append(s.substring(index + 1, index + 3).toLowerCase(Locale.US));
index += 3;
prevIndex = index;
}
@@ -1399,36 +1403,8 @@
return resolve(create(relative));
}
- /**
- * Encode unicode chars that are not part of US-ASCII char set into the
- * escaped form
- *
- * i.e. The Euro currency symbol is encoded as "%E2%82%AC".
- */
- private String encodeNonAscii(String s) {
- try {
- /*
- * Use a different encoder than URLEncoder since: 1. chars like "/",
- * "#", "@" etc needs to be preserved instead of being encoded, 2.
- * UTF-8 char set needs to be used for encoding instead of default
- * platform one 3. Only other chars need to be converted
- */
- return URIEncoderDecoder.encodeOthers(s);
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e.toString());
- }
- }
-
private String decode(String s) {
- if (s == null) {
- return s;
- }
-
- try {
- return URIEncoderDecoder.decode(s);
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e.toString());
- }
+ return s != null ? UriCodec.decode(s) : null;
}
/**
@@ -1438,7 +1414,9 @@
* @return the US-ASCII string representation of this URI.
*/
public String toASCIIString() {
- return encodeNonAscii(toString());
+ StringBuilder result = new StringBuilder();
+ ASCII_ONLY.appendEncoded(result, toString());
+ return result.toString();
}
/**
@@ -1490,7 +1468,7 @@
private String getHashString() {
StringBuilder result = new StringBuilder();
if (scheme != null) {
- result.append(scheme.toLowerCase());
+ result.append(scheme.toLowerCase(Locale.US));
result.append(':');
}
if (opaque) {
@@ -1504,7 +1482,7 @@
if (userInfo != null) {
result.append(userInfo + "@");
}
- result.append(host.toLowerCase());
+ result.append(host.toLowerCase(Locale.US));
if (port != -1) {
result.append(":" + port);
}
diff --git a/luni/src/main/java/java/net/URIEncoderDecoder.java b/luni/src/main/java/java/net/URIEncoderDecoder.java
deleted file mode 100644
index bccef8c..0000000
--- a/luni/src/main/java/java/net/URIEncoderDecoder.java
+++ /dev/null
@@ -1,210 +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.net;
-
-import java.io.ByteArrayOutputStream;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charsets;
-
-/**
- * This class is used to encode a string using the format required by {@code
- * application/x-www-form-urlencoded} MIME content type. It contains helper
- * methods used by the URI class, and performs encoding and decoding in a
- * slightly different way than {@code URLEncoder} and {@code URLDecoder}.
- */
-class URIEncoderDecoder {
-
- static final String digits = "0123456789ABCDEF";
-
- /**
- * Validate a string by checking if it contains any characters other than:
- * 1. letters ('a'..'z', 'A'..'Z') 2. numbers ('0'..'9') 3. characters in
- * the legalset parameter 4. others (unicode characters that are not in
- * US-ASCII set, and are not ISO Control or are not ISO Space characters)
- * <p>
- * called from {@code URI.Helper.parseURI()} to validate each component
- *
- * @param s
- * {@code java.lang.String} the string to be validated
- * @param legal
- * {@code java.lang.String} the characters allowed in the String
- * s
- */
- static void validate(String s, String legal) throws URISyntaxException {
- for (int i = 0; i < s.length();) {
- char ch = s.charAt(i);
- if (ch == '%') {
- do {
- if (i + 2 >= s.length()) {
- throw new URISyntaxException(s, "Incomplete % sequence", i);
- }
- int d1 = Character.digit(s.charAt(i + 1), 16);
- int d2 = Character.digit(s.charAt(i + 2), 16);
- if (d1 == -1 || d2 == -1) {
- throw new URISyntaxException(s, "Invalid % sequence: " +
- s.substring(i, i + 3), i);
- }
-
- i += 3;
- } while (i < s.length() && s.charAt(i) == '%');
-
- continue;
- }
- if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
- || (ch >= '0' && ch <= '9') || legal.indexOf(ch) > -1 || (ch > 127
- && !Character.isSpaceChar(ch) && !Character
- .isISOControl(ch)))) {
- throw new URISyntaxException(s, "Illegal character", i);
- }
- i++;
- }
- }
-
- static void validateSimple(String s, String legal)
- throws URISyntaxException {
- for (int i = 0; i < s.length();) {
- char ch = s.charAt(i);
- if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
- || (ch >= '0' && ch <= '9') || legal.indexOf(ch) > -1)) {
- throw new URISyntaxException(s, "Illegal character", i);
- }
- i++;
- }
- }
-
- /**
- * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
- * and legal characters are converted into their hexidecimal value prepended
- * by '%'.
- * <p>
- * For example: '#' -> %23
- * Other characters, which are unicode chars that are not US-ASCII, and are
- * not ISO Control or are not ISO Space chars, are preserved.
- * <p>
- * Called from {@code URI.quoteComponent()} (for multiple argument
- * constructors)
- *
- * @param s
- * java.lang.String the string to be converted
- * @param legal
- * java.lang.String the characters allowed to be preserved in the
- * string s
- * @return java.lang.String the converted string
- */
- static String quoteIllegal(String s, String legal)
- throws UnsupportedEncodingException {
- StringBuilder buf = new StringBuilder();
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if ((ch >= 'a' && ch <= 'z')
- || (ch >= 'A' && ch <= 'Z')
- || (ch >= '0' && ch <= '9')
- || legal.indexOf(ch) > -1
- || (ch > 127 && !Character.isSpaceChar(ch) && !Character
- .isISOControl(ch))) {
- buf.append(ch);
- } else {
- byte[] bytes = new String(new char[] { ch }).getBytes(Charsets.UTF_8);
- for (int j = 0; j < bytes.length; j++) {
- buf.append('%');
- buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
- buf.append(digits.charAt(bytes[j] & 0xf));
- }
- }
- }
- return buf.toString();
- }
-
- /**
- * Other characters, which are Unicode chars that are not US-ASCII, and are
- * not ISO Control or are not ISO Space chars are not preserved. They are
- * converted into their hexidecimal value prepended by '%'.
- * <p>
- * For example: Euro currency symbol -> "%E2%82%AC".
- * <p>
- * Called from URI.toASCIIString()
- *
- * @param s
- * java.lang.String the string to be converted
- * @return java.lang.String the converted string
- */
- static String encodeOthers(String s) throws UnsupportedEncodingException {
- StringBuilder buf = new StringBuilder();
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if (ch <= 127) {
- buf.append(ch);
- } else {
- byte[] bytes = new String(new char[] { ch }).getBytes(Charsets.UTF_8);
- for (int j = 0; j < bytes.length; j++) {
- buf.append('%');
- buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
- buf.append(digits.charAt(bytes[j] & 0xf));
- }
- }
- }
- return buf.toString();
- }
-
- /**
- * Decodes the string argument which is assumed to be encoded in the {@code
- * x-www-form-urlencoded} MIME content type using the UTF-8 encoding scheme.
- * <p>
- *'%' and two following hex digit characters are converted to the
- * equivalent byte value. All other characters are passed through
- * unmodified.
- * <p>
- * e.g. "A%20B%20C %24%25" -> "A B C $%"
- * <p>
- * Called from URI.getXYZ() methods
- *
- * @param s
- * java.lang.String The encoded string.
- * @return java.lang.String The decoded version.
- */
- static String decode(String s) throws UnsupportedEncodingException {
-
- StringBuilder result = new StringBuilder();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for (int i = 0; i < s.length();) {
- char c = s.charAt(i);
- if (c == '%') {
- out.reset();
- do {
- if (i + 2 >= s.length()) {
- throw new IllegalArgumentException("Incomplete % sequence at: " + i);
- }
- int d1 = Character.digit(s.charAt(i + 1), 16);
- int d2 = Character.digit(s.charAt(i + 2), 16);
- if (d1 == -1 || d2 == -1) {
- throw new IllegalArgumentException("Invalid % sequence " +
- s.substring(i, i + 3) + " at " + i);
- }
- out.write((byte) ((d1 << 4) + d2));
- i += 3;
- } while (i < s.length() && s.charAt(i) == '%');
- result.append(out.toString("UTF-8"));
- continue;
- }
- result.append(c);
- i++;
- }
- return result.toString();
- }
-
-}
diff --git a/luni/src/main/java/java/net/URL.java b/luni/src/main/java/java/net/URL.java
index 947762b..ebe9950 100644
--- a/luni/src/main/java/java/net/URL.java
+++ b/luni/src/main/java/java/net/URL.java
@@ -20,11 +20,8 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
-import java.security.AccessController;
import java.util.Hashtable;
-import java.util.StringTokenizer;
-import org.apache.harmony.luni.util.PriviAction;
-import org.apache.harmony.luni.util.Util;
+import java.util.Locale;
/**
* A URL instance specifies the location of a resource on the internet as
@@ -136,10 +133,6 @@
if (streamHandlerFactory != null) {
throw new Error("Factory already set");
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSetFactory();
- }
streamHandlers.clear();
streamHandlerFactory = streamFactory;
}
@@ -195,13 +188,8 @@
* if the given string {@code spec} could not be parsed as a URL
* or an invalid protocol has been found.
*/
- public URL(URL context, String spec, URLStreamHandler handler)
- throws MalformedURLException {
+ public URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException {
if (handler != null) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(specifyStreamHandlerPermission);
- }
strmHandler = handler;
}
@@ -241,9 +229,8 @@
protocol = null;
index = -1;
} else {
- // Ignore case in protocol names.
- // Scheme is defined by ASCII characters.
- protocol = Util.toASCIILowerCase(protocol);
+ // Ignore case in protocol names. Scheme is defined by ASCII characters.
+ protocol = protocol.toLowerCase(Locale.US);
}
}
}
@@ -367,10 +354,6 @@
* @throws MalformedURLException
* if the combination of all arguments do not represent a valid
* URL or the protocol is invalid.
- * @throws SecurityException
- * if {@code handler} is non-{@code null}, and a security
- * manager is installed that disallows user-defined protocol
- * handlers.
*/
public URL(String protocol, String host, int port, String file,
URLStreamHandler handler) throws MalformedURLException {
@@ -411,10 +394,6 @@
throw new MalformedURLException("Unknown protocol: " + protocol);
}
} else {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(specifyStreamHandlerPermission);
- }
strmHandler = handler;
}
}
@@ -474,21 +453,34 @@
}
/**
- * Compares this URL instance with the given argument {@code o} and
- * determines if both are equal. Two URL instances are equal if all single
- * parts are identical in their meaning. Compares the argument to the
- * receiver, and returns true if they represent the same URL. Two URLs are
- * equal if they have the same file, host, port, protocol, and reference
- * components.
+ * Returns true if this URL equals {@code o}. URLs are equal if they have
+ * the same protocol, host, port, file, and reference.
*
- * @param o
- * the URL this instance has to be compared with.
- * @return {@code true} if both instances represents the same URL, {@code
- * false} otherwise.
- * @see #hashCode()
+ * <h3>Network I/O Warning</h3>
+ * <p>Some implementations of URL.equals() resolve host names over the
+ * network. This is problematic:
+ * <ul>
+ * <li><strong>The network may be slow.</strong> Many classes, including
+ * core collections like {@link java.util.Map Map} and {@link java.util.Set
+ * Set} expect that {@code equals} and {@code hashCode} will return quickly.
+ * By violating this assumption, this method posed potential performance
+ * problems.
+ * <li><strong>Equal IP addresses do not imply equal content.</strong>
+ * Virtual hosting permits unrelated sites to share an IP address. This
+ * method could report two otherwise unrelated URLs to be equal because
+ * they're hosted on the same server.</li>
+ * <li><strong>The network many not be available.</strong> Two URLs could be
+ * equal when a network is available and unequal otherwise.</li>
+ * <li><strong>The network may change.</strong> The IP address for a given
+ * host name varies by network and over time. This is problematic for mobile
+ * devices. Two URLs could be equal on some networks and unequal on
+ * others.</li>
+ * </ul>
+ * <p>This problem is fixed in Android in the Ice Cream Sandwich release. In
+ * that release, URLs are only equal if their host names are equal (ignoring
+ * case).
*/
- @Override
- public boolean equals(Object o) {
+ @Override public boolean equals(Object o) {
if (o == null) {
return false;
}
@@ -557,18 +549,13 @@
// Check if there is a list of packages which can provide handlers.
// If so, then walk this list looking for an applicable one.
- String packageList = AccessController
- .doPrivileged(new PriviAction<String>(
- "java.protocol.handler.pkgs"));
+ String packageList = System.getProperty("java.protocol.handler.pkgs");
if (packageList != null) {
- StringTokenizer st = new StringTokenizer(packageList, "|");
- while (st.hasMoreTokens()) {
- String className = st.nextToken() + "." + protocol + ".Handler";
-
+ for (String packageName : packageList.split("\\|")) {
+ String className = packageName + "." + protocol + ".Handler";
try {
- strmHandler = (URLStreamHandler) Class.forName(className,
- true, ClassLoader.getSystemClassLoader())
- .newInstance();
+ Class<?> klass = Class.forName(className, true, ClassLoader.getSystemClassLoader());
+ strmHandler = (URLStreamHandler) klass.newInstance();
if (strmHandler != null) {
streamHandlers.put(protocol, strmHandler);
}
@@ -692,9 +679,6 @@
* connection to this URL.
* @throws IOException
* if an I/O error occurs while opening the connection.
- * @throws SecurityException
- * if a security manager is installed and it denies to connect
- * to the proxy.
* @throws IllegalArgumentException
* if the argument proxy is {@code null} or is an invalid type.
* @throws UnsupportedOperationException
@@ -705,15 +689,6 @@
if (proxy == null) {
throw new IllegalArgumentException("proxy == null");
}
-
- SecurityManager sm = System.getSecurityManager();
- if (sm != null && proxy.type() != Proxy.Type.DIRECT) {
- InetSocketAddress pAddress = (InetSocketAddress) proxy.address();
- String pHostName = pAddress.isUnresolved() ? pAddress.getHostName()
- : pAddress.getAddress().getHostAddress();
- sm.checkConnect(pHostName, pAddress.getPort());
- }
-
return strmHandler.openConnection(this, proxy);
}
diff --git a/luni/src/main/java/java/net/URLClassLoader.java b/luni/src/main/java/java/net/URLClassLoader.java
index 6929834..1bf2777 100644
--- a/luni/src/main/java/java/net/URLClassLoader.java
+++ b/luni/src/main/java/java/net/URLClassLoader.java
@@ -27,11 +27,8 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
-import java.security.AccessControlContext;
-import java.security.AccessController;
import java.security.CodeSource;
import java.security.PermissionCollection;
-import java.security.PrivilegedAction;
import java.security.SecureClassLoader;
import java.security.cert.Certificate;
import java.util.ArrayList;
@@ -63,53 +60,6 @@
private URLStreamHandlerFactory factory;
- private AccessControlContext currentContext;
-
- static class SubURLClassLoader extends URLClassLoader {
- // The subclass that overwrites the loadClass() method
- private boolean checkingPackageAccess = false;
-
- SubURLClassLoader(URL[] urls) {
- super(urls, ClassLoader.getSystemClassLoader());
- }
-
- SubURLClassLoader(URL[] urls, ClassLoader parent) {
- super(urls, parent);
- }
-
- /**
- * Overrides the {@code loadClass()} of {@code ClassLoader}. It calls
- * the security manager's {@code checkPackageAccess()} before
- * attempting to load the class.
- *
- * @return the Class object.
- * @param className
- * String the name of the class to search for.
- * @param resolveClass
- * boolean indicates if class should be resolved after
- * loading.
- * @throws ClassNotFoundException
- * If the class could not be found.
- */
- @Override
- protected synchronized Class<?> loadClass(String className,
- boolean resolveClass) throws ClassNotFoundException {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null && !checkingPackageAccess) {
- int index = className.lastIndexOf('.');
- if (index > 0) { // skip if class is from a default package
- try {
- checkingPackageAccess = true;
- sm.checkPackageAccess(className.substring(0, index));
- } finally {
- checkingPackageAccess = false;
- }
- }
- }
- return super.loadClass(className, resolveClass);
- }
- }
-
static class IndexFile {
private HashMap<String, ArrayList<URL>> map;
@@ -274,13 +224,12 @@
URL targetURL(URL base, String name) {
try {
- String file = base.getFile() + URIEncoderDecoder.quoteIllegal(name,
- "/@" + URI.SOME_LEGAL);
+ StringBuilder fileBuilder = new StringBuilder();
+ fileBuilder.append(base.getFile());
+ URI.PATH_ENCODER.appendEncoded(fileBuilder, name);
+ String file = fileBuilder.toString();
- return new URL(base.getProtocol(), base.getHost(), base.getPort(),
- file, null);
- } catch (UnsupportedEncodingException e) {
- return null;
+ return new URL(base.getProtocol(), base.getHost(), base.getPort(), file, null);
} catch (MalformedURLException e) {
return null;
}
@@ -590,10 +539,6 @@
* @param urls
* the list of URLs where a specific class or file could be
* found.
- * @throws SecurityException
- * if a security manager exists and its {@code
- * checkCreateClassLoader()} method doesn't allow creation of
- * new ClassLoaders.
*/
public URLClassLoader(URL[] urls) {
this(urls, ClassLoader.getSystemClassLoader(), null);
@@ -609,10 +554,6 @@
* found.
* @param parent
* the class loader to assign as this loader's parent.
- * @throws SecurityException
- * if a security manager exists and its {@code
- * checkCreateClassLoader()} method doesn't allow creation of
- * new class loaders.
*/
public URLClassLoader(URL[] urls, ClassLoader parent) {
this(urls, parent, null);
@@ -646,33 +587,7 @@
if (name == null) {
return null;
}
- ArrayList<URL> result = AccessController.doPrivileged(
- new PrivilegedAction<ArrayList<URL>>() {
- public ArrayList<URL> run() {
- ArrayList<URL> results = new ArrayList<URL>();
- findResourcesImpl(name, results);
- return results;
- }
- }, currentContext);
- SecurityManager sm;
- int length = result.size();
- if (length > 0 && (sm = System.getSecurityManager()) != null) {
- ArrayList<URL> reduced = new ArrayList<URL>(length);
- for (int i = 0; i < length; i++) {
- URL url = result.get(i);
- try {
- sm.checkPermission(url.openConnection().getPermission());
- reduced.add(url);
- } catch (IOException e) {
- } catch (SecurityException e) {
- }
- }
- result = reduced;
- }
- return Collections.enumeration(result);
- }
-
- void findResourcesImpl(String name, ArrayList<URL> result) {
+ ArrayList<URL> result = new ArrayList<URL>();
int n = 0;
while (true) {
URLHandler handler = getHandler(n++);
@@ -681,9 +596,9 @@
}
handler.findResources(name, result);
}
+ return Collections.enumeration(result);
}
-
/**
* Converts an input stream into a byte array.
*
@@ -691,8 +606,7 @@
* the input stream
* @return byte[] the byte array
*/
- private static byte[] getBytes(InputStream is)
- throws IOException {
+ private static byte[] getBytes(InputStream is) throws IOException {
byte[] buf = new byte[4096];
ByteArrayOutputStream bos = new ByteArrayOutputStream(4096);
int count;
@@ -771,49 +685,30 @@
/**
* Returns a new {@code URLClassLoader} instance for the given URLs and the
- * system {@code ClassLoader} as its parent. The method {@code loadClass()}
- * of the new instance will call {@code
- * SecurityManager.checkPackageAccess()} before loading a class.
+ * system {@code ClassLoader} as its parent.
*
* @param urls
* the list of URLs that is passed to the new {@code
- * URLClassloader}.
+ * URLClassLoader}.
* @return the created {@code URLClassLoader} instance.
*/
public static URLClassLoader newInstance(final URL[] urls) {
- URLClassLoader sub = AccessController
- .doPrivileged(new PrivilegedAction<URLClassLoader>() {
- public URLClassLoader run() {
- return new SubURLClassLoader(urls);
- }
- });
- sub.currentContext = AccessController.getContext();
- return sub;
+ return new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
}
/**
* Returns a new {@code URLClassLoader} instance for the given URLs and the
- * specified {@code ClassLoader} as its parent. The method {@code
- * loadClass()} of the new instance will call the SecurityManager's {@code
- * checkPackageAccess()} before loading a class.
+ * specified {@code ClassLoader} as its parent.
*
* @param urls
- * the list of URLs that is passed to the new URLClassloader.
+ * the list of URLs that is passed to the new URLClassLoader.
* @param parentCl
* the parent class loader that is passed to the new
- * URLClassloader.
+ * URLClassLoader.
* @return the created {@code URLClassLoader} instance.
*/
- public static URLClassLoader newInstance(final URL[] urls,
- final ClassLoader parentCl) {
- URLClassLoader sub = AccessController
- .doPrivileged(new PrivilegedAction<URLClassLoader>() {
- public URLClassLoader run() {
- return new SubURLClassLoader(urls, parentCl);
- }
- });
- sub.currentContext = AccessController.getContext();
- return sub;
+ public static URLClassLoader newInstance(final URL[] urls, final ClassLoader parentCl) {
+ return new URLClassLoader(urls, parentCl);
}
/**
@@ -831,22 +726,10 @@
* @param factory
* the factory that will be used to create protocol-specific
* stream handlers.
- * @throws SecurityException
- * if a security manager exists and its {@code
- * checkCreateClassLoader()} method doesn't allow creation of
- * new {@code ClassLoader}s.
*/
- public URLClassLoader(URL[] searchUrls, ClassLoader parent,
- URLStreamHandlerFactory factory) {
+ public URLClassLoader(URL[] searchUrls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(parent);
- // Required for pre-v1.2 security managers to work
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkCreateClassLoader();
- }
this.factory = factory;
- // capture the context of the thread that creates this URLClassLoader
- currentContext = AccessController.getContext();
int nbUrls = searchUrls.length;
originalUrls = new ArrayList<URL>(nbUrls);
handlerList = new ArrayList<URLHandler>(nbUrls);
@@ -865,25 +748,30 @@
* class could be found, a class object representing the loaded class will
* be returned.
*
- * @param clsName
- * the name of the class which has to be found.
- * @return the class that has been loaded.
* @throws ClassNotFoundException
* if the specified class cannot be loaded.
*/
@Override
- protected Class<?> findClass(final String clsName)
- throws ClassNotFoundException {
- Class<?> cls = AccessController.doPrivileged(
- new PrivilegedAction<Class<?>>() {
- public Class<?> run() {
- return findClassImpl(clsName);
- }
- }, currentContext);
- if (cls != null) {
- return cls;
+ protected Class<?> findClass(final String className) throws ClassNotFoundException {
+ String partialName = className.replace('.', '/');
+ final String classFileName = new StringBuilder(partialName).append(".class").toString();
+ String packageName = null;
+ int position = partialName.lastIndexOf('/');
+ if ((position = partialName.lastIndexOf('/')) != -1) {
+ packageName = partialName.substring(0, position);
}
- throw new ClassNotFoundException(clsName);
+ int n = 0;
+ while (true) {
+ URLHandler handler = getHandler(n++);
+ if (handler == null) {
+ break;
+ }
+ Class<?> res = handler.findClass(packageName, classFileName, className);
+ if (res != null) {
+ return res;
+ }
+ }
+ throw new ClassNotFoundException(className);
}
/**
@@ -926,40 +814,13 @@
if (name == null) {
return null;
}
- URL result = AccessController.doPrivileged(new PrivilegedAction<URL>() {
- public URL run() {
- return findResourceImpl(name);
- }
- }, currentContext);
- SecurityManager sm;
- if (result != null && (sm = System.getSecurityManager()) != null) {
- try {
- sm.checkPermission(result.openConnection().getPermission());
- } catch (IOException e) {
- return null;
- } catch (SecurityException e) {
- return null;
- }
- }
- return result;
- }
-
- /**
- * Returns a URL among the given ones referencing the specified resource or
- * null if no resource could be found.
- *
- * @param resName java.lang.String the name of the requested resource
- * @return URL URL for the resource.
- */
- URL findResourceImpl(String resName) {
int n = 0;
-
while (true) {
URLHandler handler = getHandler(n++);
if (handler == null) {
break;
}
- URL res = handler.findResource(resName);
+ URL res = handler.findResource(name);
if (res != null) {
return res;
}
@@ -967,7 +828,7 @@
return null;
}
- URLHandler getHandler(int num) {
+ private URLHandler getHandler(int num) {
if (num < handlerList.size()) {
return handlerList.get(num);
}
@@ -1122,17 +983,16 @@
}
private boolean isSealed(Manifest manifest, String dirName) {
- Attributes mainAttributes = manifest.getMainAttributes();
- String value = mainAttributes.getValue(Attributes.Name.SEALED);
- boolean sealed = value != null && value.toLowerCase().equals("true");
Attributes attributes = manifest.getAttributes(dirName);
if (attributes != null) {
- value = attributes.getValue(Attributes.Name.SEALED);
+ String value = attributes.getValue(Attributes.Name.SEALED);
if (value != null) {
- sealed = value.toLowerCase().equals("true");
+ return value.equalsIgnoreCase("true");
}
}
- return sealed;
+ Attributes mainAttributes = manifest.getMainAttributes();
+ String value = mainAttributes.getValue(Attributes.Name.SEALED);
+ return (value != null && value.equalsIgnoreCase("true"));
}
/**
@@ -1170,28 +1030,4 @@
}
return addedURLs;
}
-
- Class<?> findClassImpl(String className) {
- String partialName = className.replace('.', '/');
- final String classFileName = new StringBuilder(partialName).append(".class").toString();
- String packageName = null;
- int position = partialName.lastIndexOf('/');
- if ((position = partialName.lastIndexOf('/')) != -1) {
- packageName = partialName.substring(0, position);
- }
- int n = 0;
- while (true) {
- URLHandler handler = getHandler(n++);
- if (handler == null) {
- break;
- }
- Class<?> res = handler.findClass(packageName, classFileName, className);
- if (res != null) {
- return res;
- }
- }
- return null;
-
- }
-
}
diff --git a/luni/src/main/java/java/net/URLConnection.java b/luni/src/main/java/java/net/URLConnection.java
index e467932..403c48b 100644
--- a/luni/src/main/java/java/net/URLConnection.java
+++ b/luni/src/main/java/java/net/URLConnection.java
@@ -20,15 +20,12 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
-import java.util.StringTokenizer;
-import org.apache.harmony.luni.util.PriviAction;
/**
* A connection to a URL for reading or writing. For HTTP connections, see
@@ -276,19 +273,14 @@
return (ContentHandler) cHandler;
}
- // search through the package list for the right class for the Content
- // Type
- String packageList = AccessController
- .doPrivileged(new PriviAction<String>(
- "java.content.handler.pkgs"));
+ // search through the package list for the right class for the Content Type
+ String packageList = System.getProperty("java.content.handler.pkgs");
if (packageList != null) {
- final StringTokenizer st = new StringTokenizer(packageList, "|");
- while (st.countTokens() > 0) {
+ for (String packageName : packageList.split("\\|")) {
+ String className = packageName + "." + typeString;
try {
- Class<?> cl = Class.forName(st.nextToken() + "."
- + typeString, true, ClassLoader
- .getSystemClassLoader());
- cHandler = cl.newInstance();
+ Class<?> klass = Class.forName(className, true, ClassLoader.getSystemClassLoader());
+ cHandler = klass.newInstance();
} catch (ClassNotFoundException e) {
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
@@ -297,21 +289,14 @@
}
if (cHandler == null) {
- cHandler = AccessController
- .doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- try {
- // Try looking up AWT image content handlers
- String className = "org.apache.harmony.awt.www.content."
- + typeString;
- return Class.forName(className).newInstance();
- } catch (ClassNotFoundException e) {
- } catch (IllegalAccessException e) {
- } catch (InstantiationException e) {
- }
- return null;
- }
- });
+ try {
+ // Try looking up AWT image content handlers
+ String className = "org.apache.harmony.awt.www.content." + typeString;
+ cHandler = Class.forName(className).newInstance();
+ } catch (ClassNotFoundException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InstantiationException e) {
+ }
}
if (cHandler != null) {
if (!(cHandler instanceof ContentHandler)) {
@@ -721,10 +706,7 @@
* @throws IOException
* if an I/O error occurs while reading from the input stream.
*/
- @SuppressWarnings("nls")
- public static String guessContentTypeFromStream(InputStream is)
- throws IOException {
-
+ public static String guessContentTypeFromStream(InputStream is) throws IOException {
if (!is.markSupported()) {
return null;
}
@@ -789,7 +771,7 @@
}
// Check text types
- String textHeader = header.trim().toUpperCase();
+ String textHeader = header.trim().toUpperCase(Locale.US);
if (textHeader.startsWith("<!DOCTYPE HTML") ||
textHeader.startsWith("<HTML") ||
textHeader.startsWith("<HEAD") ||
@@ -845,24 +827,17 @@
/**
* Sets the internally used content handler factory. The content factory can
- * only be set if it is allowed by the security manager and only once during
- * the lifetime of the application.
+ * only be set once during the lifetime of the application.
*
* @param contentFactory
* the content factory to be set.
* @throws Error
- * if the security manager does not allow to set the content
- * factory or it has been already set earlier ago.
+ * if the factory has been already set.
*/
- public static synchronized void setContentHandlerFactory(
- ContentHandlerFactory contentFactory) {
+ public static synchronized void setContentHandlerFactory(ContentHandlerFactory contentFactory) {
if (contentHandlerFactory != null) {
throw new Error("Factory already set");
}
- SecurityManager sManager = System.getSecurityManager();
- if (sManager != null) {
- sManager.checkSetFactory();
- }
contentHandlerFactory = contentFactory;
}
@@ -949,10 +924,6 @@
* the MIME table to be set.
*/
public static void setFileNameMap(FileNameMap map) {
- SecurityManager manager = System.getSecurityManager();
- if (manager != null) {
- manager.checkSetFactory();
- }
synchronized (URLConnection.class) {
fileNameMap = map;
}
diff --git a/luni/src/main/java/java/net/URLDecoder.java b/luni/src/main/java/java/net/URLDecoder.java
index debd111..e34fe4a 100644
--- a/luni/src/main/java/java/net/URLDecoder.java
+++ b/luni/src/main/java/java/net/URLDecoder.java
@@ -18,11 +18,8 @@
package java.net;
import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
import java.nio.charset.Charset;
-import java.nio.charset.IllegalCharsetNameException;
-import java.nio.charset.UnsupportedCharsetException;
+import libcore.net.UriCodec;
/**
* This class is used to decode a string which is encoded in the {@code
@@ -45,7 +42,7 @@
*/
@Deprecated
public static String decode(String s) {
- return decode(s, Charset.defaultCharset());
+ return UriCodec.decode(s, true, Charset.defaultCharset());
}
/**
@@ -67,76 +64,6 @@
* if the specified encoding scheme is invalid.
*/
public static String decode(String s, String encoding) throws UnsupportedEncodingException {
- if (encoding == null) {
- throw new NullPointerException();
- }
- if (encoding.isEmpty()) {
- throw new UnsupportedEncodingException(encoding);
- }
-
- if (s.indexOf('%') == -1) {
- if (s.indexOf('+') == -1)
- return s;
- char[] str = s.toCharArray();
- for (int i = 0; i < str.length; i++) {
- if (str[i] == '+')
- str[i] = ' ';
- }
- return new String(str);
- }
-
- Charset charset = null;
- try {
- charset = Charset.forName(encoding);
- } catch (IllegalCharsetNameException e) {
- throw (UnsupportedEncodingException) (new UnsupportedEncodingException(
- encoding).initCause(e));
- } catch (UnsupportedCharsetException e) {
- throw (UnsupportedEncodingException) (new UnsupportedEncodingException(
- encoding).initCause(e));
- }
-
- return decode(s, charset);
- }
-
- private static String decode(String s, Charset charset) {
-
- char[] str_buf = new char[s.length()];
- byte[] buf = new byte[s.length() / 3];
- int buf_len = 0;
-
- for (int i = 0; i < s.length();) {
- char c = s.charAt(i);
- if (c == '+') {
- str_buf[buf_len] = ' ';
- } else if (c == '%') {
-
- int len = 0;
- do {
- if (i + 2 >= s.length()) {
- throw new IllegalArgumentException("Incomplete % sequence at: " + i);
- }
- int d1 = Character.digit(s.charAt(i + 1), 16);
- int d2 = Character.digit(s.charAt(i + 2), 16);
- if (d1 == -1 || d2 == -1) {
- throw new IllegalArgumentException("Invalid % sequence " +
- s.substring(i, i + 3) + " at " + i);
- }
- buf[len++] = (byte) ((d1 << 4) + d2);
- i += 3;
- } while (i < s.length() && s.charAt(i) == '%');
-
- CharBuffer cb = charset.decode(ByteBuffer.wrap(buf, 0, len));
- len = cb.length();
- System.arraycopy(cb.array(), 0, str_buf, buf_len, len);
- buf_len += len;
- continue;
- } else {
- str_buf[buf_len] = c;
- }
- i++;
- buf_len++;
- }
- return new String(str_buf, 0, buf_len);
+ return UriCodec.decode(s, true, Charset.forName(encoding));
}
}
diff --git a/luni/src/main/java/java/net/URLEncoder.java b/luni/src/main/java/java/net/URLEncoder.java
index f53f05d..5dd85b0 100644
--- a/luni/src/main/java/java/net/URLEncoder.java
+++ b/luni/src/main/java/java/net/URLEncoder.java
@@ -18,117 +18,42 @@
package java.net;
import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.Charsets;
+import libcore.net.UriCodec;
/**
* This class is used to encode a string using the format required by
* {@code application/x-www-form-urlencoded} MIME content type.
+ *
+ * <p>All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
+ * and characters '.', '-', '*', '_' are converted into their hexadecimal value
+ * prepended by '%'. For example: '#' -> %23. In addition, spaces are
+ * substituted by '+'.
*/
public class URLEncoder {
+ private URLEncoder() {}
- static final String digits = "0123456789ABCDEF";
+ static UriCodec ENCODER = new UriCodec() {
+ @Override protected boolean isRetained(char c) {
+ return " .-*_".indexOf(c) != -1;
+ }
+ };
/**
- * Prevents this class from being instantiated.
- */
- private URLEncoder() {
- }
-
- /**
- * Encodes a given string {@code s} in a x-www-form-urlencoded string using
- * the specified encoding scheme {@code enc}.
- * <p>
- * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
- * and characters '.', '-', '*', '_' are converted into their hexadecimal
- * value prepended by '%'. For example: '#' -> %23. In addition, spaces are
- * substituted by '+'
+ * Equivalent to {@code encode(s, "UTF-8")}.
*
- * @param s
- * the string to be encoded.
- * @return the encoded string.
* @deprecated use {@link #encode(String, String)} instead.
*/
@Deprecated
public static String encode(String s) {
- // Guess a bit bigger for encoded form
- StringBuilder buf = new StringBuilder(s.length() + 16);
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
- || (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) {
- buf.append(ch);
- } else if (ch == ' ') {
- buf.append('+');
- } else {
- byte[] bytes = new String(new char[] { ch }).getBytes();
- for (int j = 0; j < bytes.length; j++) {
- buf.append('%');
- buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
- buf.append(digits.charAt(bytes[j] & 0xf));
- }
- }
- }
- return buf.toString();
+ return ENCODER.encode(s, Charsets.UTF_8);
}
/**
- * Encodes the given string {@code s} in a x-www-form-urlencoded string
- * using the specified encoding scheme {@code enc}.
- * <p>
- * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
- * and characters '.', '-', '*', '_' are converted into their hexadecimal
- * value prepended by '%'. For example: '#' -> %23. In addition, spaces are
- * substituted by '+'
- *
- * @param s
- * the string to be encoded.
- * @param enc
- * the encoding scheme to be used.
- * @return the encoded string.
- * @throws UnsupportedEncodingException
- * if the specified encoding scheme is invalid.
+ * Encodes {@code s} using the {@link Charset} named by {@code charsetName}.
*/
- public static String encode(String s, String enc) throws UnsupportedEncodingException {
- if (s == null || enc == null) {
- throw new NullPointerException();
- }
- // check for UnsupportedEncodingException
- "".getBytes(enc);
-
- // Guess a bit bigger for encoded form
- StringBuilder buf = new StringBuilder(s.length() + 16);
- int start = -1;
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
- || (ch >= '0' && ch <= '9') || " .-*_".indexOf(ch) > -1) {
- if (start >= 0) {
- convert(s.substring(start, i), buf, enc);
- start = -1;
- }
- if (ch != ' ') {
- buf.append(ch);
- } else {
- buf.append('+');
- }
- } else {
- if (start < 0) {
- start = i;
- }
- }
- }
- if (start >= 0) {
- convert(s.substring(start, s.length()), buf, enc);
- }
- return buf.toString();
- }
-
- private static void convert(String s, StringBuilder buf, String enc)
- throws UnsupportedEncodingException {
- byte[] bytes = s.getBytes(enc);
- for (int j = 0; j < bytes.length; j++) {
- buf.append('%');
- buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
- buf.append(digits.charAt(bytes[j] & 0xf));
- }
+ public static String encode(String s, String charsetName) throws UnsupportedEncodingException {
+ return ENCODER.encode(s, Charset.forName(charsetName));
}
}
diff --git a/luni/src/main/java/java/net/URLStreamHandler.java b/luni/src/main/java/java/net/URLStreamHandler.java
index a17ebe6..e4eb697 100644
--- a/luni/src/main/java/java/net/URLStreamHandler.java
+++ b/luni/src/main/java/java/net/URLStreamHandler.java
@@ -18,8 +18,6 @@
package java.net;
import java.io.IOException;
-import java.nio.charset.Charsets;
-import java.util.Locale;
import libcore.util.Objects;
import org.apache.harmony.luni.util.URLUtil;
@@ -313,144 +311,54 @@
if (authority != null && !authority.isEmpty()) {
result.append("//");
if (escapeIllegalCharacters) {
- authority = fixEncoding(authority, "$,;@&=+:[]");
+ URI.AUTHORITY_ENCODER.appendPartiallyEncoded(result, authority);
+ } else {
+ result.append(authority);
}
- result.append(authority);
}
String fileAndQuery = url.getFile();
if (fileAndQuery != null) {
if (escapeIllegalCharacters) {
- fileAndQuery = fixEncoding(fileAndQuery, "$,;@&=+:/?");
+ URI.FILE_AND_QUERY_ENCODER.appendPartiallyEncoded(result, fileAndQuery);
+ } else {
+ result.append(fileAndQuery);
}
- result.append(fileAndQuery);
}
String ref = url.getRef();
if (ref != null) {
result.append('#');
if (escapeIllegalCharacters) {
- ref = fixEncoding(ref, "$,;@&=+:/?[]");
+ URI.ALL_LEGAL_ENCODER.appendPartiallyEncoded(result, ref);
+ } else {
+ result.append(ref);
}
- result.append(ref);
}
return result.toString();
}
/**
- * Escapes the unescaped characters of {@code s} that are not permitted.
- * Permitted characters are:
- * <ul>
- * <li>Unreserved characters in RFC 2396.
- * <li>{@code extraOkayChars},
- * <li>non-ASCII, non-control, non-whitespace characters
- * </ul>
- *
- * <p>Unlike the methods in {@code URI}, this method ignores input that has
- * already been escaped. For example, input of "hello%20world" is unchanged
- * by this method but would be double-escaped to "hello%2520world" by URI.
- *
- * <p>UTF-8 is used to encode escaped characters. A single input character
- * like "\u0080" may be encoded to multiple octets like %C2%80.
+ * Returns true if {@code a} and {@code b} have the same protocol, host,
+ * port, file, and reference.
*/
- private String fixEncoding(String s, String extraPermittedChars) {
- StringBuilder result = null;
- int copiedCount = 0;
-
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
-
- if (c == '%') {
- i += 2; // this is a 3-character sequence like "%20"
- continue;
- }
-
- // unreserved characters: alphanum | mark
- if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'
- || c == '-' || c == '_' || c == '.' || c == '!' || c == '~'
- || c == '*' || c == '\'' || c == '(' || c == ')') {
- continue;
- }
-
- // characters permitted in this context
- if (extraPermittedChars.indexOf(c) != -1) {
- continue;
- }
-
- // other characters
- if (c > 0x7f && !Character.isISOControl(c) && !Character.isSpaceChar(c)) {
- continue;
- }
-
- /*
- * We've encountered a character that must be escaped.
- */
- if (result == null) {
- result = new StringBuilder();
- }
- result.append(s, copiedCount, i);
-
- if (c < 0x7f) {
- appendHex(result, c);
- } else {
- for (byte b : s.substring(i, i + 1).getBytes(Charsets.UTF_8)) {
- appendHex(result, b & 0xff);
- }
- }
-
- copiedCount = i + 1;
- }
-
- if (result == null) {
- return s;
- } else {
- result.append(s, copiedCount, s.length());
- return result.toString();
- }
- }
-
- private void appendHex(StringBuilder stringBuilder, int b) {
- String hex = Integer.toHexString(b).toUpperCase(Locale.US);
- stringBuilder.append(hex.length() == 1 ? "%0" : "%").append(hex); // always 2 hex digits
- }
-
- /**
- * Compares two URL objects whether they represent the same URL. Two URLs
- * are equal if they have the same file, host, port, protocol, query, and
- * reference components.
- *
- * @param url1
- * the first URL to compare.
- * @param url2
- * the second URL to compare.
- * @return {@code true} if the URLs are the same, {@code false} otherwise.
- * @see #hashCode
- */
- protected boolean equals(URL url1, URL url2) {
- if (!sameFile(url1, url2)) {
- return false;
- }
- return Objects.equal(url1.getRef(), url2.getRef())
- && Objects.equal(url1.getQuery(), url2.getQuery());
+ protected boolean equals(URL a, URL b) {
+ return sameFile(a, b)
+ && Objects.equal(a.getRef(), b.getRef())
+ && Objects.equal(a.getQuery(), b.getQuery());
}
/**
* Returns the default port of the protocol used by the handled URL. The
- * current implementation returns always {@code -1}.
- *
- * @return the appropriate default port number of the protocol.
+ * default implementation always returns {@code -1}.
*/
protected int getDefaultPort() {
return -1;
}
/**
- * Returns the host address of the given URL.
- *
- * @param url
- * the URL object where to read the host address from.
- * @return the host address of the specified URL.
+ * Returns the host address of {@code url}.
*/
protected InetAddress getHostAddress(URL url) {
try {
@@ -465,70 +373,33 @@
}
/**
- * Returns the hashcode value for the given URL object.
- *
- * @param url
- * the URL to determine the hashcode.
- * @return the hashcode of the given URL.
+ * Returns the hash code of {@code url}.
*/
protected int hashCode(URL url) {
return toExternalForm(url).hashCode();
}
/**
- * Compares two URL objects whether they refer to the same host.
- *
- * @param a the first URL to be compared.
- * @param b the second URL to be compared.
- * @return {@code true} if both URLs refer to the same host, {@code false}
- * otherwise.
+ * Returns true if the hosts of {@code a} and {@code b} are equal.
*/
protected boolean hostsEqual(URL a, URL b) {
- /*
- * URLs with the same case-insensitive host name have equal hosts
- */
+ // URLs with the same case-insensitive host name have equal hosts
String aHost = getHost(a);
String bHost = getHost(b);
- if (aHost != null && aHost.equalsIgnoreCase(bHost)) {
- return true;
- }
-
- /*
- * Call out to DNS to resolve the host addresses. If this succeeds for
- * both addresses and both addresses yield the same InetAddress, report
- * equality.
- *
- * Although it's consistent with historical behavior of the RI, this
- * approach is fundamentally broken. In particular, acting upon this
- * result is bogus because a single server may serve content for many
- * unrelated host names.
- */
- InetAddress aResolved = getHostAddress(a);
- return aResolved != null && aResolved.equals(getHostAddress(b));
+ return aHost != null && aHost.equalsIgnoreCase(bHost);
}
/**
- * Compares two URL objects whether they refer to the same file. In the
- * comparison included are the URL components protocol, host, port and file.
- *
- * @param url1
- * the first URL to be compared.
- * @param url2
- * the second URL to be compared.
- * @return {@code true} if both URLs refer to the same file, {@code false}
- * otherwise.
+ * Returns true if {@code a} and {@code b} have the same protocol, host,
+ * port and file.
*/
- protected boolean sameFile(URL url1, URL url2) {
- return Objects.equal(url1.getProtocol(), url2.getProtocol())
- && Objects.equal(url1.getFile(), url2.getFile())
- && hostsEqual(url1, url2)
- && url1.getEffectivePort() == url2.getEffectivePort();
+ protected boolean sameFile(URL a, URL b) {
+ return Objects.equal(a.getProtocol(), b.getProtocol())
+ && hostsEqual(a, b)
+ && a.getEffectivePort() == b.getEffectivePort()
+ && Objects.equal(a.getFile(), b.getFile());
}
- /*
- * If the URL host is empty while protocal is file, the host is regarded as
- * localhost.
- */
private static String getHost(URL url) {
String host = url.getHost();
if ("file".equals(url.getProtocol()) && host.isEmpty()) {
diff --git a/luni/src/main/java/java/nio/DatagramChannelImpl.java b/luni/src/main/java/java/nio/DatagramChannelImpl.java
index 2c85a67..df5e1f7 100644
--- a/luni/src/main/java/java/nio/DatagramChannelImpl.java
+++ b/luni/src/main/java/java/nio/DatagramChannelImpl.java
@@ -130,17 +130,6 @@
// check the address
InetSocketAddress inetSocketAddress = SocketChannelImpl.validateAddress(address);
- // security check
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- if (inetSocketAddress.getAddress().isMulticastAddress()) {
- sm.checkMulticast(inetSocketAddress.getAddress());
- } else {
- sm.checkConnect(inetSocketAddress.getAddress().getHostName(),
- inetSocketAddress.getPort());
- }
- }
-
try {
begin();
Platform.NETWORK.connect(fd,
@@ -224,17 +213,6 @@
receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength(),
false, isConnected());
- // security check
- SecurityManager sm = System.getSecurityManager();
- if (!isConnected() && sm != null) {
- try {
- sm.checkAccept(receivePacket.getAddress().getHostAddress(),
- receivePacket.getPort());
- } catch (SecurityException e) {
- // do discard the datagram packet
- receivePacket = null;
- }
- }
if (receivePacket != null && receivePacket.getAddress() != null) {
if (received > 0) {
@@ -262,17 +240,6 @@
received = Platform.NETWORK.recvDirect(fd, receivePacket, address,
target.position(), target.remaining(), false, isConnected());
- // security check
- SecurityManager sm = System.getSecurityManager();
- if (!isConnected() && sm != null) {
- try {
- sm.checkAccept(receivePacket.getAddress().getHostAddress(),
- receivePacket.getPort());
- } catch (SecurityException e) {
- // do discard the datagram packet
- receivePacket = null;
- }
- }
if (receivePacket != null && receivePacket.getAddress() != null) {
// copy the data of received packet
if (received > 0) {
@@ -302,20 +269,8 @@
throw new IOException();
}
- if (isConnected()) {
- if (!connectAddress.equals(isa)) {
- throw new IllegalArgumentException();
- }
- } else {
- // not connected, check security
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- if (isa.getAddress().isMulticastAddress()) {
- sm.checkMulticast(isa.getAddress());
- } else {
- sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
- }
- }
+ if (isConnected() && !connectAddress.equals(isa)) {
+ throw new IllegalArgumentException();
}
// the return value.
diff --git a/luni/src/main/java/java/nio/DirectByteBuffer.java b/luni/src/main/java/java/nio/DirectByteBuffer.java
index d9e8afd..ccc5c6b 100644
--- a/luni/src/main/java/java/nio/DirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/DirectByteBuffer.java
@@ -205,18 +205,20 @@
block.free();
}
- @Override
- final protected byte[] protectedArray() {
- throw new UnsupportedOperationException();
+ @Override protected byte[] protectedArray() {
+ byte[] array = this.block.array();
+ if (array == null) {
+ throw new UnsupportedOperationException();
+ }
+ return array;
}
- @Override
- final protected int protectedArrayOffset() {
- throw new UnsupportedOperationException();
+ @Override protected int protectedArrayOffset() {
+ protectedArray(); // Check we have an array.
+ return offset;
}
- @Override
- final protected boolean protectedHasArray() {
- return false;
+ @Override protected boolean protectedHasArray() {
+ return protectedArray() != null;
}
}
diff --git a/luni/src/main/java/java/nio/FileChannelImpl.java b/luni/src/main/java/java/nio/FileChannelImpl.java
index c8efc97..3bca1b1 100644
--- a/luni/src/main/java/java/nio/FileChannelImpl.java
+++ b/luni/src/main/java/java/nio/FileChannelImpl.java
@@ -514,7 +514,6 @@
int[] handles = new int[length];
int[] offsets = new int[length];
int[] lengths = new int[length];
- // BEGIN android-changed
// list of allocated direct ByteBuffers to prevent them from being GC-ed
ByteBuffer[] allocatedBufs = new ByteBuffer[length];
@@ -534,7 +533,6 @@
handles[i] = NioUtils.getDirectBufferAddress(buffer);
lengths[i] = buffer.remaining();
}
- // END android-changed
long bytesWritten = 0;
boolean completed = false;
diff --git a/luni/src/main/java/java/nio/IntBuffer.java b/luni/src/main/java/java/nio/IntBuffer.java
index 3e1d9a3..9cc05ff 100644
--- a/luni/src/main/java/java/nio/IntBuffer.java
+++ b/luni/src/main/java/java/nio/IntBuffer.java
@@ -146,7 +146,6 @@
: otherBuffer.remaining();
int thisPos = position;
int otherPos = otherBuffer.position;
- // BEGIN android-changed
int thisInt, otherInt;
while (compareRemaining > 0) {
thisInt = get(thisPos);
@@ -158,7 +157,6 @@
otherPos++;
compareRemaining--;
}
- // END android-changed
return remaining() - otherBuffer.remaining();
}
diff --git a/luni/src/main/java/java/nio/LongBuffer.java b/luni/src/main/java/java/nio/LongBuffer.java
index 3b4be66..27edd2e 100644
--- a/luni/src/main/java/java/nio/LongBuffer.java
+++ b/luni/src/main/java/java/nio/LongBuffer.java
@@ -148,7 +148,6 @@
: otherBuffer.remaining();
int thisPos = position;
int otherPos = otherBuffer.position;
- // BEGIN android-changed
long thisLong, otherLong;
while (compareRemaining > 0) {
thisLong = get(thisPos);
@@ -160,7 +159,6 @@
otherPos++;
compareRemaining--;
}
- // END android-changed
return remaining() - otherBuffer.remaining();
}
diff --git a/luni/src/main/java/java/nio/MemoryBlock.java b/luni/src/main/java/java/nio/MemoryBlock.java
index 76a7b36..a19e5a0 100644
--- a/luni/src/main/java/java/nio/MemoryBlock.java
+++ b/luni/src/main/java/java/nio/MemoryBlock.java
@@ -58,6 +58,10 @@
this.array = array;
}
+ @Override public byte[] array() {
+ return array;
+ }
+
@Override public void free() {
array = null;
address = 0;
@@ -103,6 +107,11 @@
this.size = size;
}
+ // Used to support array/arrayOffset/hasArray for direct buffers.
+ public byte[] array() {
+ return null;
+ }
+
public void free() {
}
diff --git a/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java b/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
index d061e9c..0d61797 100644
--- a/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
@@ -135,4 +135,16 @@
public ByteBuffer slice() {
return new ReadOnlyDirectByteBuffer(block, remaining(), offset + position);
}
+
+ @Override protected byte[] protectedArray() {
+ throw new ReadOnlyBufferException();
+ }
+
+ @Override protected int protectedArrayOffset() {
+ throw new ReadOnlyBufferException();
+ }
+
+ @Override protected boolean protectedHasArray() {
+ return false;
+ }
}
diff --git a/luni/src/main/java/java/nio/ServerSocketChannelImpl.java b/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
index 9cefe5f..01d86a4 100644
--- a/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
+++ b/luni/src/main/java/java/nio/ServerSocketChannelImpl.java
@@ -155,10 +155,6 @@
sockChannel.setBound(true);
sockChannel.finishAccept();
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkAccept(socket.getInetAddress().getHostAddress(), socket.getPort());
- }
connectOK = true;
} finally {
if (!connectOK) {
diff --git a/luni/src/main/java/java/nio/SocketChannelImpl.java b/luni/src/main/java/java/nio/SocketChannelImpl.java
index dbef3c0..0a8b8b4 100644
--- a/luni/src/main/java/java/nio/SocketChannelImpl.java
+++ b/luni/src/main/java/java/nio/SocketChannelImpl.java
@@ -170,11 +170,6 @@
int port = inetSocketAddress.getPort();
String hostName = normalAddr.getHostName();
- // security check
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkConnect(hostName, port);
- }
// connect result
int result = EOF;
@@ -351,11 +346,8 @@
int offset = target.position();
int length = target.remaining();
if (target.isDirect()) {
- // BEGIN android-changed
- // changed address from long to int
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();
@@ -716,9 +708,7 @@
}
ByteBuffer buf = ByteBuffer.allocate(1);
int result = channel.read(buf);
- // BEGIN android-changed: input was already consumed
- return (-1 == result) ? result : buf.get(0) & 0xFF;
- // END android-changed
+ return (result == -1) ? result : (buf.get(0) & 0xff);
}
@Override
diff --git a/luni/src/main/java/java/nio/channels/DatagramChannel.java b/luni/src/main/java/java/nio/channels/DatagramChannel.java
index dd09e16..486b168 100644
--- a/luni/src/main/java/java/nio/channels/DatagramChannel.java
+++ b/luni/src/main/java/java/nio/channels/DatagramChannel.java
@@ -121,11 +121,8 @@
* if another thread interrupts the calling thread while the
* operation is in progress. The calling thread will have the
* interrupt state set and the channel will be closed.
- * @throws SecurityException
- * if there is a security manager, and the address is not
- * permitted to be accessed.
* @throws IOException
- * if some other I/O error occurrs.
+ * if some other I/O error occurs.
*/
public abstract DatagramChannel connect(SocketAddress address)
throws IOException;
@@ -175,9 +172,6 @@
* if another thread interrupts the calling thread while the
* operation is in progress. The calling thread will have the
* interrupt state set and the channel will be closed.
- * @throws SecurityException
- * if there is a security manager, and the address is not
- * permitted to be accessed.
* @throws IOException
* some other I/O error occurs.
*/
@@ -216,14 +210,10 @@
* if another thread interrupts the calling thread while the
* operation is in progress. The calling thread will have the
* interrupt state set and the channel will be closed.
- * @throws SecurityException
- * if there is a security manager, and the address is not
- * permitted to access.
* @throws IOException
* some other I/O error occurs.
*/
- public abstract int send(ByteBuffer source, SocketAddress address)
- throws IOException;
+ public abstract int send(ByteBuffer source, SocketAddress address) throws IOException;
/**
* Reads a datagram from this channel into the byte buffer.
diff --git a/luni/src/main/java/java/nio/channels/FileLock.java b/luni/src/main/java/java/nio/channels/FileLock.java
index 2c8025e..f1fa2ee 100644
--- a/luni/src/main/java/java/nio/channels/FileLock.java
+++ b/luni/src/main/java/java/nio/channels/FileLock.java
@@ -193,16 +193,7 @@
* @return the display string.
*/
@Override
- @SuppressWarnings("nls")
public final String toString() {
- StringBuilder buffer = new StringBuilder(64); // Guess length of string
- buffer.append("FileLock: [position=");
- buffer.append(position);
- buffer.append(", size=");
- buffer.append(size);
- buffer.append(", shared=");
- buffer.append(Boolean.toString(shared));
- buffer.append("]");
- return buffer.toString();
+ return "FileLock[position=" + position + ", size=" + size + ", shared=" + shared + "]";
}
}
diff --git a/luni/src/main/java/java/nio/channels/ServerSocketChannel.java b/luni/src/main/java/java/nio/channels/ServerSocketChannel.java
index 67d3b8e..f3c3390 100644
--- a/luni/src/main/java/java/nio/channels/ServerSocketChannel.java
+++ b/luni/src/main/java/java/nio/channels/ServerSocketChannel.java
@@ -107,9 +107,6 @@
* if another I/O error occurs.
* @throws NotYetBoundException
* if the socket has not yet been bound.
- * @throws SecurityException
- * if there is a security manager and it does not permit to
- * access the new connection.
*/
public abstract SocketChannel accept() throws IOException;
}
diff --git a/luni/src/main/java/java/nio/channels/SocketChannel.java b/luni/src/main/java/java/nio/channels/SocketChannel.java
index 9ca75ef..6e54ab9 100644
--- a/luni/src/main/java/java/nio/channels/SocketChannel.java
+++ b/luni/src/main/java/java/nio/channels/SocketChannel.java
@@ -97,9 +97,6 @@
* if another thread interrupts the calling thread while this
* operation is executing. The calling thread will have the
* interrupt state set and the channel will be closed.
- * @throws SecurityException
- * if there is a security manager and it denies the access of
- * {@code address}.
* @throws UnresolvedAddressException
* if the address is not resolved.
* @throws UnsupportedAddressTypeException
@@ -187,9 +184,6 @@
* if the address is not resolved.
* @throws UnsupportedAddressTypeException
* if the address type is not supported.
- * @throws SecurityException
- * if there is a security manager and it denies the access of
- * {@code address}.
* @throws IOException
* if an I/O error occurs.
*/
diff --git a/luni/src/main/java/java/nio/channels/spi/AbstractInterruptibleChannel.java b/luni/src/main/java/java/nio/channels/spi/AbstractInterruptibleChannel.java
index 47f2512..8befb1b 100644
--- a/luni/src/main/java/java/nio/channels/spi/AbstractInterruptibleChannel.java
+++ b/luni/src/main/java/java/nio/channels/spi/AbstractInterruptibleChannel.java
@@ -23,9 +23,6 @@
import java.nio.channels.Channel;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.InterruptibleChannel;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
/**
* {@code AbstractInterruptibleChannel} is the root class for interruptible
@@ -37,27 +34,15 @@
* argument to the {@code end} method should indicate if the I/O operation has
* actually completed so that any change may be visible to the invoker.
*/
-public abstract class AbstractInterruptibleChannel implements Channel,
- InterruptibleChannel {
+public abstract class AbstractInterruptibleChannel implements Channel, InterruptibleChannel {
static Method setInterruptAction = null;
-
static {
try {
- setInterruptAction = AccessController
- .doPrivileged(new PrivilegedExceptionAction<Method>() {
- public Method run() throws Exception {
- return Thread.class.getDeclaredMethod(
- "setInterruptAction",
- new Class[] { Runnable.class });
-
- }
- });
+ setInterruptAction = Thread.class.getDeclaredMethod("setInterruptAction", Runnable.class);
setInterruptAction.setAccessible(true);
- } catch (PrivilegedActionException e) {
- // FIXME: be accommodate before VM actually provides
- // setInterruptAction method
- // throw new Error(e);
+ } catch (NoSuchMethodException e) {
+ throw new AssertionError(e);
}
}
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 201ea9f..66ecb7e 100644
--- a/luni/src/main/java/java/nio/channels/spi/SelectorProvider.java
+++ b/luni/src/main/java/java/nio/channels/spi/SelectorProvider.java
@@ -24,8 +24,6 @@
import java.nio.channels.Pipe;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.ServiceLoader;
/**
@@ -44,17 +42,9 @@
/**
* Constructs a new {@code SelectorProvider}.
- *
- * @throws SecurityException
- * if there is a security manager installed that does not permit
- * the runtime permission labeled "selectorProvider".
*/
protected SelectorProvider() {
super();
- if (System.getSecurityManager() != null) {
- System.getSecurityManager().checkPermission(
- new RuntimePermission("selectorProvider"));
- }
}
/**
@@ -80,11 +70,7 @@
provider = loadProviderByJar();
}
if (provider == null) {
- provider = AccessController.doPrivileged(new PrivilegedAction<SelectorProvider>() {
- public SelectorProvider run() {
- return new SelectorProviderImpl();
- }
- });
+ provider = new SelectorProviderImpl();
}
}
return provider;
@@ -150,15 +136,8 @@
* @return the channel.
* @throws IOException
* if an I/O error occurs.
- * @throws SecurityException
- * if there is a security manager installed that does not permit
- * the runtime permission labeled "selectorProvider".
*/
public Channel inheritedChannel() throws IOException {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("inheritedChannel"));
- }
// Android never has stdin/stdout connected to a socket.
return null;
}
diff --git a/luni/src/main/java/java/nio/charset/Charset.java b/luni/src/main/java/java/nio/charset/Charset.java
index 800d810..04c8324 100644
--- a/luni/src/main/java/java/nio/charset/Charset.java
+++ b/luni/src/main/java/java/nio/charset/Charset.java
@@ -21,8 +21,6 @@
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.spi.CharsetProvider;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -565,11 +563,7 @@
}
private static Charset getDefaultCharset() {
- String encoding = AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return System.getProperty("file.encoding", "UTF-8");
- }
- });
+ String encoding = System.getProperty("file.encoding", "UTF-8");
try {
return Charset.forName(encoding);
} catch (UnsupportedCharsetException e) {
diff --git a/luni/src/main/java/java/nio/charset/CharsetDecoder.java b/luni/src/main/java/java/nio/charset/CharsetDecoder.java
index df2bb6a..f67dbbc 100644
--- a/luni/src/main/java/java/nio/charset/CharsetDecoder.java
+++ b/luni/src/main/java/java/nio/charset/CharsetDecoder.java
@@ -82,37 +82,21 @@
* @see java.nio.charset.CharsetEncoder
*/
public abstract class CharsetDecoder {
-
- /*
- * internal status consts
- */
private static final int INIT = 0;
-
private static final int ONGOING = 1;
-
private static final int END = 2;
-
private static final int FLUSH = 3;
- // average number of chars for one byte
- private float averChars;
+ private final float averageCharsPerByte;
+ private final float maxCharsPerByte;
- // maximum number of chars for one byte
- private float maxChars;
+ private final Charset cs;
- // charset for this decoder
- private Charset cs;
+ private CodingErrorAction malformedInputAction;
+ private CodingErrorAction unmappableCharacterAction;
- // specify the action if malformed input error encountered
- private CodingErrorAction malformAction;
+ private String replacementChars;
- // specify the action if unmappable character error encountered
- private CodingErrorAction unmapAction;
-
- // the replacement string
- private String replace;
-
- // the current status
private int status;
/**
@@ -133,38 +117,32 @@
* if <code>averageCharsPerByte</code> or
* <code>maxCharsPerByte</code> is negative.
*/
- protected CharsetDecoder(Charset charset, float averageCharsPerByte,
- float maxCharsPerByte) {
+ protected CharsetDecoder(Charset charset, float averageCharsPerByte, float maxCharsPerByte) {
if (averageCharsPerByte <= 0 || maxCharsPerByte <= 0) {
throw new IllegalArgumentException("averageCharsPerByte and maxCharsPerByte must be positive");
}
if (averageCharsPerByte > maxCharsPerByte) {
throw new IllegalArgumentException("averageCharsPerByte is greater than maxCharsPerByte");
}
- averChars = averageCharsPerByte;
- maxChars = maxCharsPerByte;
+ this.averageCharsPerByte = averageCharsPerByte;
+ this.maxCharsPerByte = maxCharsPerByte;
cs = charset;
status = INIT;
- malformAction = CodingErrorAction.REPORT;
- unmapAction = CodingErrorAction.REPORT;
- replace = "\ufffd";
+ malformedInputAction = CodingErrorAction.REPORT;
+ unmappableCharacterAction = CodingErrorAction.REPORT;
+ replacementChars = "\ufffd";
}
/**
- * Gets the average number of characters created by this decoder for a
+ * Returns the average number of characters created by this decoder for a
* single input byte.
- *
- * @return the average number of characters created by this decoder for a
- * single input byte.
*/
public final float averageCharsPerByte() {
- return averChars;
+ return averageCharsPerByte;
}
/**
- * Gets the <code>Charset</code> which this decoder uses.
- *
- * @return the <code>Charset</code> which this decoder uses.
+ * Returns the {@link Charset} which this decoder uses.
*/
public final Charset charset() {
return cs;
@@ -203,10 +181,9 @@
* @throws CharacterCodingException
* if another exception happened during the decode operation.
*/
- public final CharBuffer decode(ByteBuffer in)
- throws CharacterCodingException {
+ public final CharBuffer decode(ByteBuffer in) throws CharacterCodingException {
reset();
- int length = (int) (in.remaining() * averChars);
+ int length = (int) (in.remaining() * averageCharsPerByte);
CharBuffer output = CharBuffer.allocate(length);
CoderResult result = null;
while (true) {
@@ -239,12 +216,10 @@
/*
* checks the result whether it needs to throw CharacterCodingException.
*/
- private void checkCoderResult(CoderResult result)
- throws CharacterCodingException {
- if (result.isMalformed() && malformAction == CodingErrorAction.REPORT) {
+ private void checkCoderResult(CoderResult result) throws CharacterCodingException {
+ if (result.isMalformed() && malformedInputAction == CodingErrorAction.REPORT) {
throw new MalformedInputException(result.length());
- } else if (result.isUnmappable()
- && unmapAction == CodingErrorAction.REPORT) {
+ } else if (result.isUnmappable() && unmappableCharacterAction == CodingErrorAction.REPORT) {
throw new UnmappableCharacterException(result.length());
}
}
@@ -368,16 +343,16 @@
return result;
}
// set coding error handle action
- action = malformAction;
+ action = malformedInputAction;
if (result.isUnmappable()) {
- action = unmapAction;
+ action = unmappableCharacterAction;
}
// If the action is IGNORE or REPLACE, we should continue decoding.
if (action == CodingErrorAction.REPLACE) {
- if (out.remaining() < replace.length()) {
+ if (out.remaining() < replacementChars.length()) {
return CoderResult.OVERFLOW;
}
- out.put(replace);
+ out.put(replacementChars);
} else {
if (action != CodingErrorAction.IGNORE)
return result;
@@ -585,25 +560,19 @@
}
/**
- * Gets this decoder's <code>CodingErrorAction</code> when malformed input
+ * Returns this decoder's <code>CodingErrorAction</code> when malformed input
* occurred during the decoding process.
- *
- * @return this decoder's <code>CodingErrorAction</code> when malformed
- * input occurred during the decoding process.
*/
public CodingErrorAction malformedInputAction() {
- return malformAction;
+ return malformedInputAction;
}
/**
- * Gets the maximum number of characters which can be created by this
+ * Returns the maximum number of characters which can be created by this
* decoder for one input byte, must be positive.
- *
- * @return the maximum number of characters which can be created by this
- * decoder for one input byte, must be positive.
*/
public final float maxCharsPerByte() {
- return maxChars;
+ return maxCharsPerByte;
}
/**
@@ -623,7 +592,7 @@
if (newAction == null) {
throw new IllegalArgumentException();
}
- malformAction = newAction;
+ malformedInputAction = newAction;
implOnMalformedInput(newAction);
return this;
}
@@ -645,18 +614,16 @@
if (newAction == null) {
throw new IllegalArgumentException();
}
- unmapAction = newAction;
+ unmappableCharacterAction = newAction;
implOnUnmappableCharacter(newAction);
return this;
}
/**
- * Gets the replacement string, which is never null or empty.
- *
- * @return the replacement string, cannot be null or empty.
+ * Returns the replacement string, which is never null or empty.
*/
public final String replacement() {
- return replace;
+ return replacementChars;
}
/**
@@ -667,7 +634,7 @@
* {@link #implReplaceWith(String) implReplaceWith} method with the given
* new replacement as argument.
*
- * @param newReplacement
+ * @param replacement
* the replacement string, cannot be null or empty. Its length
* cannot be larger than {@link #maxCharsPerByte()}.
* @return this decoder.
@@ -675,15 +642,19 @@
* if the given replacement cannot satisfy the requirement
* mentioned above.
*/
- public final CharsetDecoder replaceWith(String newReplacement) {
- if (newReplacement == null || newReplacement.isEmpty()) {
- throw new IllegalArgumentException("Replacement string cannot be null or empty");
+ public final CharsetDecoder replaceWith(String replacement) {
+ if (replacement == null) {
+ throw new IllegalArgumentException("replacement == null");
}
- if (newReplacement.length() > maxChars) {
- throw new IllegalArgumentException("Replacement string cannot be longer than max characters per byte");
+ if (replacement.isEmpty()) {
+ throw new IllegalArgumentException("replacement.isEmpty()");
}
- replace = newReplacement;
- implReplaceWith(newReplacement);
+ if (replacement.length() > maxCharsPerByte()) {
+ throw new IllegalArgumentException("replacement length > maxCharsPerByte: " +
+ replacement.length() + " > " + maxCharsPerByte());
+ }
+ replacementChars = replacement;
+ implReplaceWith(replacement);
return this;
}
@@ -701,13 +672,10 @@
}
/**
- * Gets this decoder's <code>CodingErrorAction</code> when an unmappable
+ * Returns this decoder's <code>CodingErrorAction</code> when an unmappable
* character error occurred during the decoding process.
- *
- * @return this decoder's <code>CodingErrorAction</code> when an
- * unmappable character error occurred during the decoding process.
*/
public CodingErrorAction unmappableCharacterAction() {
- return unmapAction;
+ return unmappableCharacterAction;
}
}
diff --git a/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java b/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java
new file mode 100644
index 0000000..3ad46d7
--- /dev/null
+++ b/luni/src/main/java/java/nio/charset/CharsetDecoderICU.java
@@ -0,0 +1,221 @@
+/**
+*******************************************************************************
+* Copyright (C) 1996-2006, International Business Machines Corporation and *
+* others. All Rights Reserved. *
+*******************************************************************************
+*
+*******************************************************************************
+*/
+ /**
+ * A JNI interface for ICU converters.
+ *
+ *
+ * @author Ram Viswanadha, IBM
+ */
+package java.nio.charset;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import libcore.icu.ErrorCode;
+import libcore.icu.NativeConverter;
+import libcore.util.EmptyArray;
+
+final class CharsetDecoderICU extends CharsetDecoder {
+ private static final int MAX_CHARS_PER_BYTE = 2;
+
+ private static final int INPUT_OFFSET = 0;
+ private static final int OUTPUT_OFFSET = 1;
+ private static final int INVALID_BYTES = 2;
+ /*
+ * data[INPUT_OFFSET] = on input contains the start of input and on output the number of input bytes consumed
+ * data[OUTPUT_OFFSET] = on input contains the start of output and on output the number of output chars written
+ * data[INVALID_BYTES] = number of invalid bytes
+ */
+ private int[] data = new int[3];
+
+ /* handle to the ICU converter that is opened */
+ private long converterHandle = 0;
+
+ private byte[] input = null;
+ private char[] output= null;
+
+ private byte[] allocatedInput = null;
+ private char[] allocatedOutput = null;
+
+ // These instance variables are always assigned in the methods before being used. This class
+ // is inherently thread-unsafe so we don't have to worry about synchronization.
+ private int inEnd;
+ private int outEnd;
+ private int ec;
+
+ public static CharsetDecoderICU newInstance(Charset cs, String icuCanonicalName) {
+ // This complexity is necessary to ensure that even if the constructor, superclass
+ // constructor, or call to updateCallback throw, we still free the native peer.
+ long address = 0;
+ try {
+ address = NativeConverter.openConverter(icuCanonicalName);
+ float averageCharsPerByte = NativeConverter.getAveCharsPerByte(address);
+ CharsetDecoderICU result = new CharsetDecoderICU(cs, averageCharsPerByte, address);
+ address = 0; // CharsetDecoderICU has taken ownership; its finalizer will do the free.
+ result.updateCallback();
+ return result;
+ } finally {
+ if (address != 0) {
+ NativeConverter.closeConverter(address);
+ }
+ }
+ }
+
+ private CharsetDecoderICU(Charset cs, float averageCharsPerByte, long address) {
+ super(cs, averageCharsPerByte, MAX_CHARS_PER_BYTE);
+ this.converterHandle = address;
+ }
+
+ @Override protected void implReplaceWith(String newReplacement) {
+ updateCallback();
+ }
+
+ @Override protected final void implOnMalformedInput(CodingErrorAction newAction) {
+ updateCallback();
+ }
+
+ @Override protected final void implOnUnmappableCharacter(CodingErrorAction newAction) {
+ updateCallback();
+ }
+
+ private void updateCallback() {
+ ec = NativeConverter.setCallbackDecode(converterHandle, this);
+ if (ErrorCode.isFailure(ec)) {
+ throw ErrorCode.throwException(ec);
+ }
+ }
+
+ @Override protected void implReset() {
+ NativeConverter.resetByteToChar(converterHandle);
+ data[INPUT_OFFSET] = 0;
+ data[OUTPUT_OFFSET] = 0;
+ data[INVALID_BYTES] = 0;
+ output = null;
+ input = null;
+ allocatedInput = null;
+ allocatedOutput = null;
+ ec = 0;
+ inEnd = 0;
+ outEnd = 0;
+ }
+
+ @Override protected final CoderResult implFlush(CharBuffer out) {
+ try {
+ // ICU needs to see an empty input.
+ input = EmptyArray.BYTE;
+ inEnd = 0;
+ data[INPUT_OFFSET] = 0;
+
+ data[OUTPUT_OFFSET] = getArray(out);
+ data[INVALID_BYTES] = 0; // Make sure we don't see earlier errors.
+
+ ec = NativeConverter.decode(converterHandle, input, inEnd, output, outEnd, data, true);
+ if (ErrorCode.isFailure(ec)) {
+ if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
+ return CoderResult.OVERFLOW;
+ } else if (ec == ErrorCode.U_TRUNCATED_CHAR_FOUND) {
+ if (data[INPUT_OFFSET] > 0) {
+ return CoderResult.malformedForLength(data[INPUT_OFFSET]);
+ }
+ } else {
+ throw ErrorCode.throwException(ec);
+ }
+ }
+ return CoderResult.UNDERFLOW;
+ } finally {
+ setPosition(out);
+ implReset();
+ }
+ }
+
+ @Override protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
+ if (!in.hasRemaining()) {
+ return CoderResult.UNDERFLOW;
+ }
+
+ data[INPUT_OFFSET] = getArray(in);
+ data[OUTPUT_OFFSET]= getArray(out);
+
+ try {
+ ec = NativeConverter.decode(converterHandle, input, inEnd, output, outEnd, data, false);
+ if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
+ return CoderResult.OVERFLOW;
+ } else if (ec == ErrorCode.U_INVALID_CHAR_FOUND) {
+ return CoderResult.unmappableForLength(data[INVALID_BYTES]);
+ } else if (ec == ErrorCode.U_ILLEGAL_CHAR_FOUND) {
+ return CoderResult.malformedForLength(data[INVALID_BYTES]);
+ }
+ // Decoding succeeded: give us more data.
+ return CoderResult.UNDERFLOW;
+ } finally {
+ setPosition(in);
+ setPosition(out);
+ }
+ }
+
+ @Override protected void finalize() throws Throwable {
+ try {
+ NativeConverter.closeConverter(converterHandle);
+ converterHandle = 0;
+ } finally {
+ super.finalize();
+ }
+ }
+
+ private int getArray(CharBuffer out) {
+ if (out.hasArray()) {
+ output = out.array();
+ outEnd = out.arrayOffset() + out.limit();
+ return out.arrayOffset() + out.position();
+ } else {
+ outEnd = out.remaining();
+ if (allocatedOutput == null || outEnd > allocatedOutput.length) {
+ allocatedOutput = new char[outEnd];
+ }
+ // The array's start position is 0.
+ output = allocatedOutput;
+ return 0;
+ }
+ }
+
+ private int getArray(ByteBuffer in) {
+ if (in.hasArray()) {
+ input = in.array();
+ inEnd = in.arrayOffset() + in.limit();
+ return in.arrayOffset() + in.position();
+ } else {
+ inEnd = in.remaining();
+ if (allocatedInput == null || inEnd > allocatedInput.length) {
+ allocatedInput = new byte[inEnd];
+ }
+ // Copy the input buffer into the allocated array.
+ int pos = in.position();
+ in.get(allocatedInput, 0, inEnd);
+ in.position(pos);
+ // The array's start position is 0.
+ input = allocatedInput;
+ return 0;
+ }
+ }
+
+ private void setPosition(CharBuffer out) {
+ if (out.hasArray()) {
+ out.position(out.position() + data[OUTPUT_OFFSET] - out.arrayOffset());
+ } else {
+ out.put(output, 0, data[OUTPUT_OFFSET]);
+ }
+ // release reference to output array, which may not be ours
+ output = null;
+ }
+
+ private void setPosition(ByteBuffer in) {
+ in.position(in.position() + data[INPUT_OFFSET]);
+ // release reference to input array, which may not be ours
+ input = null;
+ }
+}
diff --git a/luni/src/main/java/java/nio/charset/CharsetEncoder.java b/luni/src/main/java/java/nio/charset/CharsetEncoder.java
index 739b152..28b2cb8 100644
--- a/luni/src/main/java/java/nio/charset/CharsetEncoder.java
+++ b/luni/src/main/java/java/nio/charset/CharsetEncoder.java
@@ -21,7 +21,6 @@
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.
@@ -77,41 +76,27 @@
* @see java.nio.charset.CharsetDecoder
*/
public abstract class CharsetEncoder {
-
- /*
- * internal status consts
- */
- private static final int INIT = 0;
-
+ private static final int READY = 0;
private static final int ONGOING = 1;
-
private static final int END = 2;
-
private static final int FLUSH = 3;
+ private static final int INIT = 4;
- // the Charset which creates this encoder
- private Charset cs;
+ private final Charset cs;
- // average bytes per character created by this encoder
- private float averBytes;
+ private final float averageBytesPerChar;
+ private final float maxBytesPerChar;
- // maximum bytes per character can be created by this encoder
- private float maxBytes;
+ private byte[] replacementBytes;
- // replacement byte array
- private byte[] replace;
-
- // internal status
private int status;
+ // internal status indicates encode(CharBuffer) operation is finished
+ private boolean finished;
- // action for malformed input
- private CodingErrorAction malformAction;
+ private CodingErrorAction malformedInputAction;
+ private CodingErrorAction unmappableCharacterAction;
- // action for unmapped char input
- private CodingErrorAction unmapAction;
-
- // decoder instance for this encoder's charset, used for replacement value
- // checking
+ // decoder instance for this encoder's charset, used for replacement value checking
private CharsetDecoder decoder;
/**
@@ -143,8 +128,11 @@
* @throws IllegalArgumentException
* if any parameters are invalid.
*/
- protected CharsetEncoder(Charset cs, float averageBytesPerChar,
- float maxBytesPerChar, byte[] replacement) {
+ protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement) {
+ this(cs, averageBytesPerChar, maxBytesPerChar, replacement, false);
+ }
+
+ CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement, boolean trusted) {
if (averageBytesPerChar <= 0 || maxBytesPerChar <= 0) {
throw new IllegalArgumentException("averageBytesPerChar and maxBytesPerChar must both be positive");
}
@@ -152,29 +140,26 @@
throw new IllegalArgumentException("averageBytesPerChar is greater than maxBytesPerChar");
}
this.cs = cs;
- averBytes = averageBytesPerChar;
- maxBytes = maxBytesPerChar;
+ this.averageBytesPerChar = averageBytesPerChar;
+ this.maxBytesPerChar = maxBytesPerChar;
status = INIT;
- malformAction = CodingErrorAction.REPORT;
- unmapAction = CodingErrorAction.REPORT;
- if (this instanceof CharsetEncoderICU) {
+ malformedInputAction = CodingErrorAction.REPORT;
+ unmappableCharacterAction = CodingErrorAction.REPORT;
+ if (trusted) {
// The RI enforces unnecessary restrictions on the replacement bytes. We trust ICU to
- // know what it's doing. This lets us support EUC-JP, SCSU, and Shift_JIS.
- uncheckedReplaceWith(replacement);
+ // know what it's doing. Doing so lets us support ICU's EUC-JP, SCSU, and Shift_JIS.
+ this.replacementBytes = replacement;
} else {
replaceWith(replacement);
}
}
/**
- * Gets the average number of bytes created by this encoder for a single
+ * Returns the average number of bytes created by this encoder for a single
* input character.
- *
- * @return the average number of bytes created by this encoder for a single
- * input character.
*/
public final float averageBytesPerChar() {
- return averBytes;
+ return averageBytesPerChar;
}
/**
@@ -199,14 +184,14 @@
// implementation of canEncode
private boolean implCanEncode(CharBuffer cb) {
- if (status == FLUSH) {
- status = INIT;
+ if (status == FLUSH || status == INIT) {
+ status = READY;
}
- if (status != INIT) {
+ if (status != READY) {
throw new IllegalStateException("encoding already in progress");
}
- CodingErrorAction malformBak = malformAction;
- CodingErrorAction unmapBak = unmapAction;
+ CodingErrorAction malformBak = malformedInputAction;
+ CodingErrorAction unmapBak = unmappableCharacterAction;
onMalformedInput(CodingErrorAction.REPORT);
onUnmappableCharacter(CodingErrorAction.REPORT);
boolean result = true;
@@ -249,9 +234,7 @@
}
/**
- * Gets the <code>Charset</code> which this encoder uses.
- *
- * @return the <code>Charset</code> which this encoder uses.
+ * Returns the {@link Charset} which this encoder uses.
*/
public final Charset charset() {
return cs;
@@ -293,7 +276,7 @@
return ByteBuffer.allocate(0);
}
reset();
- int length = (int) (in.remaining() * averBytes);
+ int length = (int) (in.remaining() * averageBytesPerChar);
ByteBuffer output = ByteBuffer.allocate(length);
CoderResult result = null;
while (true) {
@@ -327,7 +310,8 @@
}
break;
}
- status = FLUSH;
+ status = READY;
+ finished = true;
return output;
}
@@ -335,9 +319,9 @@
* checks the result whether it needs to throw CharacterCodingException.
*/
private void checkCoderResult(CoderResult result) throws CharacterCodingException {
- if (malformAction == CodingErrorAction.REPORT && result.isMalformed() ) {
+ if (malformedInputAction == CodingErrorAction.REPORT && result.isMalformed() ) {
throw new MalformedInputException(result.length());
- } else if (unmapAction == CodingErrorAction.REPORT && result.isUnmappable()) {
+ } else if (unmappableCharacterAction == CodingErrorAction.REPORT && result.isUnmappable()) {
throw new UnmappableCharacterException(result.length());
}
}
@@ -416,6 +400,11 @@
* <code>BufferUnderflowException</code>.
*/
public final CoderResult encode(CharBuffer in, ByteBuffer out, boolean endOfInput) {
+ // If the previous step is encode(CharBuffer), then no more input is needed
+ // thus endOfInput should not be false
+ if (status == READY && finished && !endOfInput) {
+ throw new IllegalStateException();
+ }
if ((status == FLUSH) || (!endOfInput && status == END)) {
throw new IllegalStateException();
}
@@ -445,17 +434,17 @@
status = endOfInput ? END : ONGOING;
return result;
}
- CodingErrorAction action = malformAction;
+ CodingErrorAction action = malformedInputAction;
if (result.isUnmappable()) {
- action = unmapAction;
+ action = unmappableCharacterAction;
}
// If the action is IGNORE or REPLACE, we should continue
// encoding.
if (action == CodingErrorAction.REPLACE) {
- if (out.remaining() < replace.length) {
+ if (out.remaining() < replacementBytes.length) {
return CoderResult.OVERFLOW;
}
- out.put(replace);
+ out.put(replacementBytes);
} else {
if (action != CodingErrorAction.IGNORE) {
return result;
@@ -531,7 +520,7 @@
* for the last boolean parameter.
*/
public final CoderResult flush(ByteBuffer out) {
- if (status != END && status != INIT) {
+ if (status != END && status != READY) {
throw new IllegalStateException();
}
CoderResult result = implFlush(out);
@@ -625,25 +614,19 @@
}
/**
- * Gets this encoder's <code>CodingErrorAction</code> when a malformed
+ * Returns this encoder's <code>CodingErrorAction</code> when a malformed
* input error occurred during the encoding process.
- *
- * @return this encoder's <code>CodingErrorAction</code> when a malformed
- * input error occurred during the encoding process.
*/
public CodingErrorAction malformedInputAction() {
- return malformAction;
+ return malformedInputAction;
}
/**
- * Gets the maximum number of bytes which can be created by this encoder for
+ * Returns the maximum number of bytes which can be created by this encoder for
* one input character, must be positive.
- *
- * @return the maximum number of bytes which can be created by this encoder
- * for one input character, must be positive.
*/
public final float maxBytesPerChar() {
- return maxBytes;
+ return maxBytesPerChar;
}
/**
@@ -663,7 +646,7 @@
if (newAction == null) {
throw new IllegalArgumentException("newAction == null");
}
- malformAction = newAction;
+ malformedInputAction = newAction;
implOnMalformedInput(newAction);
return this;
}
@@ -685,18 +668,16 @@
if (newAction == null) {
throw new IllegalArgumentException("newAction == null");
}
- unmapAction = newAction;
+ unmappableCharacterAction = newAction;
implOnUnmappableCharacter(newAction);
return this;
}
/**
- * Gets the replacement byte array, which is never null or empty.
- *
- * @return the replacement byte array, cannot be null or empty.
+ * Returns the replacement byte array, which is never null or empty.
*/
public final byte[] replacement() {
- return replace;
+ return replacementBytes;
}
/**
@@ -721,25 +702,25 @@
if (replacement == null) {
throw new IllegalArgumentException("replacement == null");
}
- if (replacement.length == 0 || maxBytes < replacement.length) {
- throw new IllegalArgumentException("bad replacement length: " + replacement.length);
+ if (replacement.length == 0) {
+ throw new IllegalArgumentException("replacement.length == 0");
+ }
+ if (replacement.length > maxBytesPerChar()) {
+ throw new IllegalArgumentException("replacement length > maxBytesPerChar: " +
+ replacement.length + " > " + maxBytesPerChar());
}
if (!isLegalReplacement(replacement)) {
throw new IllegalArgumentException("bad replacement: " + Arrays.toString(replacement));
}
- uncheckedReplaceWith(replacement);
- return this;
- }
-
- private final void uncheckedReplaceWith(byte[] replacement) {
// It seems like a bug, but the RI doesn't clone, and we have tests that check we don't.
- replace = replacement;
- implReplaceWith(replace);
+ this.replacementBytes = replacement;
+ implReplaceWith(replacementBytes);
+ return this;
}
/**
* Resets this encoder. This method will reset the internal status and then
- * calla <code>implReset()</code> to reset any status related to the
+ * calls <code>implReset()</code> to reset any status related to the
* specific charset.
*
* @return this encoder.
@@ -751,13 +732,10 @@
}
/**
- * Gets this encoder's <code>CodingErrorAction</code> when unmappable
+ * Returns this encoder's <code>CodingErrorAction</code> when unmappable
* character occurred during encoding process.
- *
- * @return this encoder's <code>CodingErrorAction</code> when unmappable
- * character occurred during encoding process.
*/
public CodingErrorAction unmappableCharacterAction() {
- return unmapAction;
+ return unmappableCharacterAction;
}
}
diff --git a/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java b/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java
new file mode 100644
index 0000000..cf071ca
--- /dev/null
+++ b/luni/src/main/java/java/nio/charset/CharsetEncoderICU.java
@@ -0,0 +1,262 @@
+/**
+*******************************************************************************
+* Copyright (C) 1996-2006, International Business Machines Corporation and *
+* others. All Rights Reserved. *
+*******************************************************************************
+*
+*******************************************************************************
+*/
+/**
+ * A JNI interface for ICU converters.
+ *
+ *
+ * @author Ram Viswanadha, IBM
+ */
+package java.nio.charset;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.util.HashMap;
+import java.util.Map;
+import libcore.icu.ErrorCode;
+import libcore.icu.NativeConverter;
+import libcore.util.EmptyArray;
+
+final class CharsetEncoderICU extends CharsetEncoder {
+ private static final Map<String, byte[]> DEFAULT_REPLACEMENTS = new HashMap<String, byte[]>();
+ static {
+ // ICU has different default replacements to the RI in some cases. There are many
+ // additional cases, but this covers all the charsets that Java guarantees will be
+ // available, which is where compatibility seems most important. (The RI even uses
+ // the byte corresponding to '?' in ASCII as the replacement byte for charsets where that
+ // byte corresponds to an entirely different character.)
+ // It's odd that UTF-8 doesn't use U+FFFD, given that (unlike ISO-8859-1 and US-ASCII) it
+ // can represent it, but this is what the RI does...
+ byte[] questionMark = new byte[] { (byte) '?' };
+ DEFAULT_REPLACEMENTS.put("UTF-8", questionMark);
+ DEFAULT_REPLACEMENTS.put("ISO-8859-1", questionMark);
+ DEFAULT_REPLACEMENTS.put("US-ASCII", questionMark);
+ }
+
+ private static final int INPUT_OFFSET = 0;
+ private static final int OUTPUT_OFFSET = 1;
+ private static final int INVALID_CHARS = 2;
+ /*
+ * data[INPUT_OFFSET] = on input contains the start of input and on output the number of input chars consumed
+ * data[OUTPUT_OFFSET] = on input contains the start of output and on output the number of output bytes written
+ * data[INVALID_CHARS] = number of invalid chars
+ */
+ private int[] data = new int[3];
+
+ /* handle to the ICU converter that is opened */
+ private long converterHandle=0;
+
+ private char[] input = null;
+ private byte[] output = null;
+
+ private char[] allocatedInput = null;
+ private byte[] allocatedOutput = null;
+
+ // These instance variables are always assigned in the methods before being used. This class
+ // is inherently thread-unsafe so we don't have to worry about synchronization.
+ private int inEnd;
+ private int outEnd;
+ private int ec;
+
+ public static CharsetEncoderICU newInstance(Charset cs, String icuCanonicalName) {
+ // This complexity is necessary to ensure that even if the constructor, superclass
+ // constructor, or call to updateCallback throw, we still free the native peer.
+ long address = 0;
+ try {
+ address = NativeConverter.openConverter(icuCanonicalName);
+ float averageBytesPerChar = NativeConverter.getAveBytesPerChar(address);
+ float maxBytesPerChar = NativeConverter.getMaxBytesPerChar(address);
+ byte[] replacement = makeReplacement(icuCanonicalName, address);
+ CharsetEncoderICU result = new CharsetEncoderICU(cs, averageBytesPerChar, maxBytesPerChar, replacement, address);
+ address = 0; // CharsetEncoderICU has taken ownership; its finalizer will do the free.
+ return result;
+ } finally {
+ if (address != 0) {
+ NativeConverter.closeConverter(address);
+ }
+ }
+ }
+
+ private static byte[] makeReplacement(String icuCanonicalName, long address) {
+ // We have our own map of RI-compatible default replacements (where ICU disagrees)...
+ byte[] replacement = DEFAULT_REPLACEMENTS.get(icuCanonicalName);
+ if (replacement != null) {
+ return replacement.clone();
+ }
+ // ...but fall back to asking ICU.
+ return NativeConverter.getSubstitutionBytes(address);
+ }
+
+ private CharsetEncoderICU(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement, long address) {
+ super(cs, averageBytesPerChar, maxBytesPerChar, replacement, true);
+ // Our native peer needs to know what just happened...
+ this.converterHandle = address;
+ updateCallback();
+ }
+
+ @Override protected void implReplaceWith(byte[] newReplacement) {
+ updateCallback();
+ }
+
+ @Override protected void implOnMalformedInput(CodingErrorAction newAction) {
+ updateCallback();
+ }
+
+ @Override protected void implOnUnmappableCharacter(CodingErrorAction newAction) {
+ updateCallback();
+ }
+
+ private void updateCallback() {
+ ec = NativeConverter.setCallbackEncode(converterHandle, this);
+ if (ErrorCode.isFailure(ec)) {
+ throw ErrorCode.throwException(ec);
+ }
+ }
+
+ @Override protected void implReset() {
+ NativeConverter.resetCharToByte(converterHandle);
+ data[INPUT_OFFSET] = 0;
+ data[OUTPUT_OFFSET] = 0;
+ data[INVALID_CHARS] = 0;
+ output = null;
+ input = null;
+ allocatedInput = null;
+ allocatedOutput = null;
+ ec = 0;
+ inEnd = 0;
+ outEnd = 0;
+ }
+
+ @Override protected CoderResult implFlush(ByteBuffer out) {
+ try {
+ // ICU needs to see an empty input.
+ input = EmptyArray.CHAR;
+ inEnd = 0;
+ data[INPUT_OFFSET] = 0;
+
+ data[OUTPUT_OFFSET] = getArray(out);
+ data[INVALID_CHARS] = 0; // Make sure we don't see earlier errors.
+
+ ec = NativeConverter.encode(converterHandle, input, inEnd, output, outEnd, data, true);
+ if (ErrorCode.isFailure(ec)) {
+ if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
+ return CoderResult.OVERFLOW;
+ } else if (ec == ErrorCode.U_TRUNCATED_CHAR_FOUND) {
+ if (data[INPUT_OFFSET] > 0) {
+ return CoderResult.malformedForLength(data[INPUT_OFFSET]);
+ }
+ } else {
+ throw ErrorCode.throwException(ec);
+ }
+ }
+ return CoderResult.UNDERFLOW;
+ } finally {
+ setPosition(out);
+ implReset();
+ }
+ }
+
+ @Override protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
+ if (!in.hasRemaining()) {
+ return CoderResult.UNDERFLOW;
+ }
+
+ data[INPUT_OFFSET] = getArray(in);
+ data[OUTPUT_OFFSET]= getArray(out);
+ data[INVALID_CHARS] = 0; // Make sure we don't see earlier errors.
+
+ try {
+ ec = NativeConverter.encode(converterHandle, input, inEnd, output, outEnd, data, false);
+ if (ErrorCode.isFailure(ec)) {
+ if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
+ return CoderResult.OVERFLOW;
+ } else if (ec == ErrorCode.U_INVALID_CHAR_FOUND) {
+ return CoderResult.unmappableForLength(data[INVALID_CHARS]);
+ } else if (ec == ErrorCode.U_ILLEGAL_CHAR_FOUND) {
+ return CoderResult.malformedForLength(data[INVALID_CHARS]);
+ } else {
+ throw new AssertionError("unexpected failure: " + ec);
+ }
+ }
+ // Decoding succeeded: give us more data.
+ return CoderResult.UNDERFLOW;
+ } finally {
+ setPosition(in);
+ setPosition(out);
+ }
+ }
+
+ public boolean canEncode(char c) {
+ return canEncode((int) c);
+ }
+
+ public boolean canEncode(int codePoint) {
+ return NativeConverter.canEncode(converterHandle, codePoint);
+ }
+
+ @Override protected void finalize() throws Throwable {
+ try {
+ NativeConverter.closeConverter(converterHandle);
+ converterHandle=0;
+ } finally {
+ super.finalize();
+ }
+ }
+
+ private int getArray(ByteBuffer out) {
+ if (out.hasArray()) {
+ output = out.array();
+ outEnd = out.arrayOffset() + out.limit();
+ return out.arrayOffset() + out.position();
+ } else {
+ outEnd = out.remaining();
+ if (allocatedOutput == null || outEnd > allocatedOutput.length) {
+ allocatedOutput = new byte[outEnd];
+ }
+ // The array's start position is 0
+ output = allocatedOutput;
+ return 0;
+ }
+ }
+
+ private int getArray(CharBuffer in) {
+ if (in.hasArray()) {
+ input = in.array();
+ inEnd = in.arrayOffset() + in.limit();
+ return in.arrayOffset() + in.position();
+ } else {
+ inEnd = in.remaining();
+ if (allocatedInput == null || inEnd > allocatedInput.length) {
+ allocatedInput = new char[inEnd];
+ }
+ // Copy the input buffer into the allocated array.
+ int pos = in.position();
+ in.get(allocatedInput, 0, inEnd);
+ in.position(pos);
+ // The array's start position is 0
+ input = allocatedInput;
+ return 0;
+ }
+ }
+
+ private void setPosition(ByteBuffer out) {
+ if (out.hasArray()) {
+ out.position(out.position() + data[OUTPUT_OFFSET] - out.arrayOffset());
+ } else {
+ out.put(output, 0, data[OUTPUT_OFFSET]);
+ }
+ // release reference to output array, which may not be ours
+ output = null;
+ }
+
+ private void setPosition(CharBuffer in) {
+ in.position(in.position() + data[INPUT_OFFSET] - data[INVALID_CHARS]);
+ // release reference to input array, which may not be ours
+ input = null;
+ }
+}
diff --git a/luni/src/main/java/libcore/icu/CharsetICU.java b/luni/src/main/java/java/nio/charset/CharsetICU.java
similarity index 85%
rename from luni/src/main/java/libcore/icu/CharsetICU.java
rename to luni/src/main/java/java/nio/charset/CharsetICU.java
index ac84e6c..63e3fe1 100644
--- a/luni/src/main/java/libcore/icu/CharsetICU.java
+++ b/luni/src/main/java/java/nio/charset/CharsetICU.java
@@ -7,13 +7,11 @@
*******************************************************************************
*/
-package libcore.icu;
+package java.nio.charset;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
+import libcore.icu.NativeConverter;
-public final class CharsetICU extends Charset {
+final class CharsetICU extends Charset {
private final String icuCanonicalName;
protected CharsetICU(String canonicalName, String icuCanonName, String[] aliases) {
diff --git a/luni/src/main/java/java/nio/charset/spi/CharsetProvider.java b/luni/src/main/java/java/nio/charset/spi/CharsetProvider.java
index d24bebd..c3ed3c8 100644
--- a/luni/src/main/java/java/nio/charset/spi/CharsetProvider.java
+++ b/luni/src/main/java/java/nio/charset/spi/CharsetProvider.java
@@ -23,22 +23,10 @@
* The service provider class for character sets.
*/
public abstract class CharsetProvider {
-
- // The permission required to construct a new provider.
- private static final RuntimePermission CONSTRUCT_PERM = new RuntimePermission(
- "charsetProvider");
-
/**
* Constructor for subclassing with concrete types.
- *
- * @throws SecurityException
- * if there is a security manager installed that does not permit
- * the runtime permission labeled "charsetProvider".
*/
protected CharsetProvider() {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null)
- securityManager.checkPermission(CONSTRUCT_PERM);
}
/**
diff --git a/luni/src/main/java/java/security/AccessControlContext.java b/luni/src/main/java/java/security/AccessControlContext.java
index b161b7f..0da6fd5 100644
--- a/luni/src/main/java/java/security/AccessControlContext.java
+++ b/luni/src/main/java/java/security/AccessControlContext.java
@@ -56,10 +56,6 @@
/**
* Constructs a new instance of {@code AccessControlContext} with the
* specified {@code AccessControlContext} and {@code DomainCombiner}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this constructor
- * need the {@code SecurityPermission} {@code createAccessControlContext} to
- * be granted, otherwise a {@code SecurityException} will be thrown.
*
* @param acc
* the {@code AccessControlContext} related to the given {@code
@@ -67,19 +63,10 @@
* @param combiner
* the {@code DomainCombiner} related to the given {@code
* AccessControlContext}
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this constructor
* @throws NullPointerException
* if {@code acc} is {@code null}
*/
- public AccessControlContext(AccessControlContext acc,
- DomainCombiner combiner) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SecurityPermission(
- "createAccessControlContext"));
- }
+ public AccessControlContext(AccessControlContext acc, DomainCombiner combiner) {
// no need to clone() here as ACC is immutable
this.context = acc.context;
this.combiner = combiner;
@@ -119,44 +106,6 @@
}
/**
- * Package-level ctor which is used in AccessController.<br>
- * ProtectionDomains passed as <code>stack</code> is then passed into
- * {@link #AccessControlContext(ProtectionDomain[])}, therefore:<br>
- * <il>
- * <li>it must not be null
- * <li>duplicates will be removed
- * <li>null-s will be removed
- * </li>
- *
- * @param stack - array of ProtectionDomains
- * @param inherited - inherited context, which may be null
- */
- AccessControlContext(ProtectionDomain[] stack,
- AccessControlContext inherited) {
- this(stack); // removes dups, removes nulls, checks for stack==null
- this.inherited = inherited;
- }
-
- /**
- * Package-level ctor which is used in AccessController.<br>
- * ProtectionDomains passed as <code>stack</code> is then passed into
- * {@link #AccessControlContext(ProtectionDomain[])}, therefore:<br>
- * <il>
- * <li>it must not be null
- * <li>duplicates will be removed
- * <li>null-s will be removed
- * </li>
- *
- * @param stack - array of ProtectionDomains
- * @param combiner - combiner
- */
- AccessControlContext(ProtectionDomain[] stack,
- DomainCombiner combiner) {
- this(stack); // removes dups, removes nulls, checks for stack==null
- this.combiner = combiner;
- }
-
- /**
* Checks the specified permission against the vm's current security policy.
* The check is based on this {@code AccessControlContext} as opposed to the
* {@link AccessController#checkPermission(Permission)} method which
@@ -189,8 +138,7 @@
}
for (int i = 0; i < context.length; i++) {
if (!context[i].implies(perm)) {
- throw new AccessControlException("Permission check failed "
- + perm, perm);
+ throw new AccessControlException("Permission check failed " + perm, perm);
}
}
if (inherited != null) {
@@ -223,12 +171,10 @@
.matchSubset(that.context, context))) {
return false;
}
- // BEGIN android-changed
if (combiner != null) {
return combiner.equals(that.combiner);
}
return that.combiner == null;
- // END android-changed
}
return false;
}
@@ -236,22 +182,11 @@
/**
* Returns the {@code DomainCombiner} associated with this {@code
* AccessControlContext}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code getDomainCombiner} to be granted,
- * otherwise a {@code SecurityException} will be thrown.
*
* @return the {@code DomainCombiner} associated with this {@code
* AccessControlContext}
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method
*/
public DomainCombiner getDomainCombiner() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SecurityPermission("getDomainCombiner"));
- }
return combiner;
}
diff --git a/luni/src/main/java/java/security/AccessController.java b/luni/src/main/java/java/security/AccessController.java
index d395592..99ec698 100644
--- a/luni/src/main/java/java/security/AccessController.java
+++ b/luni/src/main/java/java/security/AccessController.java
@@ -32,234 +32,66 @@
package java.security;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.WeakHashMap;
-import org.apache.harmony.security.fortress.SecurityUtils;
-
/**
- * {@code AccessController} provides static methods to perform access control
- * checks and privileged operations.
+ * Legacy security code; this class exists for compatibility only.
*/
public final class AccessController {
private AccessController() {
- throw new Error("statics only.");
}
/**
- * A map used to store a mapping between a given Thread and
- * AccessControllerContext-s used in successive calls of doPrivileged(). A
- * WeakHashMap is used to allow automatic wiping of the dead threads from
- * the map. The thread (normally Thread.currentThread()) is used as a key
- * for the map, and a value is ArrayList where all AccessControlContext-s
- * are stored.
- * ((ArrayList)contexts.get(Thread.currentThread())).lastElement() - is
- * reference to the latest context passed to the doPrivileged() call.
- *
- * TODO: ThreadLocal?
- */
- private static final WeakHashMap<Thread, ArrayList<AccessControlContext>> contexts = new WeakHashMap<Thread, ArrayList<AccessControlContext>>();
-
- /**
- * Returns the result of executing the specified privileged action. Only the
- * {@code ProtectionDomain} of the direct caller of this method and the
- * {@code ProtectionDomain}s of all subsequent classes in the call chain are
- * checked to be granted the necessary permission if access checks are
- * performed.
- * <p>
- * If an instance of {@code RuntimeException} is thrown during the execution
- * of the {@code PrivilegedAction#run()} method of the given action, it will
- * be propagated through this method.
- *
- * @param action
- * the action to be executed with privileges
- * @return the result of executing the privileged action
- * @throws NullPointerException
- * if the specified action is {@code null}
+ * Calls {@code action.run()}.
*/
public static <T> T doPrivileged(PrivilegedAction<T> action) {
- if (action == null) {
- throw new NullPointerException("action == null");
- }
- return doPrivileged(action, null);
+ return action.run();
}
/**
- * Returns the result of executing the specified privileged action. The
- * {@code ProtectionDomain} of the direct caller of this method, the {@code
- * ProtectionDomain}s of all subsequent classes in the call chain and all
- * {@code ProtectionDomain}s of the given context are checked to be granted
- * the necessary permission if access checks are performed.
- * <p>
- * If an instance of {@code RuntimeException} is thrown during the execution
- * of the {@code PrivilegedAction#run()} method of the given action, it will
- * be propagated through this method.
- *
- * @param action
- * the action to be executed with privileges
- * @param context
- * the {@code AccessControlContext} whose protection domains are
- * checked additionally
- * @return the result of executing the privileged action
- * @throws NullPointerException
- * if the specified action is {@code null}
+ * Calls {@code action.run()}.
*/
- public static <T> T doPrivileged(PrivilegedAction<T> action,
- AccessControlContext context) {
- if (action == null) {
- throw new NullPointerException("action == null");
- }
- List<AccessControlContext> contextsStack = contextsForThread();
- contextsStack.add(context);
- try {
- return action.run();
- } finally {
- contextsStack.remove(contextsStack.size() - 1);
- }
+ public static <T> T doPrivileged(PrivilegedAction<T> action, AccessControlContext context) {
+ return action.run();
}
/**
- * Returns the result of executing the specified privileged action. Only the
- * {@code ProtectionDomain} of the direct caller of this method and the
- * {@code ProtectionDomain}s of all subsequent classes in the call chain are
- * checked to be granted the necessary permission if access checks are
- * performed.
- * <p>
- * If a checked exception is thrown by the action's run method, it will be
- * wrapped and propagated through this method.
- * <p>
- * If an instance of {@code RuntimeException} is thrown during the execution
- * of the {@code PrivilegedAction#run()} method of the given action, it will
- * be propagated through this method.
- *
- * @param action
- * the action to be executed with privileges
- * @return the result of executing the privileged action
- * @throws PrivilegedActionException
- * if the action's run method throws any checked exception
- * @throws NullPointerException
- * if the specified action is {@code null}
+ * Calls {@code action.run()}.
*/
- public static <T> T doPrivileged(PrivilegedExceptionAction<T> action)
- throws PrivilegedActionException {
- return doPrivileged(action, null);
- }
-
- /**
- * Returns the result of executing the specified privileged action. The
- * {@code ProtectionDomain} of the direct caller of this method, the {@code
- * ProtectionDomain}s of all subsequent classes in the call chain and all
- * {@code ProtectionDomain}s of the given context are checked to be granted
- * the necessary permission if access checks are performed.
- * <p>
- * If a checked exception is thrown by the action's run method, it will be
- * wrapped and propagated through this method.
- * <p>
- * If an instance of {@code RuntimeException} is thrown during the execution
- * of the {@code PrivilegedAction#run()} method of the given action, it will
- * be propagated through this method.
- *
- * @param action
- * the action to be executed with privileges
- * @param context
- * the {@code AccessControlContext} whose protection domains are
- * checked additionally
- * @return the result of executing the privileged action
- * @throws PrivilegedActionException
- * if the action's run method throws any checked exception
- * @throws NullPointerException
- * if the specified action is {@code null}
- */
- public static <T> T doPrivileged(PrivilegedExceptionAction<T> action,
- AccessControlContext context) throws PrivilegedActionException {
- if (action == null) {
- throw new NullPointerException("action == null");
- }
- List<AccessControlContext> contextsStack = contextsForThread();
- contextsStack.add(context);
+ public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException {
try {
return action.run();
} catch (RuntimeException e) {
throw e; // so we don't wrap RuntimeExceptions with PrivilegedActionException
} catch (Exception e) {
throw new PrivilegedActionException(e);
- } finally {
- contextsStack.remove(contextsStack.size() - 1);
- }
- }
-
- public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action) {
- return doPrivileged(action, newContextSameDomainCombiner());
- }
-
- public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action)
- throws PrivilegedActionException {
- return doPrivileged(action, newContextSameDomainCombiner());
- }
-
- private static AccessControlContext newContextSameDomainCombiner() {
- List<AccessControlContext> contextsStack = contextsForThread();
- DomainCombiner domainCombiner = contextsStack.isEmpty()
- ? null
- : contextsStack.get(contextsStack.size() - 1).getDomainCombiner();
- return new AccessControlContext(new ProtectionDomain[0], domainCombiner);
- }
-
- private static List<AccessControlContext> contextsForThread() {
- Thread currThread = Thread.currentThread();
-
- /*
- * Thread.currentThread() is null when Thread.class is being initialized, and contexts is
- * null when AccessController.class is still being initialized. In either case, return an
- * empty list so callers need not worry.
- */
- if (currThread == null || contexts == null) {
- return new ArrayList<AccessControlContext>();
- }
-
- synchronized (contexts) {
- ArrayList<AccessControlContext> result = contexts.get(currThread);
- if (result == null) {
- result = new ArrayList<AccessControlContext>();
- contexts.put(currThread, result);
- }
- return result;
}
}
/**
- * Checks the specified permission against the VM's current security policy.
- * The check is performed in the context of the current thread. This method
- * returns silently if the permission is granted, otherwise an {@code
- * AccessControlException} is thrown.
- * <p>
- * A permission is considered granted if every {@link ProtectionDomain} in
- * the current execution context has been granted the specified permission.
- * If privileged operations are on the execution context, only the {@code
- * ProtectionDomain}s from the last privileged operation are taken into
- * account.
- * <p>
- * This method delegates the permission check to
- * {@link AccessControlContext#checkPermission(Permission)} on the current
- * callers' context obtained by {@link #getContext()}.
- *
- * @param permission
- * the permission to check against the policy
- * @throws AccessControlException
- * if the specified permission is not granted
- * @throws NullPointerException
- * if the specified permission is {@code null}
- * @see AccessControlContext#checkPermission(Permission)
- *
+ * Calls {@code action.run()}.
*/
- public static void checkPermission(Permission permission)
- throws AccessControlException {
- if (permission == null) {
- throw new NullPointerException("permission == null");
- }
+ public static <T> T doPrivileged(PrivilegedExceptionAction<T> action, AccessControlContext context) throws PrivilegedActionException {
+ return doPrivileged(action);
+ }
- getContext().checkPermission(permission);
+ /**
+ * Calls {@code action.run()}.
+ */
+ public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action) {
+ return action.run();
+ }
+
+ /**
+ * Calls {@code action.run()}.
+ */
+ public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action) throws PrivilegedActionException {
+ return doPrivileged(action);
+ }
+
+ /**
+ * Does nothing.
+ */
+ public static void checkPermission(Permission permission) throws AccessControlException {
}
/**
@@ -283,36 +115,7 @@
* @see Thread#currentThread
*/
public static AccessControlContext getContext() {
-
- // duplicates (if any) will be removed in ACC constructor
- ProtectionDomain[] stack = getStackDomains();
-
- Thread currentThread = Thread.currentThread();
- if (currentThread == null || AccessController.contexts == null) {
- // Big boo time. No need to check anything ?
- return new AccessControlContext(stack);
- }
-
- List<AccessControlContext> threadContexts = contextsForThread();
-
- // if we're in a doPrivileged method, use its context.
- AccessControlContext that = threadContexts.isEmpty()
- ? SecurityUtils.getContext(currentThread)
- : threadContexts.get(threadContexts.size() - 1);
-
- if (that != null && that.combiner != null) {
- ProtectionDomain[] assigned = null;
- if (that.context != null && that.context.length != 0) {
- assigned = new ProtectionDomain[that.context.length];
- System.arraycopy(that.context, 0, assigned, 0, assigned.length);
- }
- ProtectionDomain[] protectionDomains = that.combiner.combine(stack, assigned);
- if (protectionDomains == null) {
- protectionDomains = new ProtectionDomain[0];
- }
- return new AccessControlContext(protectionDomains, that.combiner);
- }
-
- return new AccessControlContext(stack, that);
+ // TODO: just return null?
+ return new AccessControlContext(getStackDomains());
}
}
diff --git a/luni/src/main/java/java/security/AllPermissionCollection.java b/luni/src/main/java/java/security/AllPermissionCollection.java
index 121e891..ee1c22c 100644
--- a/luni/src/main/java/java/security/AllPermissionCollection.java
+++ b/luni/src/main/java/java/security/AllPermissionCollection.java
@@ -35,8 +35,9 @@
private static final long serialVersionUID = -4023755556366636806L;
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "all_allowed", Boolean.TYPE), };
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("all_allowed", boolean.class),
+ };
// Single element of collection.
private transient Permission all;
@@ -67,7 +68,7 @@
* An auxiliary implementation for enumerating a single object.
*
*/
- final static class SingletonEnumeration<E> implements Enumeration<E> {
+ static final class SingletonEnumeration<E> implements Enumeration<E> {
private E element;
diff --git a/luni/src/main/java/java/security/AuthProvider.java b/luni/src/main/java/java/security/AuthProvider.java
index 70dd842..47b262c 100644
--- a/luni/src/main/java/java/security/AuthProvider.java
+++ b/luni/src/main/java/java/security/AuthProvider.java
@@ -50,11 +50,6 @@
/**
* Performs a login into this {@code AuthProvider}. The specified {@code
* CallbackHandler} is used to obtain information from the caller.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code authProvider.NAME} (where NAME is
- * the provider name) to be granted, otherwise a {@code SecurityException}
- * will be thrown.
*
* @param subject
* the subject that is used to login.
@@ -63,25 +58,14 @@
* caller.
* @throws LoginException
* if the login fails.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public abstract void login(Subject subject, CallbackHandler handler) throws LoginException;
/**
* Performs a logout from this {@code AuthProvider}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code authProvider.NAME} (where NAME is
- * the provider name) to be granted, otherwise a {@code SecurityException}
- * will be thrown.
*
* @throws LoginException
* if the logout fails.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public abstract void logout() throws LoginException;
@@ -93,18 +77,10 @@
* If no handler is set, this {@code AuthProvider} uses the {@code
* CallbackHandler} specified by the {@code
* auth.login.defaultCallbackHandler} security property.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code authProvider.NAME} (where NAME is
- * the provider name) to be granted, otherwise a {@code SecurityException}
- * will be thrown.
*
* @param handler
* the handler to obtain authentication information from the
* caller.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public abstract void setCallbackHandler(CallbackHandler handler);
}
diff --git a/luni/src/main/java/java/security/BasicPermission.java b/luni/src/main/java/java/security/BasicPermission.java
index 50e3d30..9bc59ac 100644
--- a/luni/src/main/java/java/security/BasicPermission.java
+++ b/luni/src/main/java/java/security/BasicPermission.java
@@ -21,23 +21,7 @@
import java.io.Serializable;
/**
- * {@code BasicPermission} is the common base class of all permissions which
- * have a name but no action lists. A {@code BasicPermission} is granted or it
- * is not.
- * <p>
- * Names of a BasicPermission follow the dot separated, hierarchical property
- * naming convention. Asterisk '*' can be used as wildcards. Either by itself,
- * matching anything, or at the end of the name, immediately preceded by a '.'.
- * For example:
- *
- * <pre>
- * java.io.* grants all permissions under the java.io permission hierarchy
- * * grants all permissions
- * </pre>
- * <p>
- * While this class ignores the action list in the
- * {@link #BasicPermission(String, String)} constructor, subclasses may
- * implement actions on top of this class.
+ * Legacy security code; this class exists for compatibility only.
*/
public abstract class BasicPermission extends Permission implements
Serializable {
diff --git a/luni/src/main/java/java/security/BasicPermissionCollection.java b/luni/src/main/java/java/security/BasicPermissionCollection.java
index 2df0095..fae3854 100644
--- a/luni/src/main/java/java/security/BasicPermissionCollection.java
+++ b/luni/src/main/java/java/security/BasicPermissionCollection.java
@@ -41,9 +41,10 @@
private static final long serialVersionUID = 739301742472979399L;
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("all_allowed", Boolean.TYPE),
+ new ObjectStreamField("all_allowed", boolean.class),
new ObjectStreamField("permissions", Hashtable.class),
- new ObjectStreamField("permClass", Class.class), };
+ new ObjectStreamField("permClass", Class.class),
+ };
//should be final, but because of writeObject() cannot be
private transient Map<String, Permission> items = new HashMap<String, Permission>();
diff --git a/luni/src/main/java/java/security/DomainCombiner.java b/luni/src/main/java/java/security/DomainCombiner.java
index 520ad93..374f0eb 100644
--- a/luni/src/main/java/java/security/DomainCombiner.java
+++ b/luni/src/main/java/java/security/DomainCombiner.java
@@ -18,12 +18,7 @@
package java.security;
/**
- * {@code DomainCombiner} is used to update and optimize {@code
- * ProtectionDomain}s from an {@code AccessControlContext}.
- *
- * @see AccessControlContext
- * @see AccessControlContext#AccessControlContext(AccessControlContext,
- * DomainCombiner)
+ * Legacy security code; this class exists for compatibility only.
*/
public interface DomainCombiner {
@@ -33,15 +28,11 @@
* duplicates and perform other optimizations.
*
* @param current
- * the protection domains of the current execution thread (since
- * the most recent call to {@link AccessController#doPrivileged}
- * ).
+ * the protection domains of the current execution thread
* @param assigned
- * the protection domains of the parent thread, maybe {@code
- * null}.
+ * the protection domains of the parent thread, may be {@code null}.
* @return a single {@code ProtectionDomain} array computed from the two
* provided arrays.
*/
- ProtectionDomain[] combine(ProtectionDomain[] current,
- ProtectionDomain[] assigned);
+ ProtectionDomain[] combine(ProtectionDomain[] current, ProtectionDomain[] assigned);
}
diff --git a/luni/src/main/java/java/security/Identity.java b/luni/src/main/java/java/security/Identity.java
index 536d77b..6e5b8a3 100644
--- a/luni/src/main/java/java/security/Identity.java
+++ b/luni/src/main/java/java/security/Identity.java
@@ -82,25 +82,13 @@
/**
* Adds a {@code Certificate} to this {@code Identity}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code addIdentityCertificate} to be
- * granted, otherwise a {@code SecurityException} will be thrown.
*
* @param certificate
* the {@code Certificate} to be added to this {@code Identity}.
* @throws KeyManagementException
* if the certificate is not valid.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
- public void addCertificate(Certificate certificate)
- throws KeyManagementException {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("addIdentityCertificate");
- }
+ public void addCertificate(Certificate certificate) throws KeyManagementException {
PublicKey certPK = certificate.getPublicKey();
if (publicKey != null) {
if (!checkKeysEqual(publicKey, certPK)) {
@@ -141,32 +129,17 @@
/**
* Removes the specified {@code Certificate} from this {@code Identity}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code "removeIdentityCertificate"} to be
- * granted, otherwise a {@code SecurityException} will be thrown.
- * <p>
*
* @param certificate
* the {@code Certificate} to be removed.
* @throws KeyManagementException
* if the certificate is not found.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
- public void removeCertificate(Certificate certificate)
- throws KeyManagementException {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("removeIdentityCertificate");
- }
+ public void removeCertificate(Certificate certificate) throws KeyManagementException {
if (certificates != null) {
- // BEGIN android-added
if (!certificates.contains(certificate)) {
throw new KeyManagementException("Certificate not found");
}
- // END android-added
certificates.removeElement(certificate);
}
}
@@ -254,25 +227,14 @@
/**
* Sets the specified {@code PublicKey} to this {@code Identity}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code setIdentityPublicKey} to be
- * granted, otherwise a {@code SecurityException} will be thrown.
*
* @param key
* the {@code PublicKey} to be set.
* @throws KeyManagementException
* if another {@code Identity} in the same scope as this {@code
* Identity} already has the same {@code PublicKey}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public void setPublicKey(PublicKey key) throws KeyManagementException {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("setIdentityPublicKey");
- }
// this check does not always work
if ((scope != null) && (key != null)) {
Identity i = scope.getIdentity(key);
@@ -302,28 +264,13 @@
/**
* Sets an information string for this {@code Identity}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code setIdentityInfo} to be granted,
- * otherwise a {@code SecurityException} will be thrown.
- *
* @param info
* the information to be set.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public void setInfo(String info) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("setIdentityInfo");
- }
this.info = info;
}
-
-
-
/**
* Returns the information string of this {@code Identity}.
*
@@ -333,9 +280,6 @@
return info;
}
-
-
-
/**
* Compares the specified object with this {@code Identity} for equality and
* returns {@code true} if the specified object is equal, {@code false}
@@ -363,9 +307,6 @@
return identityEquals(i);
}
-
-
-
/**
* Returns the name of this {@code Identity}.
*
@@ -375,9 +316,6 @@
return name;
}
-
-
-
/**
* Returns the hash code value for this {@code Identity}. Returns the same
* hash code for {@code Identity}s that are equal to each other as required
@@ -399,29 +337,14 @@
return hash;
}
-
-
-
/**
* Returns a string containing a concise, human-readable description of the
* this {@code Identity} including its name and its scope.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method
- * needs the {@code SecurityPermission} {@code printIdentity} to be granted,
- * otherwise a {@code SecurityException} will be thrown.
*
* @return a printable representation for this {@code Identity}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
@Override
- @SuppressWarnings("nls")
public String toString() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("printIdentity");
- }
String s = (this.name == null ? "" : this.name);
if (scope != null) {
s += " [" + scope.getName() + "]";
diff --git a/luni/src/main/java/java/security/IdentityScope.java b/luni/src/main/java/java/security/IdentityScope.java
index e5acc96..a590db2 100644
--- a/luni/src/main/java/java/security/IdentityScope.java
+++ b/luni/src/main/java/java/security/IdentityScope.java
@@ -81,11 +81,7 @@
* implementation as fallback, i.e., return null if fails to init an instance.
*/
if (systemScope == null) {
- String className = AccessController.doPrivileged(new PrivilegedAction<String>(){
- public String run() {
- return Security.getProperty("system.scope");
- }
- });
+ String className = Security.getProperty("system.scope");
if(className != null){
try {
systemScope = (IdentityScope) Class.forName(className).newInstance();
@@ -104,10 +100,6 @@
* the scope to set.
*/
protected static void setSystemScope(IdentityScope scope) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("setSystemScope");
- }
systemScope = scope;
}
diff --git a/luni/src/main/java/java/security/KeyFactory.java b/luni/src/main/java/java/security/KeyFactory.java
index 916b697..554885a 100644
--- a/luni/src/main/java/java/security/KeyFactory.java
+++ b/luni/src/main/java/java/security/KeyFactory.java
@@ -98,9 +98,8 @@
* if the requested provider is not available.
* @throws IllegalArgumentException if {@code provider == null || provider.isEmpty()}
*/
- @SuppressWarnings("nls")
public static KeyFactory getInstance(String algorithm, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
+ throws NoSuchAlgorithmException, NoSuchProviderException {
if (provider == null || provider.isEmpty()) {
throw new IllegalArgumentException();
}
diff --git a/luni/src/main/java/java/security/KeyStore.java b/luni/src/main/java/java/security/KeyStore.java
index ab4b924..7e91083 100644
--- a/luni/src/main/java/java/security/KeyStore.java
+++ b/luni/src/main/java/java/security/KeyStore.java
@@ -176,8 +176,7 @@
* NoSuchAlgorithmException) as in 1.4 release
* @see #getDefaultType
*/
- public static KeyStore getInstance(String type, Provider provider)
- throws KeyStoreException {
+ public static KeyStore getInstance(String type, Provider provider) throws KeyStoreException {
// check parameters
if (provider == null) {
throw new IllegalArgumentException();
@@ -197,21 +196,15 @@
/**
* Returns the default type for {@code KeyStore} instances.
- * <p>
- * The default is specified in the {@code 'keystore.type'} property in the
- * file named {@code JAVA_HOME/lib/security/java.security}. If this property
+ *
+ * <p>The default is specified in the {@code 'keystore.type'} property in the
+ * file named {@code java.security} properties file. If this property
* is not set, {@code "jks"} will be used.
*
* @return the default type for {@code KeyStore} instances
*/
public static final String getDefaultType() {
- String dt = AccessController.doPrivileged(
- new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- }
- );
+ String dt = Security.getProperty(PROPERTYNAME);
return (dt == null ? DEFAULT_KEYSTORE_TYPE : dt);
}
@@ -254,9 +247,7 @@
throws KeyStoreException, NoSuchAlgorithmException,
UnrecoverableKeyException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineGetKey(alias, password);
}
@@ -271,12 +262,9 @@
* @throws KeyStoreException
* if this {@code KeyStore} is not initialized.
*/
- public final Certificate[] getCertificateChain(String alias)
- throws KeyStoreException {
+ public final Certificate[] getCertificateChain(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineGetCertificateChain(alias);
}
@@ -291,12 +279,9 @@
* @throws KeyStoreException
* if this {@code KeyStore} is not initialized.
*/
- public final Certificate getCertificate(String alias)
- throws KeyStoreException {
+ public final Certificate getCertificate(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineGetCertificate(alias);
}
@@ -313,9 +298,7 @@
*/
public final Date getCreationDate(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineGetCreationDate(alias);
}
@@ -344,9 +327,7 @@
public final void setKeyEntry(String alias, Key key, char[] password,
Certificate[] chain) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
// Certificate chain is required for PrivateKey
@@ -383,9 +364,7 @@
public final void setKeyEntry(String alias, byte[] key, Certificate[] chain)
throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
implSpi.engineSetKeyEntry(alias, key, chain);
}
@@ -406,12 +385,9 @@
* @throws NullPointerException
* if {@code alias} is {@code null}.
*/
- public final void setCertificateEntry(String alias, Certificate cert)
- throws KeyStoreException {
+ public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
implSpi.engineSetCertificateEntry(alias, cert);
}
@@ -428,9 +404,7 @@
*/
public final void deleteEntry(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
implSpi.engineDeleteEntry(alias);
}
@@ -446,9 +420,7 @@
*/
public final Enumeration<String> aliases() throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineAliases();
}
@@ -464,9 +436,7 @@
*/
public final boolean containsAlias(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineContainsAlias(alias);
}
@@ -480,9 +450,7 @@
*/
public final int size() throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineSize();
}
@@ -499,9 +467,7 @@
*/
public final boolean isKeyEntry(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineIsKeyEntry(alias);
}
@@ -517,12 +483,9 @@
* @throws KeyStoreException
* if this {@code KeyStore} is not initialized.
*/
- public final boolean isCertificateEntry(String alias)
- throws KeyStoreException {
+ public final boolean isCertificateEntry(String alias) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineIsCertificateEntry(alias);
}
@@ -538,12 +501,9 @@
* @throws KeyStoreException
* if this {@code KeyStore} is not initialized.
*/
- public final String getCertificateAlias(Certificate cert)
- throws KeyStoreException {
+ public final String getCertificateAlias(Certificate cert) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineGetCertificateAlias(cert);
}
@@ -568,12 +528,9 @@
* this {@code KeyStore}.
*/
public final void store(OutputStream stream, char[] password)
- throws KeyStoreException, IOException, NoSuchAlgorithmException,
- CertificateException {
+ throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
//Just delegate stream and password to implSpi
@@ -602,9 +559,7 @@
public final void store(LoadStoreParameter param) throws KeyStoreException,
IOException, NoSuchAlgorithmException, CertificateException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
implSpi.engineStore(param);
}
@@ -679,15 +634,12 @@
* if {@code alias} is {@code null}.
*/
public final Entry getEntry(String alias, ProtectionParameter param)
- throws NoSuchAlgorithmException, UnrecoverableEntryException,
- KeyStoreException {
+ throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
if (alias == null) {
throw new NullPointerException("alias == null");
}
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineGetEntry(alias, param);
}
@@ -714,9 +666,7 @@
public final void setEntry(String alias, Entry entry,
ProtectionParameter param) throws KeyStoreException {
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
if (alias == null) {
throw new NullPointerException("alias == null");
@@ -751,9 +701,7 @@
}
if (!isInit) {
- // BEGIN android-changed
throwNotInitialized();
- // END android-changed
}
return implSpi.engineEntryInstanceOf(alias, entryClass);
}
@@ -826,8 +774,7 @@
if (!keyStore.isInit) {
throw new IllegalArgumentException("KeyStore was not initialized");
}
- return new BuilderImpl(keyStore, protectionParameter,
- null, null, null, null);
+ return new BuilderImpl(keyStore, protectionParameter, null, null, null);
}
/**
@@ -887,8 +834,7 @@
throw new IllegalArgumentException("Not a regular file: " + file.getName());
}
// create new instance
- return new BuilderImpl(null, protectionParameter, file,
- type, provider, AccessController.getContext());
+ return new BuilderImpl(null, protectionParameter, file, type, provider);
}
/**
@@ -926,8 +872,7 @@
if (protectionParameter == null) {
throw new NullPointerException("protectionParameter == null");
}
- return new BuilderImpl(null, protectionParameter, null,
- type, provider, AccessController.getContext());
+ return new BuilderImpl(null, protectionParameter, null, type, provider);
}
/*
@@ -958,16 +903,13 @@
// Store last Exception in getKeyStore()
private KeyStoreException lastException;
- // Store AccessControlContext which is used in getKeyStore() method
- private final AccessControlContext accControlContext;
-
/**
* 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) {
super();
keyStore = ks;
protParameter = pp;
@@ -976,7 +918,6 @@
providerForKeyStore = provider;
isGetKeyStore = false;
lastException = null;
- accControlContext = context;
}
/**
@@ -1009,15 +950,13 @@
}
try {
- final KeyStore ks;
- final char[] passwd;
-
// get KeyStore instance using type or type and provider
- ks = (providerForKeyStore == null ? KeyStore
+ final KeyStore ks = (providerForKeyStore == null ? KeyStore
.getInstance(typeForKeyStore) : KeyStore
.getInstance(typeForKeyStore, providerForKeyStore));
// protection parameter should be PasswordProtection
// or CallbackHandlerProtection
+ final char[] passwd;
if (protParameter instanceof PasswordProtection) {
passwd = ((PasswordProtection) protParameter)
.getPassword();
@@ -1030,25 +969,17 @@
}
// load KeyStore from file
- AccessController.doPrivileged(
- new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- if (fileForLoad != null) {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(fileForLoad);
- ks.load(fis, passwd);
- } finally {
- IoUtils.closeQuietly(fis);
- }
- } else {
- ks.load(new TmpLSParameter(
- protParameter));
- }
- return null;
- }
- }, accControlContext);
-
+ if (fileForLoad != null) {
+ FileInputStream fis = null;
+ try {
+ fis = new FileInputStream(fileForLoad);
+ ks.load(fis, passwd);
+ } finally {
+ IoUtils.closeQuietly(fis);
+ }
+ } else {
+ ks.load(new TmpLSParameter(protParameter));
+ }
isGetKeyStore = true;
return ks;
diff --git a/luni/src/main/java/java/security/Permission.java b/luni/src/main/java/java/security/Permission.java
index 60a5c7e..044c01f 100644
--- a/luni/src/main/java/java/security/Permission.java
+++ b/luni/src/main/java/java/security/Permission.java
@@ -20,10 +20,7 @@
import java.io.Serializable;
/**
- * {@code Permission} is the common base class of all permissions that
- * participate in the access control security framework around
- * {@link AccessController} and {@link AccessControlContext}. A permission
- * constitutes of a name and associated actions.
+ * Legacy security code; this class exists for compatibility only.
*/
public abstract class Permission implements Guard, Serializable {
@@ -81,8 +78,6 @@
/**
* Indicates whether the specified permission is implied by this permission.
- * The {@link AccessController} uses this method to check whether permission
- * protected access is allowed with the present policy.
*
* @param permission
* the permission to check against this permission.
@@ -111,23 +106,9 @@
}
/**
- * Invokes {@link SecurityManager#checkPermission(Permission)} with this
- * permission as its argument. This method implements the {@link Guard}
- * interface.
- *
- * @param obj
- * as specified in {@link Guard#checkGuard(Object)} but ignored
- * in this implementation.
- * @throws SecurityException
- * if this permission is not granted.
- * @see Guard
- * @see SecurityManager#checkPermission(Permission)
+ * Does nothing.
*/
public void checkGuard(Object obj) throws SecurityException {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(this);
- }
}
/**
diff --git a/luni/src/main/java/java/security/Permissions.java b/luni/src/main/java/java/security/Permissions.java
index 356a072..88a3414 100644
--- a/luni/src/main/java/java/security/Permissions.java
+++ b/luni/src/main/java/java/security/Permissions.java
@@ -45,7 +45,8 @@
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("perms", Hashtable.class),
- new ObjectStreamField("allPermission", PermissionCollection.class), };
+ new ObjectStreamField("allPermission", PermissionCollection.class),
+ };
// Hash to store PermissionCollection's
private transient Map klasses = new HashMap();
@@ -107,7 +108,7 @@
* collection of PermissionCollections.
*
*/
- final static class MetaEnumeration implements Enumeration {
+ static final class MetaEnumeration implements Enumeration {
private Iterator pcIter;
diff --git a/luni/src/main/java/java/security/Policy.java b/luni/src/main/java/java/security/Policy.java
index 8a5934d..b2887a3 100644
--- a/luni/src/main/java/java/security/Policy.java
+++ b/luni/src/main/java/java/security/Policy.java
@@ -108,9 +108,6 @@
* @throws NoSuchAlgorithmException
* if no Provider supports a PolicySpi implementation for the
* specified type.
- * @throws SecurityException
- * if the caller does not have permission to get a Policy
- * instance for the specified type.
* @throws NullPointerException
* if the specified type is null.
* @throws IllegalArgumentException
@@ -119,8 +116,6 @@
*/
public static Policy getInstance(String type, Policy.Parameters params)
throws NoSuchAlgorithmException {
- checkSecurityPermission(new SecurityPermission(CREATE_POLICY + type));
-
if (type == null) {
throw new NullPointerException();
}
@@ -159,9 +154,6 @@
* @throws NoSuchAlgorithmException
* if the specified provider does not support a PolicySpi
* implementation for the specified type.
- * @throws SecurityException
- * if the caller does not have permission to get a Policy
- * instance for the specified type.
* @throws NullPointerException
* if the specified type is null.
* @throws IllegalArgumentException
@@ -175,7 +167,6 @@
if ((provider == null) || provider.isEmpty()) {
throw new IllegalArgumentException("Provider is null or empty string");
}
- checkSecurityPermission(new SecurityPermission(CREATE_POLICY + type));
Provider impProvider = Security.getProvider(provider);
if (impProvider == null) {
@@ -210,27 +201,15 @@
* implementation from the specified Provider.
* @throws NullPointerException
* if the specified type is null.
- * @throws SecurityException
- * if the caller does not have permission to get a Policy
- * instance for the specified type.
*/
public static Policy getInstance(String type, Policy.Parameters params,
Provider provider) throws NoSuchAlgorithmException {
if (provider == null) {
throw new IllegalArgumentException("provider == null");
}
- checkSecurityPermission(new SecurityPermission(CREATE_POLICY + type));
-
return getInstanceImpl(type, params, provider);
}
- private static void checkSecurityPermission(SecurityPermission permission) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(permission);
- }
- }
-
private static Policy getInstanceImpl(String type, Policy.Parameters params, Provider provider)
throws NoSuchAlgorithmException {
if (type == null) {
@@ -442,18 +421,10 @@
* Returns the current system security policy. If no policy has been
* instantiated then this is done using the security property {@code
* "policy.provider"}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code getPolicy} to be granted, otherwise
- * a {@code SecurityException} will be thrown.
*
* @return the current system security policy.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public static Policy getPolicy() {
- checkSecurityPermission(GET_POLICY);
return getAccessiblePolicy();
}
@@ -462,34 +433,18 @@
// In case of any error, including undefined provider name,
// returns new instance of org.apache.harmony.security.FilePolicy provider.
private static Policy getDefaultProvider() {
- final String defaultClass = AccessController
- .doPrivileged(new PolicyUtils.SecurityPropertyAccessor(
- POLICY_PROVIDER));
+ final String defaultClass = Security.getProperty(POLICY_PROVIDER);
if (defaultClass == null) {
- // TODO log warning
- // System.err.println("No policy provider specified. Loading the "
- // + DefaultPolicy.class.getName());
return new DefaultPolicy();
}
// TODO accurate classloading
- return AccessController.doPrivileged(new PrivilegedAction<Policy>() {
-
- public Policy run() {
- try {
- return (Policy) Class.forName(defaultClass, true,
- ClassLoader.getSystemClassLoader()).newInstance();
- } catch (Exception e) {
- //TODO log error
- //System.err.println("Error loading policy provider <"
- // + defaultClass + "> : " + e
- // + "\nSwitching to the default "
- // + DefaultPolicy.class.getName());
- return new DefaultPolicy();
- }
- }
- });
-
+ try {
+ return (Policy) Class.forName(defaultClass, true,
+ ClassLoader.getSystemClassLoader()).newInstance();
+ } catch (Exception e) {
+ return new DefaultPolicy();
+ }
}
/**
@@ -518,19 +473,10 @@
/**
* Sets the system wide policy.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code setPolicy} to be granted, otherwise
- * a {@code SecurityException} will be thrown.
- *
* @param policy
* the {@code Policy} to set.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public static void setPolicy(Policy policy) {
- checkSecurityPermission(SET_POLICY);
synchronized (Policy.class) {
activePolicy = policy;
}
diff --git a/luni/src/main/java/java/security/PrivilegedAction.java b/luni/src/main/java/java/security/PrivilegedAction.java
index 1dbbe65..d635f58 100644
--- a/luni/src/main/java/java/security/PrivilegedAction.java
+++ b/luni/src/main/java/java/security/PrivilegedAction.java
@@ -18,20 +18,11 @@
package java.security;
/**
- * {@code PrivilegedAction} represents an action that can be executed privileged
- * regarding access control. Instances of {@code PrivilegedAction} can be
- * executed on {@code AccessController.doPrivileged()}.
- *
- * @see AccessController
- * @see AccessController#doPrivileged(PrivilegedAction)
- * @see AccessController#doPrivileged(PrivilegedAction, AccessControlContext)
- * @see PrivilegedExceptionAction
+ * Legacy security code; this class exists for compatibility only.
*/
public interface PrivilegedAction<T> {
/**
* Returns the result of running the action.
- *
- * @return the result of running the action.
*/
public T run();
}
diff --git a/luni/src/main/java/java/security/PrivilegedActionException.java b/luni/src/main/java/java/security/PrivilegedActionException.java
index 7965469..e470ebf 100644
--- a/luni/src/main/java/java/security/PrivilegedActionException.java
+++ b/luni/src/main/java/java/security/PrivilegedActionException.java
@@ -18,21 +18,7 @@
package java.security;
/**
- * {@code PrivilegedActionException} wraps exceptions which are thrown from
- * within privileged operations.
- * <p>
- * Privileged actions which can throw exceptions are of type {@code
- * PrivilegedExceptionAction} and are thrown by
- * <ul>
- * {@code AccessController#doPrivileged(PrivilegedExceptionAction)}<br>
- * {@code AccessController#doPrivileged(PrivilegedExceptionAction,
- * AccessControlContext)} </br>
- * </ul>
- *
- * @see PrivilegedExceptionAction
- * @see AccessController#doPrivileged(PrivilegedExceptionAction)
- * @see AccessController#doPrivileged(PrivilegedExceptionAction,
- * AccessControlContext)
+ * Legacy security code; this class exists for compatibility only.
*/
public class PrivilegedActionException extends Exception {
diff --git a/luni/src/main/java/java/security/PrivilegedExceptionAction.java b/luni/src/main/java/java/security/PrivilegedExceptionAction.java
index bc072d5..a9496ad 100644
--- a/luni/src/main/java/java/security/PrivilegedExceptionAction.java
+++ b/luni/src/main/java/java/security/PrivilegedExceptionAction.java
@@ -18,23 +18,11 @@
package java.security;
/**
- * {@code PrivilegedAction} represents an action, that can be executed
- * privileged regarding access control. Instances of {@code PrivilegedAction}
- * can be executed invoking {@code AccessController.doPrivileged()}.
- *
- * @see AccessController
- * @see AccessController#doPrivileged(PrivilegedExceptionAction)
- * @see AccessController#doPrivileged(PrivilegedExceptionAction,
- * AccessControlContext)
- * @see PrivilegedAction
+ * Legacy security code; this class exists for compatibility only.
*/
public interface PrivilegedExceptionAction<T> {
/**
* Returns the result of running the action.
- *
- * @return the result of running the action
- * @throws Exception
- * if an exception occurred.
*/
T run() throws Exception;
}
diff --git a/luni/src/main/java/java/security/Provider.java b/luni/src/main/java/java/security/Provider.java
index 346d199..2de3751 100644
--- a/luni/src/main/java/java/security/Provider.java
+++ b/luni/src/main/java/java/security/Provider.java
@@ -28,11 +28,11 @@
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.harmony.luni.util.TwoKeyHashMap;
-import org.apache.harmony.security.Util;
import org.apache.harmony.security.fortress.Services;
/**
@@ -149,22 +149,9 @@
/**
* Clears all properties used to look up services implemented by this
* {@code Provider}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code clearProviderProperties.NAME}
- * (where NAME is the provider name) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
- *
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
@Override
public synchronized void clear() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("clearProviderProperties." + name);
- }
super.clear();
if (serviceTable != null) {
serviceTable.clear();
@@ -178,9 +165,7 @@
if (propertyAliasTable != null) {
propertyAliasTable.clear();
}
- // BEGIN android-changed
changedProperties = null;
- // END android-changed
putProviderInfo();
if (providerNumber != -1) {
// if registered then refresh Services
@@ -198,29 +183,11 @@
/**
* Copies all from the provided map to this {@code Provider}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code putProviderProperty.NAME} (where
- * NAME is the provider name) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
- *
* @param t
* the mappings to copy to this provider.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
@Override
public synchronized void putAll(Map<?,?> t) {
-
- // Implementation note:
- // checkSecurityAccess method call is NOT specified
- // Do it as in put(Object key, Object value).
-
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("putProviderProperty." + name);
- }
myPutAll(t);
}
@@ -269,11 +236,6 @@
/**
* Maps the specified {@code key} property name to the specified {@code
* value}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code putProviderProperty.NAME} (where
- * NAME is the provider name) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
*
* @param key
* the name of the property.
@@ -281,16 +243,9 @@
* the value of the property.
* @return the value that was previously mapped to the specified {@code key}
* ,or {@code null} if it did not have one.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
@Override
public synchronized Object put(Object key, Object value) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("putProviderProperty." + name);
- }
if (key instanceof String && ((String) key).startsWith("Provider.")) {
// Provider service type is reserved
return null;
@@ -312,26 +267,14 @@
/**
* Removes the specified {@code key} and its associated value from this
* {@code Provider}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code removeProviderProperty.NAME} (where
- * NAME is the provider name) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
*
* @param key
* the name of the property
* @return the value that was mapped to the specified {@code key} ,or
* {@code null} if no mapping was present
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have the permission to invoke this method.
*/
@Override
public synchronized Object remove(Object key) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("removeProviderProperty." + name);
- }
if (key instanceof String && ((String) key).startsWith("Provider.")) {
// Provider service type is reserved
return null;
@@ -342,11 +285,9 @@
}
if (changedProperties != null && changedProperties.remove(key) == null) {
removeFromPropertyServiceTable(key);
- // BEGIN android-added
if (changedProperties.size() == 0) {
changedProperties = null;
}
- // END android-added
}
return super.remove(key);
}
@@ -385,20 +326,20 @@
return false;
}
- // Returns true if this provider has the same value as is given for the
- // given attribute
+ /**
+ * Returns true if this provider has the same value as is given for the
+ * given attribute
+ */
private boolean checkAttribute(String servAlg, String attribute, String val) {
String attributeValue = getPropertyIgnoreCase(servAlg + ' ' + attribute);
if (attributeValue != null) {
- if (Util.equalsIgnoreCase(attribute,"KeySize")) {
- // BEGIN android-changed
+ if (attribute.equalsIgnoreCase("KeySize")) {
if (Integer.parseInt(attributeValue) >= Integer.parseInt(val)) {
return true;
}
- // END android-changed
} else { // other attributes
- if (Util.equalsIgnoreCase(attributeValue, val)) {
+ if (attributeValue.equalsIgnoreCase(val)) {
return true;
}
}
@@ -469,12 +410,11 @@
throw new NullPointerException();
}
- if (type.equals(lastServiceName)
- && Util.equalsIgnoreCase(algorithm, lastAlgorithm)) {
+ if (type.equals(lastServiceName) && algorithm.equalsIgnoreCase(lastAlgorithm)) {
return returnedService;
}
- String alg = Util.toUpperCase(algorithm);
+ String alg = algorithm.toUpperCase(Locale.US);
Object o = null;
if (serviceTable != null) {
o = serviceTable.get(type, alg);
@@ -528,26 +468,14 @@
/**
* Adds a {@code Service} to this {@code Provider}. If a service with the
* same name was registered via this method, it is replace.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code putProviderProperty.NAME} (where
- * NAME is the provider name) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
*
* @param s
* the {@code Service} to register
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method
*/
protected synchronized void putService(Provider.Service s) {
if (s == null) {
throw new NullPointerException();
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("putProviderProperty." + name);
- }
if ("Provider".equals(s.getType())) { // Provider service type cannot be added
return;
}
@@ -555,13 +483,13 @@
if (serviceTable == null) {
serviceTable = new TwoKeyHashMap<String, String, Service>(128);
}
- serviceTable.put(s.type, Util.toUpperCase(s.algorithm), s);
+ serviceTable.put(s.type, s.algorithm.toUpperCase(Locale.US), s);
if (s.aliases != null) {
if (aliasTable == null) {
aliasTable = new TwoKeyHashMap<String, String, Service>(256);
}
for (String alias : s.getAliases()) {
- aliasTable.put(s.type, Util.toUpperCase(alias), s);
+ aliasTable.put(s.type, alias.toUpperCase(Locale.US), s);
}
}
serviceInfoToProperties(s);
@@ -570,17 +498,9 @@
/**
* Removes a previously registered {@code Service} from this {@code
* Provider}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code removeProviderProperty.NAME} (where
- * NAME is the provider name) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
*
* @param s
* the {@code Service} to remove
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method
* @throws NullPointerException
* if {@code s} is {@code null}
*/
@@ -588,17 +508,13 @@
if (s == null) {
throw new NullPointerException();
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("removeProviderProperty." + name);
- }
servicesChanged();
if (serviceTable != null) {
- serviceTable.remove(s.type, Util.toUpperCase(s.algorithm));
+ serviceTable.remove(s.type, s.algorithm.toUpperCase(Locale.US));
}
if (aliasTable != null && s.aliases != null) {
for (String alias: s.getAliases()) {
- aliasTable.remove(s.type, Util.toUpperCase(alias));
+ aliasTable.remove(s.type, alias.toUpperCase(Locale.US));
}
}
serviceInfoFromProperties(s);
@@ -668,7 +584,7 @@
serviceName = service_alias.substring(0, i);
aliasName = service_alias.substring(i + 1);
if (propertyAliasTable != null) {
- propertyAliasTable.remove(serviceName, Util.toUpperCase(aliasName));
+ propertyAliasTable.remove(serviceName, aliasName.toUpperCase(Locale.US));
}
if (propertyServiceTable != null) {
for (Iterator<Service> it = propertyServiceTable.values().iterator(); it
@@ -693,12 +609,11 @@
algorithm = k.substring(j + 1);
if (propertyServiceTable != null) {
Provider.Service ser = propertyServiceTable.remove(serviceName,
- Util.toUpperCase(algorithm));
+ algorithm.toUpperCase(Locale.US));
if (ser != null && propertyAliasTable != null
&& ser.aliases != null) {
- for (Iterator<String> it = ser.aliases.iterator(); it.hasNext();) {
- propertyAliasTable.remove(serviceName, Util.toUpperCase(it
- .next()));
+ for (String alias : ser.aliases) {
+ propertyAliasTable.remove(serviceName, alias.toUpperCase(Locale.US));
}
}
}
@@ -709,7 +624,7 @@
serviceName = k.substring(0, j);
algorithm = k.substring(j + 1, i);
if (propertyServiceTable != null) {
- Object o = propertyServiceTable.get(serviceName, Util.toUpperCase(algorithm));
+ Object o = propertyServiceTable.get(serviceName, algorithm.toUpperCase(Locale.US));
if (o != null) {
s = (Provider.Service) o;
s.attributes.remove(attribute);
@@ -752,7 +667,7 @@
serviceName = service_alias.substring(0, i);
aliasName = service_alias.substring(i + 1);
algorithm = value;
- String algUp = Util.toUpperCase(algorithm);
+ String algUp = algorithm.toUpperCase(Locale.US);
Object o = null;
if (propertyServiceTable == null) {
propertyServiceTable = new TwoKeyHashMap<String, String, Service>(128);
@@ -761,14 +676,11 @@
}
if (o != null) {
s = (Provider.Service) o;
- // BEGIN android-changed
s.addAlias(aliasName);
- // END android-changed
if (propertyAliasTable == null) {
propertyAliasTable = new TwoKeyHashMap<String, String, Service>(256);
}
- propertyAliasTable.put(serviceName,
- Util.toUpperCase(aliasName), s);
+ propertyAliasTable.put(serviceName, aliasName.toUpperCase(Locale.US), s);
} else {
String className = (String) changedProperties
.get(serviceName + "." + algorithm);
@@ -781,8 +693,7 @@
if (propertyAliasTable == null) {
propertyAliasTable = new TwoKeyHashMap<String, String, Service>(256);
}
- propertyAliasTable.put(serviceName, Util.toUpperCase(aliasName
- ), s);
+ propertyAliasTable.put(serviceName, aliasName.toUpperCase(Locale.US), s);
}
}
continue;
@@ -795,7 +706,7 @@
if (i == -1) { // <crypto_service>.<algorithm_or_type>=<className>
serviceName = key.substring(0, j);
algorithm = key.substring(j + 1);
- String alg = Util.toUpperCase(algorithm);
+ String alg = algorithm.toUpperCase(Locale.US);
Object o = null;
if (propertyServiceTable != null) {
o = propertyServiceTable.get(serviceName, alg);
@@ -804,11 +715,9 @@
s = (Provider.Service) o;
s.className = value;
} else {
- // BEGIN android-changed
s = new Provider.Service(this, serviceName, algorithm,
value, Collections.<String>emptyList(),
Collections.<String,String>emptyMap());
- // END android-changed
if (propertyServiceTable == null) {
propertyServiceTable = new TwoKeyHashMap<String, String, Service>(128);
}
@@ -821,16 +730,14 @@
serviceName = key.substring(0, j);
algorithm = key.substring(j + 1, i);
String attribute = key.substring(i + 1);
- String alg = Util.toUpperCase(algorithm);
+ String alg = algorithm.toUpperCase(Locale.US);
Object o = null;
if (propertyServiceTable != null) {
o = propertyServiceTable.get(serviceName, alg);
}
if (o != null) {
s = (Provider.Service) o;
- // BEGIN android-changed
s.putAttribute(attribute, value);
- // END android-changed
} else {
String className = (String) changedProperties
.get(serviceName + "." + algorithm);
@@ -848,9 +755,7 @@
}
}
servicesChanged();
- // BEGIN android-changed
changedProperties = null;
- // END android-changed
}
private void servicesChanged() {
@@ -864,7 +769,6 @@
* Provider.id name, Provider.id version, Provider.id info,
* Provider.id className
*/
- @SuppressWarnings("nls")
private void putProviderInfo() {
super.put("Provider.id name", (name != null) ? name : "null");
super.put("Provider.id version", versionString);
@@ -873,21 +777,18 @@
}
/**
- * Searches for the property with the specified key in the
- * provider properties. Key is not case-sensitive.
- *
- * @param prop
- * @return the property value with the specified key value.
+ * Returns the property with the specified key in the provider properties.
+ * The name is not case-sensitive.
*/
private String getPropertyIgnoreCase(String key) {
String res = getProperty(key);
if (res != null) {
return res;
}
- for (Enumeration<?> e = propertyNames(); e.hasMoreElements();) {
- String pname = (String) e.nextElement();
- if (Util.equalsIgnoreCase(key, pname)) {
- return getProperty(pname);
+ for (Enumeration<?> e = propertyNames(); e.hasMoreElements(); ) {
+ String propertyName = (String) e.nextElement();
+ if (key.equalsIgnoreCase(propertyName)) {
+ return getProperty(propertyName);
}
}
return null;
@@ -956,16 +857,13 @@
this.type = type;
this.algorithm = algorithm;
this.className = className;
- // BEGIN android-changed
this.aliases = ((aliases != null) && (aliases.size() == 0))
? Collections.<String>emptyList() : aliases;
this.attributes =
((attributes != null) && (attributes.size() == 0))
? Collections.<String,String>emptyMap() : attributes;
- // END android-changed
}
- // BEGIN android-added
/**
* Adds an alias.
*
@@ -990,7 +888,6 @@
}
attributes.put(name, value);
}
- // END android-added
/**
* Returns the type of this {@code Service}. For example {@code
@@ -1074,31 +971,17 @@
* if the implementation does not support the specified
* {@code constructorParameter}.
*/
- public Object newInstance(Object constructorParameter)
- throws NoSuchAlgorithmException {
+ public Object newInstance(Object constructorParameter) throws NoSuchAlgorithmException {
if (implementation == null || !className.equals(lastClassName)) {
- NoSuchAlgorithmException result = AccessController
- .doPrivileged(new PrivilegedAction<NoSuchAlgorithmException>() {
- public NoSuchAlgorithmException run() {
- ClassLoader cl = provider.getClass()
- .getClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- implementation = Class.forName(className,
- true, cl);
- } catch (Exception e) {
- return new NoSuchAlgorithmException(
- type + " " + algorithm
- + " implementation not found: " + e);
- }
- lastClassName = className;
- return null;
- }
- });
- if (result != null) {
- throw result;
+ ClassLoader cl = provider.getClass().getClassLoader();
+ if (cl == null) {
+ cl = ClassLoader.getSystemClassLoader();
+ }
+ try {
+ implementation = Class.forName(className, true, cl);
+ lastClassName = className;
+ } catch (Exception e) {
+ throw new NoSuchAlgorithmException(type + " " + algorithm + " implementation not found: " + e);
}
}
if (constructorParameter == null) {
@@ -1116,9 +999,8 @@
Class[] parameterTypes = new Class[1];
Object[] initargs = { constructorParameter };
try {
- if (Util.equalsIgnoreCase(type,"CertStore")) {
- parameterTypes[0] = Class
- .forName("java.security.cert.CertStoreParameters");
+ if (type.equalsIgnoreCase("CertStore")) {
+ parameterTypes[0] = Class.forName("java.security.cert.CertStoreParameters");
} else {
parameterTypes[0] = constructorParameter.getClass();
}
diff --git a/luni/src/main/java/java/security/SecureClassLoader.java b/luni/src/main/java/java/security/SecureClassLoader.java
index bca7207..f0be669 100644
--- a/luni/src/main/java/java/security/SecureClassLoader.java
+++ b/luni/src/main/java/java/security/SecureClassLoader.java
@@ -33,14 +33,6 @@
/**
* Constructs a new instance of {@code SecureClassLoader}. The default
* parent {@code ClassLoader} is used.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this constructor
- * needs the {@code SecurityPermission} {@code checkCreateClassLoader} to be
- * granted, otherwise a {@code SecurityException} will be thrown.
- *
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this constructor.
*/
protected SecureClassLoader() {
super();
@@ -49,16 +41,9 @@
/**
* Constructs a new instance of {@code SecureClassLoader} with the specified
* parent {@code ClassLoader}.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this constructor
- * needs the {@code SecurityPermission} {@code checkCreateClassLoader} to be
- * granted, otherwise a {@code SecurityException} will be thrown.
*
* @param parent
* the parent {@code ClassLoader}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this constructor.
*/
protected SecureClassLoader(ClassLoader parent) {
super(parent);
diff --git a/luni/src/main/java/java/security/Security.java b/luni/src/main/java/java/security/Security.java
index 65b5a3e..db28264 100644
--- a/luni/src/main/java/java/security/Security.java
+++ b/luni/src/main/java/java/security/Security.java
@@ -31,7 +31,6 @@
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
-import org.apache.harmony.security.Util;
import org.apache.harmony.security.fortress.Engine;
import org.apache.harmony.security.fortress.SecurityAccess;
import org.apache.harmony.security.fortress.Services;
@@ -51,70 +50,20 @@
// - load statically registered providers
// - if no provider description file found then load default providers
static {
- AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
- public Void run() {
- boolean loaded = false;
-
- // BEGIN android-added
- /*
- * Android only uses a local "security.properties" resource
- * for configuration. TODO: Reevaluate this decision.
- */
- try {
- InputStream configStream =
- getClass().getResourceAsStream("security.properties");
- InputStream input = new BufferedInputStream(configStream);
- secprops.load(input);
- loaded = true;
- configStream.close();
- } catch (Exception ex) {
- Logger.global.log(Level.SEVERE,
- "Could not load Security properties.", ex);
- }
- // END android-added
-
- // BEGIN android-removed
-// if (Util.equalsIgnoreCase("true", secprops.getProperty("security.allowCustomPropertiesFile", "true"))) {
-// String securityFile = System.getProperty("java.security.properties");
-// if (securityFile != null) {
-// if (securityFile.startsWith("=")) { // overwrite
-// secprops = new Properties();
-// loaded = false;
-// securityFile = securityFile.substring(1);
-// }
-// try {
-// securityFile = PolicyUtils.expand(securityFile, System.getProperties());
-// } catch (PolicyUtils.ExpansionFailedException e) {
-//// System.err.println("Could not load custom Security properties file "
-//// + securityFile +": " + e);
-// }
-// f = new File(securityFile);
-// InputStream is;
-// try {
-// if (f.exists()) {
-// FileInputStream fis = new FileInputStream(f);
-// is = new BufferedInputStream(fis);
-// } else {
-// URL url = new URL(securityFile);
-// is = new BufferedInputStream(url.openStream());
-// }
-// secprops.load(is);
-// loaded = true;
-// is.close();
-// } catch (IOException e) {
-// // System.err.println("Could not load custom Security properties file "
-// // + securityFile +": " + e);
-// }
-// }
-// }
- // END android-removed
- if (!loaded) {
- registerDefaultProviders();
- }
- Engine.door = new SecurityDoor();
- return null;
- }
- });
+ boolean loaded = false;
+ try {
+ InputStream configStream = Security.class.getResourceAsStream("security.properties");
+ InputStream input = new BufferedInputStream(configStream);
+ secprops.load(input);
+ loaded = true;
+ configStream.close();
+ } catch (Exception ex) {
+ Logger.global.log(Level.SEVERE, "Could not load Security properties.", ex);
+ }
+ if (!loaded) {
+ registerDefaultProviders();
+ }
+ Engine.door = new SecurityDoor();
}
/**
@@ -148,16 +97,13 @@
if (algName == null || propName == null) {
return null;
}
- // BEGIN android-changed
String prop = "Alg." + propName + "." + algName;
- // END android-changed
Provider[] providers = getProviders();
- for (int i = 0; i < providers.length; i++) {
- for (Enumeration e = providers[i].propertyNames(); e
- .hasMoreElements();) {
- String pname = (String) e.nextElement();
- if (Util.equalsIgnoreCase(prop, pname)) {
- return providers[i].getProperty(pname);
+ for (Provider provider : providers) {
+ for (Enumeration e = provider.propertyNames(); e.hasMoreElements(); ) {
+ String propertyName = (String) e.nextElement();
+ if (propertyName.equalsIgnoreCase(prop)) {
+ return provider.getProperty(propertyName);
}
}
}
@@ -168,11 +114,6 @@
* Insert the given {@code Provider} at the specified {@code position}. The
* positions define the preference order in which providers are searched for
* requested algorithms.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code insertProvider.NAME} (where NAME is
- * the provider name) to be granted, otherwise a {@code SecurityException}
- * will be thrown.
*
* @param provider
* the provider to insert.
@@ -181,20 +122,12 @@
* @return the actual position or {@code -1} if the given {@code provider}
* was already in the list. The actual position may be different
* from the desired position.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
- public static synchronized int insertProviderAt(Provider provider,
- int position) {
- // check security access; check that provider is not already
+ public static synchronized int insertProviderAt(Provider provider, int position) {
+ // check that provider is not already
// installed, else return -1; if (position <1) or (position > max
// position) position = max position + 1; insert provider, shift up
// one position for next providers; Note: The position is 1-based
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("insertProvider." + provider.getName());
- }
if (getProvider(provider.getName()) != null) {
return -1;
}
@@ -206,19 +139,11 @@
/**
* Adds the given {@code provider} to the collection of providers at the
* next available position.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code insertProvider.NAME} (where NAME is
- * the provider name) to be granted, otherwise a {@code SecurityException}
- * will be thrown.
*
* @param provider
* the provider to be added.
* @return the actual position or {@code -1} if the given {@code provider}
* was already in the list.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public static int addProvider(Provider provider) {
return insertProviderAt(provider, 0);
@@ -229,20 +154,12 @@
* of providers. If the the {@code Provider} with the specified name is
* removed, all provider at a greater position are shifted down one
* position.
- * <p>
- * Returns silently if {@code name} is {@code null} or no provider with the
+ *
+ * <p>Returns silently if {@code name} is {@code null} or no provider with the
* specified name is installed.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code removeProvider.NAME} (where NAME is
- * the provider name) to be granted, otherwise a {@code SecurityException}
- * will be thrown.
*
* @param name
* the name of the provider to remove.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public static synchronized void removeProvider(String name) {
// It is not clear from spec.:
@@ -259,10 +176,6 @@
if (p == null) {
return;
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("removeProvider." + name);
- }
Services.removeProvider(p.getProviderNumber());
renumProviders();
p.setProviderNumber(-1);
@@ -418,27 +331,15 @@
/**
* Returns the value of the security property named by the argument.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code getProperty.KEY} (where KEY is the
- * specified {@code key}) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
*
* @param key
* the name of the requested security property.
* @return the value of the security property.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
public static String getProperty(String key) {
if (key == null) {
throw new NullPointerException("key == null");
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("getProperty." + key);
- }
String property = secprops.getProperty(key);
if (property != null) {
property = property.trim();
@@ -448,26 +349,9 @@
/**
* Sets the value of the specified security property.
- * <p>
- * If a {@code SecurityManager} is installed, code calling this method needs
- * the {@code SecurityPermission} {@code setProperty.KEY} (where KEY is the
- * specified {@code key}) to be granted, otherwise a {@code
- * SecurityException} will be thrown.
- *
- * @param key
- * the name of the security property.
- * @param datnum
- * the value of the security property.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
- public static void setProperty(String key, String datnum) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("setProperty." + key);
- }
- secprops.put(key, datnum);
+ public static void setProperty(String key, String value) {
+ secprops.put(key, value);
}
/**
@@ -484,18 +368,14 @@
*/
public static Set<String> getAlgorithms(String serviceName) {
Set<String> result = new HashSet<String>();
- // BEGIN android-added
// compatibility with RI
if (serviceName == null) {
return result;
}
- // END android-added
- Provider[] p = getProviders();
- for (int i = 0; i < p.length; i++) {
- for (Iterator it = p[i].getServices().iterator(); it.hasNext();) {
- Provider.Service s = (Provider.Service) it.next();
- if (Util.equalsIgnoreCase(s.getType(),serviceName)) {
- result.add(s.getAlgorithm());
+ for (Provider provider : getProviders()) {
+ for (Provider.Service service: provider.getServices()) {
+ if (service.getType().equalsIgnoreCase(serviceName)) {
+ result.add(service.getAlgorithm());
}
}
}
diff --git a/luni/src/main/java/java/security/Signer.java b/luni/src/main/java/java/security/Signer.java
index 58f8c04..9981ae0 100644
--- a/luni/src/main/java/java/security/Signer.java
+++ b/luni/src/main/java/java/security/Signer.java
@@ -61,36 +61,19 @@
* if a signer with the specified name already exists in the
* provided scope.
*/
- public Signer(String name, IdentityScope scope)
- throws KeyManagementException {
+ public Signer(String name, IdentityScope scope) throws KeyManagementException {
super(name, scope);
}
/**
- * Returns the private key of this {@code Signer}. If a {@code
- * SecurityManager} is installed, code calling this method needs the {@code
- * SecurityPermission} {@code "getSignerPrivateKey"} to be granted, otherwise
- * a {@code SecurityException} will be thrown.
- *
- * @return the private key of this {@code Signer}.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
+ * Returns the private key of this {@code Signer}.
*/
public PrivateKey getPrivateKey() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("getSignerPrivateKey");
- }
-
return privateKey;
}
/**
- * Associates the specified key pair with this {@code Signer}. If a {@code
- * SecurityManager} is installed, code calling this method needs the {@code
- * SecurityPermission} {@code getSignerPrivateKey} to be granted, otherwise
- * a {@code SecurityException} will be thrown.
+ * Associates the specified key pair with this {@code Signer}.
*
* @param pair
* the key pair to associate with this {@code Signer}.
@@ -98,35 +81,16 @@
* if the key pair is invalid.
* @throws KeyException
* if any other key related problem occurs.
- * @throws SecurityException
- * if a {@code SecurityManager} is installed and the caller does
- * not have permission to invoke this method.
*/
- public final void setKeyPair(KeyPair pair)
- throws InvalidParameterException, KeyException {
-
+ public final void setKeyPair(KeyPair pair) throws InvalidParameterException, KeyException {
if (pair == null) {
throw new NullPointerException();
}
- if ((pair.getPrivate() == null) || (pair.getPublic() == null)) {
+ if (pair.getPrivate() == null || pair.getPublic() == null) {
throw new InvalidParameterException();
}
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkSecurityAccess("setSignerKeyPair");
- }
- final PublicKey pk = pair.getPublic();
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
- public Void run() throws KeyManagementException {
- setPublicKey(pk);
- return null;
- }
- });
- } catch (PrivilegedActionException e) {
- throw new KeyException(e.getException());
- }
+ setPublicKey(pair.getPublic());
this.privateKey = pair.getPrivate();
}
diff --git a/luni/src/main/java/java/security/UnresolvedPermissionCollection.java b/luni/src/main/java/java/security/UnresolvedPermissionCollection.java
index de7175c..4a9dc19 100644
--- a/luni/src/main/java/java/security/UnresolvedPermissionCollection.java
+++ b/luni/src/main/java/java/security/UnresolvedPermissionCollection.java
@@ -43,7 +43,8 @@
private static final long serialVersionUID = -7176153071733132400L;
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("permissions", Hashtable.class), };
+ new ObjectStreamField("permissions", Hashtable.class),
+ };
// elements of the collection.
private transient Map klasses = new HashMap();
diff --git a/luni/src/main/java/java/security/cert/CertPath.java b/luni/src/main/java/java/security/cert/CertPath.java
index dda778f..d247d30 100644
--- a/luni/src/main/java/java/security/cert/CertPath.java
+++ b/luni/src/main/java/java/security/cert/CertPath.java
@@ -116,15 +116,12 @@
sb.append(getCertificates().size());
sb.append(": [\n");
int n=1;
- // BEGIN android-changed
- for (Iterator<? extends Certificate> i=getCertificates().iterator();
- i.hasNext(); n++) {
+ for (Iterator<? extends Certificate> i=getCertificates().iterator(); i.hasNext(); n++) {
sb.append("---------------certificate ");
sb.append(n);
sb.append("---------------\n");
sb.append(((Certificate)i.next()).toString());
}
- // END android-changed
sb.append("\n]");
return sb.toString();
}
@@ -197,8 +194,8 @@
// Force default serialization to use writeUnshared/readUnshared
// for cert path data
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("type", String.class),
- new ObjectStreamField("data", byte[].class, true)
+ new ObjectStreamField("type", String.class),
+ new ObjectStreamField("data", byte[].class, true),
};
/**
diff --git a/luni/src/main/java/java/security/cert/CertPathBuilder.java b/luni/src/main/java/java/security/cert/CertPathBuilder.java
index c2164db..aa65fe7 100644
--- a/luni/src/main/java/java/security/cert/CertPathBuilder.java
+++ b/luni/src/main/java/java/security/cert/CertPathBuilder.java
@@ -17,7 +17,6 @@
package java.security.cert;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
@@ -193,12 +192,7 @@
* determined.
*/
public static final String getDefaultType() {
- String defaultType = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- });
+ String defaultType = Security.getProperty(PROPERTYNAME);
return (defaultType != null ? defaultType : DEFAULTPROPERTY);
}
}
diff --git a/luni/src/main/java/java/security/cert/CertPathValidator.java b/luni/src/main/java/java/security/cert/CertPathValidator.java
index 49d2408..69b9f99 100644
--- a/luni/src/main/java/java/security/cert/CertPathValidator.java
+++ b/luni/src/main/java/java/security/cert/CertPathValidator.java
@@ -17,7 +17,6 @@
package java.security.cert;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
@@ -200,12 +199,7 @@
* determined.
*/
public static final String getDefaultType() {
- String defaultType = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- });
+ String defaultType = Security.getProperty(PROPERTYNAME);
return (defaultType != null ? defaultType : DEFAULTPROPERTY);
}
}
diff --git a/luni/src/main/java/java/security/cert/CertStore.java b/luni/src/main/java/java/security/cert/CertStore.java
index a8cbfee..6cdaea7 100644
--- a/luni/src/main/java/java/security/cert/CertStore.java
+++ b/luni/src/main/java/java/security/cert/CertStore.java
@@ -17,7 +17,6 @@
package java.security.cert;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
@@ -267,12 +266,7 @@
* determined.
*/
public static final String getDefaultType() {
- String defaultType = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- });
+ String defaultType = Security.getProperty(PROPERTYNAME);
return (defaultType == null ? DEFAULTPROPERTY : defaultType);
}
}
diff --git a/luni/src/main/java/java/security/cert/PKIXCertPathChecker.java b/luni/src/main/java/java/security/cert/PKIXCertPathChecker.java
index 0991cd5..869efb5 100644
--- a/luni/src/main/java/java/security/cert/PKIXCertPathChecker.java
+++ b/luni/src/main/java/java/security/cert/PKIXCertPathChecker.java
@@ -55,7 +55,7 @@
try {
return super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/security/cert/PKIXCertPathValidatorResult.java b/luni/src/main/java/java/security/cert/PKIXCertPathValidatorResult.java
index e3bdca6..99f26a2 100644
--- a/luni/src/main/java/java/security/cert/PKIXCertPathValidatorResult.java
+++ b/luni/src/main/java/java/security/cert/PKIXCertPathValidatorResult.java
@@ -96,7 +96,7 @@
try {
return super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/security/cert/PKIXParameters.java b/luni/src/main/java/java/security/cert/PKIXParameters.java
index 2e9d4a2..7ca9443 100644
--- a/luni/src/main/java/java/security/cert/PKIXParameters.java
+++ b/luni/src/main/java/java/security/cert/PKIXParameters.java
@@ -534,7 +534,7 @@
}
return ret;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/security/cert/X509CertSelector.java b/luni/src/main/java/java/security/cert/X509CertSelector.java
index 5b36cb4..2981f63 100644
--- a/luni/src/main/java/java/security/cert/X509CertSelector.java
+++ b/luni/src/main/java/java/security/cert/X509CertSelector.java
@@ -26,12 +26,12 @@
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
import libcore.util.EmptyArray;
import org.apache.harmony.security.asn1.ASN1OctetString;
+import org.apache.harmony.security.utils.Array;
import org.apache.harmony.security.x509.AlgorithmIdentifier;
import org.apache.harmony.security.x509.CertificatePolicies;
import org.apache.harmony.security.x509.GeneralName;
@@ -61,13 +61,13 @@
private Date privateKeyValid;
private byte[] subjectPublicKey;
private boolean[] keyUsage;
- private Set extendedKeyUsage;
+ private Set<String> extendedKeyUsage;
private boolean matchAllNames = true;
private int pathLen = -1;
- private List[] subjectAltNames;
+ private List<GeneralName>[] subjectAltNames;
private NameConstraints nameConstraints;
private Set<String> policies;
- private ArrayList pathToNames;
+ private ArrayList<GeneralName> pathToNames;
// needed to avoid needless encoding/decoding work
private PublicKey subjectPublicKeyImpl;
@@ -593,10 +593,8 @@
if ((keyUsage == null) || (keyUsage.size() == 0)) {
return;
}
- HashSet key_u = new HashSet();
- Iterator it = keyUsage.iterator();
- while (it.hasNext()) {
- String usage = (String) it.next();
+ HashSet<String> key_u = new HashSet<String>();
+ for (String usage : keyUsage) {
checkOID(usage);
key_u.add(usage);
}
@@ -660,16 +658,13 @@
* @throws IOException
* if the decoding of a name fails.
*/
- public void setSubjectAlternativeNames(Collection<List<?>> names)
- throws IOException {
+ public void setSubjectAlternativeNames(Collection<List<?>> names) throws IOException {
subjectAltNames = null;
if ((names == null) || (names.size() == 0)) {
return;
}
- Iterator it = names.iterator();
- while (it.hasNext()) {
- List name = (List) it.next();
- int tag = ((Integer) name.get(0)).intValue();
+ for (List<?> name : names) {
+ int tag = (Integer) name.get(0);
Object value = name.get(1);
if (value instanceof String) {
addSubjectAlternativeName(tag, (String) value);
@@ -699,7 +694,7 @@
subjectAltNames = new ArrayList[9];
}
if (subjectAltNames[tag] == null) {
- subjectAltNames[tag] = new ArrayList();
+ subjectAltNames[tag] = new ArrayList<GeneralName>();
}
subjectAltNames[tag].add(alt_name);
}
@@ -722,7 +717,7 @@
subjectAltNames = new ArrayList[9];
}
if (subjectAltNames[tag] == null) {
- subjectAltNames[tag] = new ArrayList();
+ subjectAltNames[tag] = new ArrayList<GeneralName>();
}
subjectAltNames[tag].add(alt_name);
}
@@ -745,19 +740,13 @@
if (subjectAltNames == null) {
return null;
}
- ArrayList result = new ArrayList();
+ ArrayList<List<?>> result = new ArrayList<List<?>>();
for (int tag=0; tag<9; tag++) {
if (subjectAltNames[tag] != null) {
for (int name=0; name<subjectAltNames[tag].size(); name++) {
- Object neim = subjectAltNames[tag].get(name);
- if (neim instanceof byte[]) {
- byte[] arr_neim = (byte[]) neim;
- neim = new byte[arr_neim.length];
- System.arraycopy(arr_neim, 0, neim, 0, arr_neim.length);
- }
- List list = new ArrayList(2);
- list.add(Integer.valueOf(tag)); // android-changed
- list.add(neim);
+ List<Object> list = new ArrayList<Object>(2);
+ list.add(tag);
+ list.add(subjectAltNames[tag].get(name));
result.add(list);
}
}
@@ -877,9 +866,7 @@
return;
}
HashSet<String> pols = new HashSet<String>(policies.size());
- Iterator<String> it = policies.iterator();
- while (it.hasNext()) {
- String certPolicyId = it.next();
+ for (String certPolicyId : policies) {
checkOID(certPolicyId);
pols.add(certPolicyId);
}
@@ -901,6 +888,26 @@
}
/**
+ * Adds a {@literal "pathToName"} to the respective criterion.
+ *
+ * @param type
+ * the type of the name.
+ * @param name
+ * the name in string format.
+ * @throws IOException
+ * if parsing fails.
+ * @see #setPathToNames
+ */
+ public void addPathToName(int type, String name) throws IOException {
+ GeneralName path_name = new GeneralName(type, name);
+ // create only if there was not any errors
+ if (pathToNames == null) {
+ pathToNames = new ArrayList<GeneralName>();
+ }
+ pathToNames.add(path_name);
+ }
+
+ /**
* Sets the criterion for the pathToNames constraint.
* <p>
* This allows to specify the complete set of names, a certificate's name
@@ -923,10 +930,8 @@
if ((names == null) || (names.size() == 0)) {
return;
}
- Iterator it = names.iterator();
- while (it.hasNext()) {
- List name = (List) it.next();
- int tag = ((Integer) name.get(0)).intValue();
+ for (List<?> name : names) {
+ int tag = (Integer) name.get(0);
Object value = name.get(1);
if (value instanceof String) {
addPathToName(tag, (String) value);
@@ -942,26 +947,6 @@
* Adds a {@literal "pathToName"} to the respective criterion.
*
* @param type
- * the type of the name.
- * @param name
- * the name in string format.
- * @throws IOException
- * if parsing fails.
- * @see #setPathToNames
- */
- public void addPathToName(int type, String name) throws IOException {
- GeneralName path_name = new GeneralName(type, name);
- // create only if there was not any errors
- if (pathToNames == null) {
- pathToNames = new ArrayList();
- }
- pathToNames.add(path_name);
- }
-
- /**
- * Adds a {@literal "pathToName"} to the respective criterion.
- *
- * @param type
* the type of the name
* @param name
* the name in ASN.1 DER encoded form.
@@ -973,7 +958,7 @@
GeneralName path_name= new GeneralName(type, name);
// create only if there was not any errors
if (pathToNames == null) {
- pathToNames = new ArrayList();
+ pathToNames = new ArrayList<GeneralName>();
}
pathToNames.add(path_name);
}
@@ -992,10 +977,8 @@
if (pathToNames == null) {
return null;
}
- ArrayList result = new ArrayList();
- Iterator it = pathToNames.iterator();
- while (it.hasNext()) {
- GeneralName name = (GeneralName) it.next();
+ Collection<List<?>> result = new ArrayList<List<?>>();
+ for (GeneralName name : pathToNames) {
result.add(name.getAsList());
}
return result;
@@ -1016,39 +999,37 @@
StringBuilder result = new StringBuilder();
result.append("X509CertSelector: \n[");
if (this.certificateEquals != null) {
- result.append("\n certificateEquals: " + certificateEquals);
+ result.append("\n certificateEquals: ").append(certificateEquals);
}
if (this.serialNumber != null) {
- //FIXME: needs DRL's BigInteger.toString implementation
- //result.append("\n serialNumber: " + serialNumber);
+ result.append("\n serialNumber: ").append(serialNumber);
}
if (this.issuer != null) {
- result.append("\n issuer: " + issuer);
+ result.append("\n issuer: ").append(issuer);
}
if (this.subject != null) {
- result.append("\n subject: " + subject);
+ result.append("\n subject: ").append(subject);
}
if (this.subjectKeyIdentifier != null) {
- result.append("\n subjectKeyIdentifier: "
- + getBytesAsString(subjectKeyIdentifier));
+ result.append("\n subjectKeyIdentifier: ")
+ .append(Array.getBytesAsString(subjectKeyIdentifier));
}
if (this.authorityKeyIdentifier != null) {
- result.append("\n authorityKeyIdentifier: "
- + getBytesAsString(authorityKeyIdentifier));
+ result.append("\n authorityKeyIdentifier: ")
+ .append(Array.getBytesAsString(authorityKeyIdentifier));
}
if (this.certificateValid != null) {
- result.append("\n certificateValid: " + certificateValid);
+ result.append("\n certificateValid: ").append(certificateValid);
}
if (this.subjectPublicKeyAlgID != null) {
- result.append("\n subjectPublicKeyAlgID: "
- + subjectPublicKeyAlgID);
+ result.append("\n subjectPublicKeyAlgID: ").append(subjectPublicKeyAlgID);
}
if (this.privateKeyValid != null) {
- result.append("\n privateKeyValid: " + privateKeyValid);
+ result.append("\n privateKeyValid: ").append(privateKeyValid);
}
if (this.subjectPublicKey != null) {
- result.append("\n subjectPublicKey: "
- + getBytesAsString(subjectPublicKey));
+ result.append("\n subjectPublicKey: ")
+ .append(Array.getBytesAsString(subjectPublicKey));
}
if (this.keyUsage != null) {
result.append("\n keyUsage: \n [");
@@ -1059,26 +1040,24 @@
};
for (int i=0; i<9; i++) {
if (keyUsage[i]) {
- result.append("\n " + kuNames[i]);
+ result.append("\n ").append(kuNames[i]);
}
}
result.append("\n ]");
}
if (this.extendedKeyUsage != null) {
- result.append("\n extendedKeyUsage: "
- + extendedKeyUsage.toString());
+ result.append("\n extendedKeyUsage: ").append(extendedKeyUsage.toString());
}
- result.append("\n matchAllNames: " + matchAllNames);
- result.append("\n pathLen: " + pathLen);
+ result.append("\n matchAllNames: ").append(matchAllNames);
+ result.append("\n pathLen: ").append(pathLen);
if (this.subjectAltNames != null) {
result.append("\n subjectAltNames: \n [");
for (int i=0; i<9; i++) {
- List names = this.subjectAltNames[i];
+ List<GeneralName> names = subjectAltNames[i];
if (names != null) {
int size = names.size();
- for (int j=0; j<size; j++) {
- result.append("\n "
- + ((GeneralName)names.get(j)).toString());
+ for (GeneralName generalName : names) {
+ result.append("\n ").append(generalName.toString());
}
}
}
@@ -1087,32 +1066,18 @@
if (this.nameConstraints != null) {
}
if (this.policies != null) {
- result.append("\n policies: " + policies.toString());
+ result.append("\n policies: ").append(policies.toString());
}
if (this.pathToNames != null) {
result.append("\n pathToNames: \n [");
- int size = pathToNames.size();
- for (int i = 0; i < size; i++) {
- result.append("\n "
- + ((GeneralName)pathToNames.get(i)).toString());
+ for (GeneralName generalName : pathToNames) {
+ result.append("\n ").append(generalName.toString());
}
}
result.append("\n]");
return result.toString();
}
- private String getBytesAsString(byte[] data) {
- String result = "";
- for (int i=0; i<data.length; i++) {
- String tail = Integer.toHexString(0x00ff & data[i]);
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- result += tail + " ";
- }
- return result;
- }
-
private byte[] getExtensionValue(X509Certificate cert, String oid) {
try {
byte[] bytes = cert.getExtensionValue(oid);
@@ -1272,7 +1237,7 @@
if (bytes == null) {
return false;
}
- List sans = ((GeneralNames) GeneralNames.ASN1.decode(bytes))
+ List<GeneralName> sans = ((GeneralNames) GeneralNames.ASN1.decode(bytes))
.getNames();
if ((sans == null) || (sans.size() == 0)) {
return false;
@@ -1283,13 +1248,10 @@
map[i] = (subjectAltNames[i] == null)
? EmptyArray.BOOLEAN : new boolean[subjectAltNames[i].size()];
}
- Iterator it = sans.iterator();
- while (it.hasNext()) {
- GeneralName name = (GeneralName) it.next();
+ for (GeneralName name : sans) {
int tag = name.getTag();
- for (int i=0; i<map[tag].length; i++) {
- if (((GeneralName) subjectAltNames[tag].get(i))
- .equals(name)) {
+ for (int i = 0; i < map[tag].length; i++) {
+ if (subjectAltNames[tag].get(i).equals(name)) {
if (!matchAllNames) {
break PASSED;
}
@@ -1331,13 +1293,11 @@
}
PASSED:
try {
- List policyInformations = ((CertificatePolicies)
- CertificatePolicies.ASN1.decode(bytes))
+ List<PolicyInformation> policyInformations
+ = ((CertificatePolicies) CertificatePolicies.ASN1.decode(bytes))
.getPolicyInformations();
- Iterator it = policyInformations.iterator();
- while (it.hasNext()) {
- if (policies.contains(((PolicyInformation) it.next())
- .getPolicyIdentifier())) {
+ for (PolicyInformation policyInformation : policyInformations) {
+ if (policies.contains(policyInformation.getPolicyIdentifier())) {
break PASSED;
}
}
@@ -1406,20 +1366,20 @@
}
result.extendedKeyUsage = (this.extendedKeyUsage == null)
? null
- : new HashSet(this.extendedKeyUsage);
+ : new HashSet<String>(this.extendedKeyUsage);
if (this.subjectAltNames != null) {
result.subjectAltNames = new ArrayList[9];
for (int i=0; i<9; i++) {
if (this.subjectAltNames[i] != null) {
result.subjectAltNames[i] =
- new ArrayList(this.subjectAltNames[i]);
+ new ArrayList<GeneralName>(this.subjectAltNames[i]);
}
}
}
result.policies = (this.policies == null) ? null : new HashSet<String>(this.policies);
result.pathToNames = (this.pathToNames == null)
? null
- : new ArrayList(this.pathToNames);
+ : new ArrayList<GeneralName>(this.pathToNames);
return result;
}
}
diff --git a/luni/src/main/java/java/security/package.html b/luni/src/main/java/java/security/package.html
index 4c5e2b4..b2e7e08 100644
--- a/luni/src/main/java/java/security/package.html
+++ b/luni/src/main/java/java/security/package.html
@@ -4,32 +4,9 @@
</head>
<html>
<body>
-<p>This package provides all the classes and interfaces that
-constitute the Java security framework. The content of this package can
-be divided into two parts:
-
-<ul>
- <li>Classes implementing the access control infrastructure.
- <p>The central class is <i>java.security.AccessController</i>
- which checks if code, invoking sensitive resources, was granted the required
- permissions.
- <p>The class loader (<i>java.security.SecureClassLoader</i>) associates classes
- with a protection domain (<i>java.security.ProtectionDomain</i>) which consists of a
- code source (<i>java.security.CodeSource</i>) and the granted permissions
- (<i>java.security.Permission</i>). The policy, defined through <i>java.security.Policy</i>, defines
- which permissions are granted to classes loaded from a code source ( class
- <i>java.security.CodeSource</i>).
- <li>Classes and interfaces for the extensible cryptographic
- <i>service provider infrastructure</i> (<b>SPI</b>) such as abstractions for certificates,
- signatures, private and public keys. Also abstractions for the algorithms
- they utilize are provided in this package.
- <p>Security providers, as defined in <i>java.security.Providers</i>, can be
- registered to provide
- different implementations for a variety of security infrastructure,
- such as key stores. Therefore the corresponding
- service provider interface (i.e. <i>java.security.KeyStoreSpi</i>) must be
- implemented.
-</ul>
+<p>This package is for compatibility
+with legacy code only, and should not be used or expected to do
+anything useful.
</p>
</body>
</html>
diff --git a/luni/src/main/java/java/sql/DriverManager.java b/luni/src/main/java/java/sql/DriverManager.java
index 77fe43f..3dc0ed3 100644
--- a/luni/src/main/java/java/sql/DriverManager.java
+++ b/luni/src/main/java/java/sql/DriverManager.java
@@ -20,14 +20,12 @@
import dalvik.system.VMStack;
import java.io.PrintStream;
import java.io.PrintWriter;
-import java.security.AccessController;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
-import java.util.Vector;
-import org.apache.harmony.luni.util.PriviAction;
/**
* Provides facilities for managing JDBC drivers.
@@ -70,9 +68,7 @@
* it is defined.
*/
private static void loadInitialDrivers() {
- String theDriverList = AccessController
- .doPrivileged(new PriviAction<String>("jdbc.drivers", null));
-
+ String theDriverList = System.getProperty("jdbc.drivers", null);
if (theDriverList == null) {
return;
}
@@ -225,23 +221,17 @@
* if there is any kind of problem accessing the database.
*/
public static Driver getDriver(String url) throws SQLException {
- // BEGIN android-changed
ClassLoader callerClassLoader = VMStack.getCallingClassLoader();
- // END android-changed
-
synchronized (theDrivers) {
/*
* Loop over the drivers in the DriverSet checking to see if one
* does understand the supplied URL - return the first driver which
* does understand the URL
*/
- Iterator<Driver> theIterator = theDrivers.iterator();
- while (theIterator.hasNext()) {
- Driver theDriver = theIterator.next();
- if (theDriver.acceptsURL(url)
- && DriverManager.isClassFromClassLoader(theDriver,
- callerClassLoader)) {
- return theDriver;
+ for (Driver driver : theDrivers) {
+ if (driver.acceptsURL(url) &&
+ DriverManager.isClassFromClassLoader(driver, callerClassLoader)) {
+ return driver;
}
}
}
@@ -259,28 +249,19 @@
* {@code Drivers}.
*/
public static Enumeration<Driver> getDrivers() {
- // BEGIN android-changed
- ClassLoader callerClassLoader = VMStack.getCallingClassLoader();
- // END android-changed
/*
* Synchronize to avoid clashes with additions and removals of drivers
* in the DriverSet
*/
+ ClassLoader callerClassLoader = VMStack.getCallingClassLoader();
synchronized (theDrivers) {
- /*
- * Create the Enumeration by building a Vector from the elements of
- * the DriverSet
- */
- Vector<Driver> theVector = new Vector<Driver>();
- Iterator<Driver> theIterator = theDrivers.iterator();
- while (theIterator.hasNext()) {
- Driver theDriver = theIterator.next();
- if (DriverManager.isClassFromClassLoader(theDriver,
- callerClassLoader)) {
- theVector.add(theDriver);
+ ArrayList<Driver> result = new ArrayList<Driver>();
+ for (Driver driver : theDrivers) {
+ if (DriverManager.isClassFromClassLoader(driver, callerClassLoader)) {
+ result.add(driver);
}
}
- return theVector.elements();
+ return Collections.enumeration(result);
}
}
@@ -378,7 +359,6 @@
*/
@Deprecated
public static void setLogStream(PrintStream out) {
- checkLogSecurity();
thePrintStream = out;
}
@@ -390,22 +370,9 @@
* the {@code PrintWriter} to be used.
*/
public static void setLogWriter(PrintWriter out) {
- checkLogSecurity();
thePrintWriter = out;
}
- /*
- * Method which checks to see if setting a logging stream is allowed by the
- * Security manager
- */
- private static void checkLogSecurity() {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- // Throws a SecurityException if setting the log is not permitted
- securityManager.checkPermission(logPermission);
- }
- }
-
/**
* Determines whether the supplied object was loaded by the given {@code ClassLoader}.
*
diff --git a/luni/src/main/java/java/text/AttributedString.java b/luni/src/main/java/java/text/AttributedString.java
index 1495dc56..1335067 100644
--- a/luni/src/main/java/java/text/AttributedString.java
+++ b/luni/src/main/java/java/text/AttributedString.java
@@ -105,7 +105,7 @@
}
return clone;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
@@ -506,15 +506,9 @@
*/
public AttributedString(AttributedCharacterIterator iterator, int start,
int end, AttributedCharacterIterator.Attribute[] attributes) {
- // BEGIN android-removed
- // this(iterator, start, end, new HashSet<Attribute>(Arrays
- // .asList(attributes)));
- // END android-removed
- // BEGIN android-added
this(iterator, start, end, (attributes == null
? new HashSet<Attribute>()
: new HashSet<Attribute>(Arrays.asList(attributes))));
- // END android-added
}
/**
diff --git a/luni/src/main/java/java/text/BreakIterator.java b/luni/src/main/java/java/text/BreakIterator.java
index ccc484c..4d10b51 100644
--- a/luni/src/main/java/java/text/BreakIterator.java
+++ b/luni/src/main/java/java/text/BreakIterator.java
@@ -490,7 +490,7 @@
cloned.wrapped = (NativeBreakIterator) wrapped.clone();
return cloned;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
}
diff --git a/luni/src/main/java/java/text/Collator.java b/luni/src/main/java/java/text/Collator.java
index 689fcb7..0fa8c71 100644
--- a/luni/src/main/java/java/text/Collator.java
+++ b/luni/src/main/java/java/text/Collator.java
@@ -172,7 +172,7 @@
clone.icuColl = (RuleBasedCollatorICU) icuColl.clone();
return clone;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/text/DateFormat.java b/luni/src/main/java/java/text/DateFormat.java
index 53480e6..4055d20 100644
--- a/luni/src/main/java/java/text/DateFormat.java
+++ b/luni/src/main/java/java/text/DateFormat.java
@@ -143,51 +143,51 @@
* The format style constant defining the default format style. The default
* is MEDIUM.
*/
- public final static int DEFAULT = 2;
+ public static final int DEFAULT = 2;
/**
* The format style constant defining the full style.
*/
- public final static int FULL = 0;
+ public static final int FULL = 0;
/**
* The format style constant defining the long style.
*/
- public final static int LONG = 1;
+ public static final int LONG = 1;
/**
* The format style constant defining the medium style.
*/
- public final static int MEDIUM = 2;
+ public static final int MEDIUM = 2;
/**
* The format style constant defining the short style.
*/
- public final static int SHORT = 3;
+ public static final int SHORT = 3;
/**
* The {@code FieldPosition} selector for 'G' field alignment, corresponds
* to the {@link Calendar#ERA} field.
*/
- public final static int ERA_FIELD = 0;
+ public static final int ERA_FIELD = 0;
/**
* The {@code FieldPosition} selector for 'y' field alignment, corresponds
* to the {@link Calendar#YEAR} field.
*/
- public final static int YEAR_FIELD = 1;
+ public static final int YEAR_FIELD = 1;
/**
* The {@code FieldPosition} selector for 'M' field alignment, corresponds
* to the {@link Calendar#MONTH} field.
*/
- public final static int MONTH_FIELD = 2;
+ public static final int MONTH_FIELD = 2;
/**
* The {@code FieldPosition} selector for 'd' field alignment, corresponds
* to the {@link Calendar#DATE} field.
*/
- public final static int DATE_FIELD = 3;
+ public static final int DATE_FIELD = 3;
/**
* The {@code FieldPosition} selector for 'k' field alignment, corresponds
@@ -195,7 +195,7 @@
* used for the one-based 24-hour clock. For example, 23:59 + 01:00 results
* in 24:59.
*/
- public final static int HOUR_OF_DAY1_FIELD = 4;
+ public static final int HOUR_OF_DAY1_FIELD = 4;
/**
* The {@code FieldPosition} selector for 'H' field alignment, corresponds
@@ -203,80 +203,80 @@
* used for the zero-based 24-hour clock. For example, 23:59 + 01:00 results
* in 00:59.
*/
- public final static int HOUR_OF_DAY0_FIELD = 5;
+ public static final int HOUR_OF_DAY0_FIELD = 5;
/**
* FieldPosition selector for 'm' field alignment, corresponds to the
* {@link Calendar#MINUTE} field.
*/
- public final static int MINUTE_FIELD = 6;
+ public static final int MINUTE_FIELD = 6;
/**
* FieldPosition selector for 's' field alignment, corresponds to the
* {@link Calendar#SECOND} field.
*/
- public final static int SECOND_FIELD = 7;
+ public static final int SECOND_FIELD = 7;
/**
* FieldPosition selector for 'S' field alignment, corresponds to the
* {@link Calendar#MILLISECOND} field.
*/
- public final static int MILLISECOND_FIELD = 8;
+ public static final int MILLISECOND_FIELD = 8;
/**
* FieldPosition selector for 'E' field alignment, corresponds to the
* {@link Calendar#DAY_OF_WEEK} field.
*/
- public final static int DAY_OF_WEEK_FIELD = 9;
+ public static final int DAY_OF_WEEK_FIELD = 9;
/**
* FieldPosition selector for 'D' field alignment, corresponds to the
* {@link Calendar#DAY_OF_YEAR} field.
*/
- public final static int DAY_OF_YEAR_FIELD = 10;
+ public static final int DAY_OF_YEAR_FIELD = 10;
/**
* FieldPosition selector for 'F' field alignment, corresponds to the
* {@link Calendar#DAY_OF_WEEK_IN_MONTH} field.
*/
- public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
+ public static final int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
/**
* FieldPosition selector for 'w' field alignment, corresponds to the
* {@link Calendar#WEEK_OF_YEAR} field.
*/
- public final static int WEEK_OF_YEAR_FIELD = 12;
+ public static final int WEEK_OF_YEAR_FIELD = 12;
/**
* FieldPosition selector for 'W' field alignment, corresponds to the
* {@link Calendar#WEEK_OF_MONTH} field.
*/
- public final static int WEEK_OF_MONTH_FIELD = 13;
+ public static final int WEEK_OF_MONTH_FIELD = 13;
/**
* FieldPosition selector for 'a' field alignment, corresponds to the
* {@link Calendar#AM_PM} field.
*/
- public final static int AM_PM_FIELD = 14;
+ public static final int AM_PM_FIELD = 14;
/**
* FieldPosition selector for 'h' field alignment, corresponding to the
* {@link Calendar#HOUR} field.
*/
- public final static int HOUR1_FIELD = 15;
+ public static final int HOUR1_FIELD = 15;
/**
* The {@code FieldPosition} selector for 'K' field alignment, corresponding to the
* {@link Calendar#HOUR} field.
*/
- public final static int HOUR0_FIELD = 16;
+ public static final int HOUR0_FIELD = 16;
/**
* The {@code FieldPosition} selector for 'z' field alignment, corresponds
* to the {@link Calendar#ZONE_OFFSET} and {@link Calendar#DST_OFFSET}
* fields.
*/
- public final static int TIMEZONE_FIELD = 17;
+ public static final int TIMEZONE_FIELD = 17;
/**
* Constructs a new instance of {@code DateFormat}.
@@ -422,7 +422,7 @@
*
* @return the {@code DateFormat} instance for the default style and locale.
*/
- public final static DateFormat getDateInstance() {
+ public static final DateFormat getDateInstance() {
return getDateInstance(DEFAULT);
}
@@ -438,7 +438,7 @@
* if {@code style} is not one of SHORT, MEDIUM, LONG, FULL, or
* DEFAULT.
*/
- public final static DateFormat getDateInstance(int style) {
+ public static final DateFormat getDateInstance(int style) {
checkDateStyle(style);
return getDateInstance(style, Locale.getDefault());
}
@@ -457,7 +457,7 @@
* @return the {@code DateFormat} instance for {@code style} and
* {@code locale}.
*/
- public final static DateFormat getDateInstance(int style, Locale locale) {
+ public static final DateFormat getDateInstance(int style, Locale locale) {
checkDateStyle(style);
return new SimpleDateFormat(LocaleData.get(locale).getDateFormat(style), locale);
}
@@ -468,7 +468,7 @@
*
* @return the {@code DateFormat} instance for the default style and locale.
*/
- public final static DateFormat getDateTimeInstance() {
+ public static final DateFormat getDateTimeInstance() {
return getDateTimeInstance(DEFAULT, DEFAULT);
}
@@ -486,7 +486,7 @@
* if {@code dateStyle} or {@code timeStyle} is not one of
* SHORT, MEDIUM, LONG, FULL, or DEFAULT.
*/
- public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
+ public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
checkTimeStyle(timeStyle);
checkDateStyle(dateStyle);
return getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
@@ -508,7 +508,7 @@
* if {@code dateStyle} or {@code timeStyle} is not one of
* SHORT, MEDIUM, LONG, FULL, or DEFAULT.
*/
- public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) {
+ public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) {
checkTimeStyle(timeStyle);
checkDateStyle(dateStyle);
LocaleData localeData = LocaleData.get(locale);
@@ -523,7 +523,7 @@
* @return the {@code DateFormat} instance for the SHORT style and default
* locale.
*/
- public final static DateFormat getInstance() {
+ public static final DateFormat getInstance() {
return getDateTimeInstance(SHORT, SHORT);
}
@@ -542,7 +542,7 @@
*
* @return the {@code DateFormat} instance for the default style and locale.
*/
- public final static DateFormat getTimeInstance() {
+ public static final DateFormat getTimeInstance() {
return getTimeInstance(DEFAULT);
}
@@ -558,7 +558,7 @@
* if {@code style} is not one of SHORT, MEDIUM, LONG, FULL, or
* DEFAULT.
*/
- public final static DateFormat getTimeInstance(int style) {
+ public static final DateFormat getTimeInstance(int style) {
checkTimeStyle(style);
return getTimeInstance(style, Locale.getDefault());
}
@@ -577,7 +577,7 @@
* @return the {@code DateFormat} instance for {@code style} and
* {@code locale}.
*/
- public final static DateFormat getTimeInstance(int style, Locale locale) {
+ public static final DateFormat getTimeInstance(int style, Locale locale) {
checkTimeStyle(style);
return new SimpleDateFormat(LocaleData.get(locale).getTimeFormat(style), locale);
}
@@ -743,95 +743,95 @@
/**
* Marks the era part of a date.
*/
- public final static Field ERA = new Field("era", Calendar.ERA);
+ public static final Field ERA = new Field("era", Calendar.ERA);
/**
* Marks the year part of a date.
*/
- public final static Field YEAR = new Field("year", Calendar.YEAR);
+ public static final Field YEAR = new Field("year", Calendar.YEAR);
/**
* Marks the month part of a date.
*/
- public final static Field MONTH = new Field("month", Calendar.MONTH);
+ public static final Field MONTH = new Field("month", Calendar.MONTH);
/**
* Marks the hour of the day part of a date (0-11).
*/
- public final static Field HOUR_OF_DAY0 = new Field("hour of day", Calendar.HOUR_OF_DAY);
+ public static final Field HOUR_OF_DAY0 = new Field("hour of day", Calendar.HOUR_OF_DAY);
/**
* Marks the hour of the day part of a date (1-12).
*/
- public final static Field HOUR_OF_DAY1 = new Field("hour of day 1", -1);
+ public static final Field HOUR_OF_DAY1 = new Field("hour of day 1", -1);
/**
* Marks the minute part of a time.
*/
- public final static Field MINUTE = new Field("minute", Calendar.MINUTE);
+ public static final Field MINUTE = new Field("minute", Calendar.MINUTE);
/**
* Marks the second part of a time.
*/
- public final static Field SECOND = new Field("second", Calendar.SECOND);
+ public static final Field SECOND = new Field("second", Calendar.SECOND);
/**
* Marks the millisecond part of a time.
*/
- public final static Field MILLISECOND = new Field("millisecond", Calendar.MILLISECOND);
+ public static final Field MILLISECOND = new Field("millisecond", Calendar.MILLISECOND);
/**
* Marks the day of the week part of a date.
*/
- public final static Field DAY_OF_WEEK = new Field("day of week", Calendar.DAY_OF_WEEK);
+ public static final Field DAY_OF_WEEK = new Field("day of week", Calendar.DAY_OF_WEEK);
/**
* Marks the day of the month part of a date.
*/
- public final static Field DAY_OF_MONTH = new Field("day of month", Calendar.DAY_OF_MONTH);
+ public static final Field DAY_OF_MONTH = new Field("day of month", Calendar.DAY_OF_MONTH);
/**
* Marks the day of the year part of a date.
*/
- public final static Field DAY_OF_YEAR = new Field("day of year", Calendar.DAY_OF_YEAR);
+ public static final Field DAY_OF_YEAR = new Field("day of year", Calendar.DAY_OF_YEAR);
/**
* Marks the day of the week in the month part of a date.
*/
- public final static Field DAY_OF_WEEK_IN_MONTH = new Field("day of week in month",
+ public static final Field DAY_OF_WEEK_IN_MONTH = new Field("day of week in month",
Calendar.DAY_OF_WEEK_IN_MONTH);
/**
* Marks the week of the year part of a date.
*/
- public final static Field WEEK_OF_YEAR = new Field("week of year",
+ public static final Field WEEK_OF_YEAR = new Field("week of year",
Calendar.WEEK_OF_YEAR);
/**
* Marks the week of the month part of a date.
*/
- public final static Field WEEK_OF_MONTH = new Field("week of month",
+ public static final Field WEEK_OF_MONTH = new Field("week of month",
Calendar.WEEK_OF_MONTH);
/**
* Marks the time indicator part of a date.
*/
- public final static Field AM_PM = new Field("am pm", Calendar.AM_PM);
+ public static final Field AM_PM = new Field("am pm", Calendar.AM_PM);
/**
* Marks the hour part of a date (0-11).
*/
- public final static Field HOUR0 = new Field("hour", Calendar.HOUR);
+ public static final Field HOUR0 = new Field("hour", Calendar.HOUR);
/**
* Marks the hour part of a date (1-12).
*/
- public final static Field HOUR1 = new Field("hour 1", -1);
+ public static final Field HOUR1 = new Field("hour 1", -1);
/**
* Marks the time zone part of a date.
*/
- public final static Field TIME_ZONE = new Field("time zone", -1);
+ public static final Field TIME_ZONE = new Field("time zone", -1);
/**
* The calendar field that this field represents.
diff --git a/luni/src/main/java/java/text/DateFormatSymbols.java b/luni/src/main/java/java/text/DateFormatSymbols.java
index 73c818e..423b9df 100644
--- a/luni/src/main/java/java/text/DateFormatSymbols.java
+++ b/luni/src/main/java/java/text/DateFormatSymbols.java
@@ -327,7 +327,15 @@
* </ul>
*/
public String[][] getZoneStrings() {
- return TimeZones.clone2dStringArray(internalZoneStrings());
+ return clone2dStringArray(internalZoneStrings());
+ }
+
+ private static String[][] clone2dStringArray(String[][] array) {
+ String[][] result = new String[array.length][];
+ for (int i = 0; i < array.length; ++i) {
+ result[i] = array[i].clone();
+ }
+ return result;
}
@Override
@@ -466,7 +474,7 @@
throw new IllegalArgumentException(Arrays.toString(row) + ".length < 5");
}
}
- this.zoneStrings = TimeZones.clone2dStringArray(zoneStrings);
+ this.zoneStrings = clone2dStringArray(zoneStrings);
this.customZoneStrings = true;
}
}
diff --git a/luni/src/main/java/java/text/DecimalFormat.java b/luni/src/main/java/java/text/DecimalFormat.java
index b2b5d6a..c1a48db 100644
--- a/luni/src/main/java/java/text/DecimalFormat.java
+++ b/luni/src/main/java/java/text/DecimalFormat.java
@@ -884,30 +884,6 @@
if (number == null) {
return null;
}
- // BEGIN android-removed
- // if (this.isParseBigDecimal()) {
- // if (number instanceof Long) {
- // return new BigDecimal(number.longValue());
- // }
- // if ((number instanceof Double) && !((Double) number).isInfinite()
- // && !((Double) number).isNaN()) {
- //
- // return new BigDecimal(number.doubleValue());
- // }
- // if (number instanceof BigInteger) {
- // return new BigDecimal(number.doubleValue());
- // }
- // if (number instanceof com.ibm.icu.math.BigDecimal) {
- // return new BigDecimal(number.toString());
- // }
- // return number;
- // }
- // if ((number instanceof com.ibm.icu.math.BigDecimal)
- // || (number instanceof BigInteger)) {
- // return new Double(number.doubleValue());
- // }
- // END android-removed
- // BEGIN android-added
if (this.isParseBigDecimal()) {
if (number instanceof Long) {
return new BigDecimal(number.longValue());
@@ -925,10 +901,8 @@
if ((number instanceof BigDecimal) || (number instanceof BigInteger)) {
return new Double(number.doubleValue());
}
- // END android-added
-
if (this.isParseIntegerOnly() && number.equals(NEGATIVE_ZERO_DOUBLE)) {
- return Long.valueOf(0); // android-changed
+ return Long.valueOf(0);
}
return number;
@@ -942,10 +916,9 @@
*/
public void setDecimalFormatSymbols(DecimalFormatSymbols value) {
if (value != null) {
- // BEGIN android-changed: the Java object is canonical, and we copy down to native code.
+ // The Java object is canonical, and we copy down to native code.
this.symbols = (DecimalFormatSymbols) value.clone();
dform.setDecimalFormatSymbols(this.symbols);
- // END android-changed
}
}
@@ -959,9 +932,7 @@
*/
@Override
public void setCurrency(Currency currency) {
- // BEGIN android-changed
dform.setCurrency(Currency.getInstance(currency.getCurrencyCode()));
- // END android-changed
symbols.setCurrency(currency);
}
@@ -1150,28 +1121,29 @@
// the fields list to be serialized
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("positivePrefix", String.class),
- new ObjectStreamField("positiveSuffix", String.class),
- new ObjectStreamField("negativePrefix", String.class),
- new ObjectStreamField("negativeSuffix", String.class),
- new ObjectStreamField("posPrefixPattern", String.class),
- new ObjectStreamField("posSuffixPattern", String.class),
- new ObjectStreamField("negPrefixPattern", String.class),
- new ObjectStreamField("negSuffixPattern", String.class),
- new ObjectStreamField("multiplier", int.class),
- new ObjectStreamField("groupingSize", byte.class),
- new ObjectStreamField("groupingUsed", boolean.class),
- new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class),
- new ObjectStreamField("parseBigDecimal", boolean.class),
- new ObjectStreamField("roundingMode", RoundingMode.class),
- new ObjectStreamField("symbols", DecimalFormatSymbols.class),
- new ObjectStreamField("useExponentialNotation", boolean.class),
- new ObjectStreamField("minExponentDigits", byte.class),
- new ObjectStreamField("maximumIntegerDigits", int.class),
- new ObjectStreamField("minimumIntegerDigits", int.class),
- new ObjectStreamField("maximumFractionDigits", int.class),
- new ObjectStreamField("minimumFractionDigits", int.class),
- new ObjectStreamField("serialVersionOnStream", int.class), };
+ new ObjectStreamField("positivePrefix", String.class),
+ new ObjectStreamField("positiveSuffix", String.class),
+ new ObjectStreamField("negativePrefix", String.class),
+ new ObjectStreamField("negativeSuffix", String.class),
+ new ObjectStreamField("posPrefixPattern", String.class),
+ new ObjectStreamField("posSuffixPattern", String.class),
+ new ObjectStreamField("negPrefixPattern", String.class),
+ new ObjectStreamField("negSuffixPattern", String.class),
+ new ObjectStreamField("multiplier", int.class),
+ new ObjectStreamField("groupingSize", byte.class),
+ new ObjectStreamField("groupingUsed", boolean.class),
+ new ObjectStreamField("decimalSeparatorAlwaysShown", boolean.class),
+ new ObjectStreamField("parseBigDecimal", boolean.class),
+ new ObjectStreamField("roundingMode", RoundingMode.class),
+ new ObjectStreamField("symbols", DecimalFormatSymbols.class),
+ new ObjectStreamField("useExponentialNotation", boolean.class),
+ new ObjectStreamField("minExponentDigits", byte.class),
+ new ObjectStreamField("maximumIntegerDigits", int.class),
+ new ObjectStreamField("minimumIntegerDigits", int.class),
+ new ObjectStreamField("maximumFractionDigits", int.class),
+ new ObjectStreamField("minimumFractionDigits", int.class),
+ new ObjectStreamField("serialVersionOnStream", int.class),
+ };
/**
* Writes serialized fields following serialized forms specified by Java
@@ -1183,9 +1155,7 @@
* if some I/O error occurs
* @throws ClassNotFoundException
*/
- @SuppressWarnings("nls")
- private void writeObject(ObjectOutputStream stream) throws IOException,
- ClassNotFoundException {
+ private void writeObject(ObjectOutputStream stream) throws IOException, ClassNotFoundException {
ObjectOutputStream.PutField fields = stream.putFields();
fields.put("positivePrefix", dform.getPositivePrefix());
fields.put("positiveSuffix", dform.getPositiveSuffix());
@@ -1197,11 +1167,8 @@
fields.put("negSuffixPattern", (String) null);
fields.put("multiplier", dform.getMultiplier());
fields.put("groupingSize", (byte) dform.getGroupingSize());
- // BEGIN android-added
fields.put("groupingUsed", dform.isGroupingUsed());
- // END android-added
- fields.put("decimalSeparatorAlwaysShown", dform
- .isDecimalSeparatorAlwaysShown());
+ fields.put("decimalSeparatorAlwaysShown", dform.isDecimalSeparatorAlwaysShown());
fields.put("parseBigDecimal", dform.isParseBigDecimal());
fields.put("roundingMode", roundingMode);
fields.put("symbols", symbols);
@@ -1226,9 +1193,7 @@
* @throws ClassNotFoundException
* if some class of serialized objects or fields cannot be found
*/
- @SuppressWarnings("nls")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
- // BEGIN android-changed
ObjectInputStream.GetField fields = stream.readFields();
this.symbols = (DecimalFormatSymbols) fields.get("symbols", null);
@@ -1248,7 +1213,7 @@
final int minimumIntegerDigits = fields.get("minimumIntegerDigits", 309);
final int maximumFractionDigits = fields.get("maximumFractionDigits", 340);
final int minimumFractionDigits = fields.get("minimumFractionDigits", 340);
- // BEGIN android-changed: tell ICU what we want, then ask it what we can have, and then
+ // Tell ICU what we want, then ask it what we can have, and then
// set that in our Java object. This isn't RI-compatible, but then very little of our
// behavior in this area is, and it's not obvious how we can second-guess ICU (or tell
// it to just do exactly what we ask). We only need to do this with maximumIntegerDigits
@@ -1267,7 +1232,6 @@
setMaximumFractionDigits(super.getMaximumFractionDigits());
setMinimumFractionDigits(super.getMinimumFractionDigits());
}
- // END android-changed
}
/**
diff --git a/luni/src/main/java/java/text/DecimalFormatSymbols.java b/luni/src/main/java/java/text/DecimalFormatSymbols.java
index 13e9128..889adcd 100644
--- a/luni/src/main/java/java/text/DecimalFormatSymbols.java
+++ b/luni/src/main/java/java/text/DecimalFormatSymbols.java
@@ -565,21 +565,21 @@
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("currencySymbol", String.class),
- new ObjectStreamField("decimalSeparator", Character.TYPE),
- new ObjectStreamField("digit", Character.TYPE),
- new ObjectStreamField("exponential", Character.TYPE),
+ new ObjectStreamField("decimalSeparator", char.class),
+ new ObjectStreamField("digit", char.class),
+ new ObjectStreamField("exponential", char.class),
new ObjectStreamField("exponentialSeparator", String.class),
- new ObjectStreamField("groupingSeparator", Character.TYPE),
+ new ObjectStreamField("groupingSeparator", char.class),
new ObjectStreamField("infinity", String.class),
new ObjectStreamField("intlCurrencySymbol", String.class),
- new ObjectStreamField("minusSign", Character.TYPE),
- new ObjectStreamField("monetarySeparator", Character.TYPE),
+ new ObjectStreamField("minusSign", char.class),
+ new ObjectStreamField("monetarySeparator", char.class),
new ObjectStreamField("NaN", String.class),
- new ObjectStreamField("patternSeparator", Character.TYPE),
- new ObjectStreamField("percent", Character.TYPE),
- new ObjectStreamField("perMill", Character.TYPE),
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE),
- new ObjectStreamField("zeroDigit", Character.TYPE),
+ new ObjectStreamField("patternSeparator", char.class),
+ new ObjectStreamField("percent", char.class),
+ new ObjectStreamField("perMill", char.class),
+ new ObjectStreamField("serialVersionOnStream", int.class),
+ new ObjectStreamField("zeroDigit", char.class),
new ObjectStreamField("locale", Locale.class),
};
diff --git a/luni/src/main/java/java/text/Format.java b/luni/src/main/java/java/text/Format.java
index 200ab0f..58671fa 100644
--- a/luni/src/main/java/java/text/Format.java
+++ b/luni/src/main/java/java/text/Format.java
@@ -76,7 +76,7 @@
try {
return super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/text/MessageFormat.java b/luni/src/main/java/java/text/MessageFormat.java
index 8d8d12c..a98e4fd 100644
--- a/luni/src/main/java/java/text/MessageFormat.java
+++ b/luni/src/main/java/java/text/MessageFormat.java
@@ -21,9 +21,11 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
+import java.util.List;
import java.util.Locale;
import java.util.Vector;
import libcore.util.EmptyArray;
@@ -384,11 +386,11 @@
int length = template.length();
StringBuffer buffer = new StringBuffer();
ParsePosition position = new ParsePosition(0);
- Vector<String> localStrings = new Vector<String>();
+ ArrayList<String> localStrings = new ArrayList<String>();
int argCount = 0;
int[] args = new int[10];
int maxArg = -1;
- Vector<Format> localFormats = new Vector<Format>();
+ ArrayList<Format> localFormats = new ArrayList<Format>();
while (position.getIndex() < length) {
if (Format.upTo(template, position, buffer, '{')) {
int arg = 0;
@@ -411,7 +413,7 @@
}
offset--;
position.setIndex(offset);
- localFormats.addElement(parseVariable(template, position));
+ localFormats.add(parseVariable(template, position));
if (argCount >= args.length) {
int[] newArgs = new int[args.length * 2];
System.arraycopy(args, 0, newArgs, 0, args.length);
@@ -422,18 +424,12 @@
maxArg = arg;
}
}
- localStrings.addElement(buffer.toString());
+ localStrings.add(buffer.toString());
buffer.setLength(0);
}
- this.strings = new String[localStrings.size()];
- for (int i = 0; i < localStrings.size(); i++) {
- this.strings[i] = localStrings.elementAt(i);
- }
+ this.strings = localStrings.toArray(new String[localStrings.size()]);
argumentNumbers = args;
- this.formats = new Format[argCount];
- for (int i = 0; i < argCount; i++) {
- this.formats[i] = localFormats.elementAt(i);
- }
+ this.formats = localFormats.toArray(new Format[argCount]);
maxOffset = argCount - 1;
maxArgumentIndex = maxArg;
}
@@ -514,7 +510,7 @@
}
StringBuffer buffer = new StringBuffer();
- Vector<FieldContainer> fields = new Vector<FieldContainer>();
+ ArrayList<FieldContainer> fields = new ArrayList<FieldContainer>();
// format the message, and find fields
formatImpl((Object[]) object, buffer, new FieldPosition(0), fields);
@@ -523,8 +519,7 @@
AttributedString as = new AttributedString(buffer.toString());
// add MessageFormat field attributes and values to the AttributedString
- for (int i = 0; i < fields.size(); i++) {
- FieldContainer fc = fields.elementAt(i);
+ for (FieldContainer fc : fields) {
as.addAttribute(fc.attribute, fc.value, fc.start, fc.end);
}
@@ -556,7 +551,7 @@
}
private StringBuffer formatImpl(Object[] objects, StringBuffer buffer,
- FieldPosition position, Vector<FieldContainer> fields) {
+ FieldPosition position, List<FieldContainer> fields) {
FieldPosition passedField = new FieldPosition(0);
for (int i = 0; i <= maxOffset; i++) {
buffer.append(strings[i]);
@@ -568,8 +563,7 @@
buffer.append('{');
buffer.append(argumentNumbers[i]);
buffer.append('}');
- handleArgumentField(begin, buffer.length(), argumentNumbers[i],
- position, fields);
+ handleArgumentField(begin, buffer.length(), argumentNumbers[i], position, fields);
continue;
}
Format format = formats[i];
@@ -580,8 +574,7 @@
format = DateFormat.getInstance();
} else {
buffer.append(arg);
- handleArgumentField(begin, buffer.length(),
- argumentNumbers[i], position, fields);
+ handleArgumentField(begin, buffer.length(), argumentNumbers[i], position, fields);
continue;
}
}
@@ -590,14 +583,12 @@
MessageFormat mf = new MessageFormat(result);
mf.setLocale(locale);
mf.format(objects, buffer, passedField);
- handleArgumentField(begin, buffer.length(), argumentNumbers[i],
- position, fields);
- handleformat(format, arg, begin, fields);
+ handleArgumentField(begin, buffer.length(), argumentNumbers[i], position, fields);
+ handleFormat(format, arg, begin, fields);
} else {
format.format(arg, buffer, passedField);
- handleArgumentField(begin, buffer.length(), argumentNumbers[i],
- position, fields);
- handleformat(format, arg, begin, fields);
+ handleArgumentField(begin, buffer.length(), argumentNumbers[i], position, fields);
+ handleFormat(format, arg, begin, fields);
}
}
if (maxOffset + 1 < strings.length) {
@@ -608,12 +599,12 @@
/**
* Adds a new FieldContainer with MessageFormat.Field.ARGUMENT field,
- * argIndex, begin and end index to the fields vector, or sets the
+ * argIndex, begin and end index to the fields list, or sets the
* position's begin and end index if it has MessageFormat.Field.ARGUMENT as
* its field attribute.
*/
private void handleArgumentField(int begin, int end, int argIndex,
- FieldPosition position, Vector<FieldContainer> fields) {
+ FieldPosition position, List<FieldContainer> fields) {
if (fields != null) {
fields.add(new FieldContainer(begin, end, Field.ARGUMENT, Integer.valueOf(argIndex)));
} else {
@@ -628,7 +619,7 @@
/**
* An inner class to store attributes, values, start and end indices.
- * Instances of this inner class are used as elements for the fields vector
+ * Instances of this inner class are used as elements for the fields list.
*/
private static class FieldContainer {
int start, end;
@@ -647,8 +638,8 @@
}
/**
- * If fields vector is not null, find and add the fields of this format to
- * the fields vector by iterating through its AttributedCharacterIterator
+ * If fields list is not null, find and add the fields of this format to
+ * the fields list by iterating through its AttributedCharacterIterator
*
* @param format
* the format to find fields for
@@ -656,29 +647,23 @@
* object to format
* @param begin
* the index where the string this format has formatted begins
- * @param fields
- * fields vector, each entry in this vector are of type
- * FieldContainer.
*/
- private void handleformat(Format format, Object arg, int begin,
- Vector<FieldContainer> fields) {
- if (fields != null) {
- AttributedCharacterIterator iterator = format
- .formatToCharacterIterator(arg);
- while (iterator.getIndex() != iterator.getEndIndex()) {
- int start = iterator.getRunStart();
- int end = iterator.getRunLimit();
-
- Iterator<?> it = iterator.getAttributes().keySet().iterator();
- while (it.hasNext()) {
- AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute) it
- .next();
- Object value = iterator.getAttribute(attribute);
- fields.add(new FieldContainer(begin + start, begin + end,
- attribute, value));
- }
- iterator.setIndex(end);
+ private void handleFormat(Format format, Object arg, int begin, List<FieldContainer> fields) {
+ if (fields == null) {
+ return;
+ }
+ AttributedCharacterIterator iterator = format.formatToCharacterIterator(arg);
+ while (iterator.getIndex() != iterator.getEndIndex()) {
+ int start = iterator.getRunStart();
+ int end = iterator.getRunLimit();
+ Iterator<?> it = iterator.getAttributes().keySet().iterator();
+ while (it.hasNext()) {
+ AttributedCharacterIterator.Attribute attribute =
+ (AttributedCharacterIterator.Attribute) it.next();
+ Object value = iterator.getAttribute(attribute);
+ fields.add(new FieldContainer(begin + start, begin + end, attribute, value));
}
+ iterator.setIndex(end);
}
}
@@ -1018,9 +1003,7 @@
.getTimeInstance(dateStyle, locale);
case 2: // number
if (ch == '}') {
- // BEGIN android-changed
return NumberFormat.getInstance(locale);
- // END android-changed
}
int numberStyle = match(string, position, true,
new String[] { "currency", "percent", "integer" });
@@ -1086,16 +1069,6 @@
this.locale = locale;
for (int i = 0; i <= maxOffset; i++) {
Format format = formats[i];
- // BEGIN android-removed
- //if (format instanceof DecimalFormat) {
- // formats[i] = new DecimalFormat(((DecimalFormat) format)
- // .toPattern(), new DecimalFormatSymbols(locale));
- //} else if (format instanceof SimpleDateFormat) {
- // formats[i] = new SimpleDateFormat(((SimpleDateFormat) format)
- // .toPattern(), locale);
- //}
- // END android-removed
- // BEGIN android-added
// java specification undefined for null argument, change into
// a more tolerant implementation
if (format instanceof DecimalFormat) {
@@ -1113,7 +1086,6 @@
formats[i] = null;
}
}
- // END android-added
}
}
@@ -1235,12 +1207,13 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("argumentNumbers", int[].class),
- new ObjectStreamField("formats", Format[].class),
- new ObjectStreamField("locale", Locale.class),
- new ObjectStreamField("maxOffset", Integer.TYPE),
- new ObjectStreamField("offsets", int[].class),
- new ObjectStreamField("pattern", String.class), };
+ new ObjectStreamField("argumentNumbers", int[].class),
+ new ObjectStreamField("formats", Format[].class),
+ new ObjectStreamField("locale", Locale.class),
+ new ObjectStreamField("maxOffset", int.class),
+ new ObjectStreamField("offsets", int[].class),
+ new ObjectStreamField("pattern", String.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/text/NumberFormat.java b/luni/src/main/java/java/text/NumberFormat.java
index a5b1cb2..3bff6ad 100644
--- a/luni/src/main/java/java/text/NumberFormat.java
+++ b/luni/src/main/java/java/text/NumberFormat.java
@@ -340,7 +340,7 @@
*
* @return a {@code NumberFormat} for handling currency values.
*/
- public final static NumberFormat getCurrencyInstance() {
+ public static final NumberFormat getCurrencyInstance() {
return getCurrencyInstance(Locale.getDefault());
}
@@ -363,7 +363,7 @@
*
* @return a {@code NumberFormat} for handling integers.
*/
- public final static NumberFormat getIntegerInstance() {
+ public static final NumberFormat getIntegerInstance() {
return getIntegerInstance(Locale.getDefault());
}
@@ -387,7 +387,7 @@
*
* @return a {@code NumberFormat} for handling {@code Number} objects.
*/
- public final static NumberFormat getInstance() {
+ public static final NumberFormat getInstance() {
return getNumberInstance();
}
@@ -403,11 +403,9 @@
return getNumberInstance(locale);
}
- // BEGIN android-added
private static NumberFormat getInstance(String pattern, Locale locale) {
return new DecimalFormat(pattern, locale);
}
- // END android-added
/**
* Returns the maximum number of fraction digits that are printed when
@@ -458,7 +456,7 @@
*
* @return a {@code NumberFormat} for handling {@code Number} objects.
*/
- public final static NumberFormat getNumberInstance() {
+ public static final NumberFormat getNumberInstance() {
return getNumberInstance(Locale.getDefault());
}
@@ -484,7 +482,7 @@
* A value such as 0.53 will be treated as 53%, but 53.0 (or the integer 53) will be
* treated as 5,300%, which is rarely what you intended.
*/
- public final static NumberFormat getPercentInstance() {
+ public static final NumberFormat getPercentInstance() {
return getPercentInstance(Locale.getDefault());
}
@@ -682,17 +680,18 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("groupingUsed", Boolean.TYPE),
- new ObjectStreamField("maxFractionDigits", Byte.TYPE),
- new ObjectStreamField("maximumFractionDigits", Integer.TYPE),
- new ObjectStreamField("maximumIntegerDigits", Integer.TYPE),
- new ObjectStreamField("maxIntegerDigits", Byte.TYPE),
- new ObjectStreamField("minFractionDigits", Byte.TYPE),
- new ObjectStreamField("minimumFractionDigits", Integer.TYPE),
- new ObjectStreamField("minimumIntegerDigits", Integer.TYPE),
- new ObjectStreamField("minIntegerDigits", Byte.TYPE),
- new ObjectStreamField("parseIntegerOnly", Boolean.TYPE),
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE), };
+ new ObjectStreamField("groupingUsed", boolean.class),
+ new ObjectStreamField("maxFractionDigits", byte.class),
+ new ObjectStreamField("maximumFractionDigits", int.class),
+ new ObjectStreamField("maximumIntegerDigits", int.class),
+ new ObjectStreamField("maxIntegerDigits", byte.class),
+ new ObjectStreamField("minFractionDigits", byte.class),
+ new ObjectStreamField("minimumFractionDigits", int.class),
+ new ObjectStreamField("minimumIntegerDigits", int.class),
+ new ObjectStreamField("minIntegerDigits", byte.class),
+ new ObjectStreamField("parseIntegerOnly", boolean.class),
+ new ObjectStreamField("serialVersionOnStream", int.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/text/SimpleDateFormat.java b/luni/src/main/java/java/text/SimpleDateFormat.java
index 869678b..46ecc1a 100644
--- a/luni/src/main/java/java/text/SimpleDateFormat.java
+++ b/luni/src/main/java/java/text/SimpleDateFormat.java
@@ -21,13 +21,14 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
+import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
+import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
-import java.util.Vector;
import libcore.icu.LocaleData;
import libcore.icu.TimeZones;
@@ -484,7 +485,7 @@
private AttributedCharacterIterator formatToCharacterIteratorImpl(Date date) {
StringBuffer buffer = new StringBuffer();
- Vector<FieldPosition> fields = new Vector<FieldPosition>();
+ ArrayList<FieldPosition> fields = new ArrayList<FieldPosition>();
// format the date, and find fields
formatImpl(date, buffer, null, fields);
@@ -493,8 +494,7 @@
AttributedString as = new AttributedString(buffer.toString());
// add DateFormat field attributes to the AttributedString
- for (int i = 0; i < fields.size(); i++) {
- FieldPosition pos = fields.elementAt(i);
+ for (FieldPosition pos : fields) {
Format.Field attribute = pos.getFieldAttribute();
as.addAttribute(attribute, attribute, pos.getBeginIndex(), pos.getEndIndex());
}
@@ -510,7 +510,7 @@
* specified by this FieldPosition is formatted, set the begin and end index
* of the formatted field in the FieldPosition.
* <p>
- * If the Vector {@code fields} is not null, find fields of this
+ * If the list {@code fields} is not null, find fields of this
* date, set FieldPositions with these fields, and add them to the fields
* vector.
*
@@ -522,14 +522,14 @@
* FieldPosition to set begin and end index of the field
* specified, if it is part of the format for this date
* @param fields
- * Vector used to store the FieldPositions for each field in this
+ * list used to store the FieldPositions for each field in this
* date
* @return the formatted Date
* @throws IllegalArgumentException
* if the object cannot be formatted by this Format.
*/
private StringBuffer formatImpl(Date date, StringBuffer buffer,
- FieldPosition field, Vector<FieldPosition> fields) {
+ FieldPosition field, List<FieldPosition> fields) {
boolean quote = false;
int next, last = -1, count = 0;
@@ -582,7 +582,7 @@
}
private void append(StringBuffer buffer, FieldPosition position,
- Vector<FieldPosition> fields, char format, int count) {
+ List<FieldPosition> fields, char format, int count) {
int field = -1;
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
@@ -748,7 +748,7 @@
}
// We can't call TimeZone.getDisplayName() because it would not use
// the custom DateFormatSymbols of this SimpleDateFormat.
- String custom = TimeZones.lookupDisplayName(formatData.zoneStrings, tz.getID(), daylight, style);
+ String custom = TimeZones.getDisplayName(formatData.zoneStrings, tz.getID(), daylight, style);
if (custom != null) {
buffer.append(custom);
return;
@@ -780,6 +780,9 @@
}
private void appendNumber(StringBuffer buffer, int count, int value) {
+ // TODO: we could avoid using the NumberFormat in most cases for a significant speedup.
+ // The only problem is that we expose the NumberFormat to third-party code, so we'd have
+ // some work to do to work out when the optimization is valid.
int minimumIntegerDigits = numberFormat.getMinimumIntegerDigits();
numberFormat.setMinimumIntegerDigits(count);
numberFormat.format(Integer.valueOf(value), buffer, new FieldPosition(0));
@@ -1268,10 +1271,11 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("defaultCenturyStart", Date.class),
- new ObjectStreamField("formatData", DateFormatSymbols.class),
- new ObjectStreamField("pattern", String.class),
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE), };
+ new ObjectStreamField("defaultCenturyStart", Date.class),
+ new ObjectStreamField("formatData", DateFormatSymbols.class),
+ new ObjectStreamField("pattern", String.class),
+ new ObjectStreamField("serialVersionOnStream", int.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/text/StringCharacterIterator.java b/luni/src/main/java/java/text/StringCharacterIterator.java
index 8b0e2b7..13c3543 100644
--- a/luni/src/main/java/java/text/StringCharacterIterator.java
+++ b/luni/src/main/java/java/text/StringCharacterIterator.java
@@ -105,7 +105,7 @@
try {
return super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/ArrayList.java b/luni/src/main/java/java/util/ArrayList.java
index c0c51d9..5f848fc 100644
--- a/luni/src/main/java/java/util/ArrayList.java
+++ b/luni/src/main/java/java/util/ArrayList.java
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// New implementation: simpler and faster than Harmony implementation.
-// BEGIN android-note
-
package java.util;
import java.io.IOException;
diff --git a/luni/src/main/java/java/util/Arrays.java b/luni/src/main/java/java/util/Arrays.java
index 8d27f49..481afa0 100644
--- a/luni/src/main/java/java/util/Arrays.java
+++ b/luni/src/main/java/java/util/Arrays.java
@@ -26,15 +26,6 @@
* @since 1.2
*/
public class Arrays {
- // BEGIN android-changed
- // Replaced Bentely-McIlroy-based sort w/ DualPivotQuicksort
- // BEGIN android-changed
-
- // BEGIN android-removed
- /* Specifies when to switch to insertion sort */
- // private static final int SIMPLE_LENGTH = 7;
- // END android-removed
-
private static class ArrayList<E> extends AbstractList<E> implements
List<E>, Serializable, RandomAccess {
@@ -1944,7 +1935,7 @@
* {@code ((Comparable)first).compareTo(Second)}.
* If not, you are better off deleting ComparableTimSort to eliminate the
* code duplication. In other words, the commented out code below
- * is the preferable implementation for sorting arrays of comparbles if it
+ * is the preferable implementation for sorting arrays of Comparables if it
* offers sufficient performance.
*/
@@ -1952,10 +1943,9 @@
// * A comparator that implements the natural order of a group of
// * mutually comparable elements. Using this comparator saves us
// * from duplicating most of the code in this file (one version for
-// * commparables, one for explicit comparators).
+// * Comparables, one for explicit comparators).
// */
-// private static final Comparator<Object> NATURAL_ORDER =
-// new Comparator<Object>() {
+// private static final Comparator<Object> NATURAL_ORDER = new Comparator<Object>() {
// @SuppressWarnings("unchecked")
// public int compare(Object first, Object second) {
// return ((Comparable<Object>)first).compareTo(second);
@@ -1983,9 +1973,7 @@
* @see #sort(Object[], int, int)
*/
public static void sort(Object[] array) {
- // BEGIN android-changed
ComparableTimSort.sort(array);
- // END android-changed
}
/**
@@ -2009,55 +1997,9 @@
* if {@code start < 0} or {@code end > array.length}.
*/
public static void sort(Object[] array, int start, int end) {
- // BEGIN android-changed
ComparableTimSort.sort(array, start, end);
- // END android-changed
}
- // BEGIN android-removed
- /*
- private static void sort(int start, int end, Object[] array) {
- ...
- }
- private static void swap(int a, int b, Object[] arr) {
- ...
- }
- private static void mergeSort(Object[] in, Object[] out, int start,
- int end) {
- ...
- }
- private static void mergeSort(Object[] in, Object[] out, int start,
- int end, Comparator c) {
- ...
- }
- private static int find(Object[] arr, Comparable val, int bnd, int l, int r) {
- ...
- }
- private static int find(Object[] arr, Object val, int bnd, int l, int r,
- Comparator c) {
- ...
- }
- private static int medChar(int a, int b, int c, String[] arr, int id) {
- ...
- }
- private static int charAt(String str, int i) {
- ...
- }
- private static void copySwap(Object[] src, int from, Object[] dst, int to,
- int len) {
- ...
- }
- private static void stableStringSort(String[] arr, int start,
- int end) {
- ...
- }
- private static void stableStringSort(String[] arr, String[] src,
- String[] dst, int start, int end, int chId) {
- ...
- }
- */
- // END android-removed
-
/**
* Sorts the specified range in the array using the specified {@code Comparator}.
* All elements must be comparable to each other without a
@@ -2079,11 +2021,8 @@
* @throws ArrayIndexOutOfBoundsException
* if {@code start < 0} or {@code end > array.length}.
*/
- public static <T> void sort(T[] array, int start, int end,
- Comparator<? super T> comparator) {
- // BEGIN android-changed
+ public static <T> void sort(T[] array, int start, int end, Comparator<? super T> comparator) {
TimSort.sort(array, start, end, comparator);
- // END android-changed
}
/**
@@ -2099,9 +2038,7 @@
* using the {@code Comparator}.
*/
public static <T> void sort(T[] array, Comparator<? super T> comparator) {
- // BEGIN android-changed
TimSort.sort(array, comparator);
- // END android-changed
}
/**
@@ -2123,7 +2060,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 7); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2153,7 +2090,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 6); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2183,7 +2120,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 3); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 3);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2213,7 +2150,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 7); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2243,7 +2180,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 7); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2273,7 +2210,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 6); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2303,7 +2240,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 6); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2333,7 +2270,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 6); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 6);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2363,7 +2300,7 @@
if (array.length == 0) {
return "[]";
}
- StringBuilder sb = new StringBuilder(array.length * 7); // android-changed
+ StringBuilder sb = new StringBuilder(array.length * 7);
sb.append('[');
sb.append(array[0]);
for (int i = 1; i < array.length; i++) {
@@ -2397,7 +2334,7 @@
return "null";
}
// delegate this to the recursive method
- StringBuilder buf = new StringBuilder(array.length * 9); // android-changed
+ StringBuilder buf = new StringBuilder(array.length * 9);
deepToStringImpl(array, new Object[] { array }, buf);
return buf.toString();
}
diff --git a/luni/src/main/java/java/util/BitSet.java b/luni/src/main/java/java/util/BitSet.java
index bc76b80..4c300b5 100644
--- a/luni/src/main/java/java/util/BitSet.java
+++ b/luni/src/main/java/java/util/BitSet.java
@@ -128,7 +128,7 @@
clone.bits = bits.clone();
return clone;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
@@ -936,38 +936,20 @@
/**
* Returns the number of bits that are {@code true} in this {@code BitSet}.
- *
- * @return the number of {@code true} bits in the set.
*/
public int cardinality() {
if (!needClear) {
return 0;
}
- int count = 0;
+ int result = 0;
int length = bits.length;
- // FIXME: need to test performance, if still not satisfied, change it to
- // 256-bits table based
- for (int idx = 0; idx < length; idx++) {
- count += pop(bits[idx] & 0xffffffffL);
- count += pop(bits[idx] >>> 32);
+ for (int i = 0; i < length; ++i) {
+ result += Long.bitCount(bits[i]);
}
- return count;
+ return result;
}
- private final int pop(long x) {
- // BEGIN android-note
- // delegate to Integer.bitCount(i); consider using native code
- // END android-note
- x = x - ((x >>> 1) & 0x55555555);
- x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
- x = (x + (x >>> 4)) & 0x0f0f0f0f;
- x = x + (x >>> 8);
- x = x + (x >>> 16);
- return (int) x & 0x0000003f;
- }
-
- private void readObject(ObjectInputStream ois) throws IOException,
- ClassNotFoundException {
+ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
this.isLengthActual = false;
this.actualArrayLength = bits.length;
diff --git a/luni/src/main/java/java/util/Calendar.java b/luni/src/main/java/java/util/Calendar.java
index 3368b2d..bef6e26 100644
--- a/luni/src/main/java/java/util/Calendar.java
+++ b/luni/src/main/java/java/util/Calendar.java
@@ -818,7 +818,7 @@
clone.zone = (TimeZone) zone.clone();
return clone;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
@@ -1028,8 +1028,7 @@
* @return a {@code Calendar} subclass instance set to the current date and time in
* the specified timezone.
*/
- public static synchronized Calendar getInstance(TimeZone timezone,
- Locale locale) {
+ public static synchronized Calendar getInstance(TimeZone timezone, Locale locale) {
return new GregorianCalendar(timezone, locale);
}
@@ -1353,20 +1352,16 @@
/**
* Returns the string representation of this {@code Calendar}.
- *
- * @return the string representation of this {@code Calendar}.
*/
@Override
- @SuppressWarnings("nls")
public String toString() {
- StringBuilder result = new StringBuilder(getClass().getName() + "[time="
- + (isTimeSet ? String.valueOf(time) : "?")
- + ",areFieldsSet="
- + areFieldsSet
- + // ",areAllFieldsSet=" + areAllFieldsSet +
- ",lenient=" + lenient + ",zone=" + zone + ",firstDayOfWeek="
- + firstDayOfWeek + ",minimalDaysInFirstWeek="
- + minimalDaysInFirstWeek);
+ StringBuilder result = new StringBuilder(getClass().getName() +
+ "[time=" + (isTimeSet ? String.valueOf(time) : "?") +
+ ",areFieldsSet=" + areFieldsSet +
+ ",lenient=" + lenient +
+ ",zone=" + zone.getID() +
+ ",firstDayOfWeek=" + firstDayOfWeek +
+ ",minimalDaysInFirstWeek=" + minimalDaysInFirstWeek);
for (int i = 0; i < FIELD_COUNT; i++) {
result.append(',');
result.append(FIELD_NAMES[i]);
@@ -1502,21 +1497,20 @@
}
}
- @SuppressWarnings("nls")
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("areFieldsSet", Boolean.TYPE),
- new ObjectStreamField("fields", int[].class),
- new ObjectStreamField("firstDayOfWeek", Integer.TYPE),
- new ObjectStreamField("isSet", boolean[].class),
- new ObjectStreamField("isTimeSet", Boolean.TYPE),
- new ObjectStreamField("lenient", Boolean.TYPE),
- new ObjectStreamField("minimalDaysInFirstWeek", Integer.TYPE),
- new ObjectStreamField("nextStamp", Integer.TYPE),
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE),
- new ObjectStreamField("time", Long.TYPE),
- new ObjectStreamField("zone", TimeZone.class), };
+ new ObjectStreamField("areFieldsSet", boolean.class),
+ new ObjectStreamField("fields", int[].class),
+ new ObjectStreamField("firstDayOfWeek", int.class),
+ new ObjectStreamField("isSet", boolean[].class),
+ new ObjectStreamField("isTimeSet", boolean.class),
+ new ObjectStreamField("lenient", boolean.class),
+ new ObjectStreamField("minimalDaysInFirstWeek", int.class),
+ new ObjectStreamField("nextStamp", int.class),
+ new ObjectStreamField("serialVersionOnStream", int.class),
+ new ObjectStreamField("time", long.class),
+ new ObjectStreamField("zone", TimeZone.class),
+ };
- @SuppressWarnings("nls")
private void writeObject(ObjectOutputStream stream) throws IOException {
complete();
ObjectOutputStream.PutField putFields = stream.putFields();
@@ -1534,9 +1528,7 @@
stream.writeFields();
}
- @SuppressWarnings("nls")
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField readFields = stream.readFields();
areFieldsSet = readFields.get("areFieldsSet", false);
this.fields = (int[]) readFields.get("fields", null);
diff --git a/luni/src/main/java/java/util/Collections.java b/luni/src/main/java/java/util/Collections.java
index 38005ad..e54ae1b 100644
--- a/luni/src/main/java/java/util/Collections.java
+++ b/luni/src/main/java/java/util/Collections.java
@@ -1535,9 +1535,6 @@
* be compared to each other using the comparator.
*/
@SuppressWarnings("unchecked")
- // BEGIN android-note
- // removed "@param <T> The element type", which is rejected by apicheck
- // END android-note
public static <T> int binarySearch(List<? extends T> list, T object,
Comparator<? super T> comparator) {
if (comparator == null) {
diff --git a/luni/src/main/java/java/util/Comparator.java b/luni/src/main/java/java/util/Comparator.java
index 2d6f598..07582d5 100644
--- a/luni/src/main/java/java/util/Comparator.java
+++ b/luni/src/main/java/java/util/Comparator.java
@@ -32,7 +32,7 @@
/**
* Compares the two specified objects to determine their relative ordering. The ordering
* implied by the return value of this method for all possible pairs of
- * {@code (object1, object2)} should form an <i>equivalence relation</i>.
+ * {@code (lhs, rhs)} should form an <i>equivalence relation</i>.
* This means that
* <ul>
* <li>{@code compare(a,a)} returns zero for all {@code a}</li>
@@ -43,16 +43,16 @@
* (a,b,c)}</li>
* </ul>
*
- * @param object1
+ * @param lhs
* an {@code Object}.
- * @param object2
- * a second {@code Object} to compare with {@code object1}.
- * @return an integer < 0 if {@code object1} is less than {@code object2}, 0 if they are
- * equal, and > 0 if {@code object1} is greater than {@code object2}.
+ * @param rhs
+ * a second {@code Object} to compare with {@code lhs}.
+ * @return an integer < 0 if {@code lhs} is less than {@code rhs}, 0 if they are
+ * equal, and > 0 if {@code lhs} is greater than {@code rhs}.
* @throws ClassCastException
* if objects are not of the correct type.
*/
- public int compare(T object1, T object2);
+ public int compare(T lhs, T rhs);
/**
* Compares this {@code Comparator} with the specified {@code Object} and indicates whether they
diff --git a/luni/src/main/java/java/util/Currency.java b/luni/src/main/java/java/util/Currency.java
index 8ea8a96..0275e32 100644
--- a/luni/src/main/java/java/util/Currency.java
+++ b/luni/src/main/java/java/util/Currency.java
@@ -18,8 +18,6 @@
package java.util;
import java.io.Serializable;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import libcore.icu.ICU;
import libcore.icu.LocaleData;
@@ -36,14 +34,11 @@
private final String currencyCode;
- // BEGIN android-added
// TODO: this isn't set if we're restored from serialized form,
// so getDefaultFractionDigits always returns 0!
private transient int defaultFractionDigits;
- // END android-added
private Currency(String currencyCode) {
- // BEGIN android-changed
this.currencyCode = currencyCode;
// In some places the code XXX is used as the fall back currency.
@@ -66,7 +61,6 @@
// locale's currency.
throw badCurrency(currencyCode);
}
- // END android-changed
}
private IllegalArgumentException badCurrency(String currencyCode) {
@@ -87,14 +81,12 @@
* code.
*/
public static Currency getInstance(String currencyCode) {
- // BEGIN android-changed
Currency currency = codesToCurrencies.get(currencyCode);
if (currency == null) {
currency = new Currency(currencyCode);
codesToCurrencies.put(currencyCode, currency);
}
return currency;
- // END android-changed
}
/**
@@ -108,7 +100,6 @@
* if the locale's country is not a supported ISO 3166 Country.
*/
public static Currency getInstance(Locale locale) {
- // BEGIN android-changed
Currency currency = localesToCurrencies.get(locale);
if (currency != null) {
return currency;
@@ -129,7 +120,6 @@
Currency result = getInstance(currencyCode);
localesToCurrencies.put(locale, result);
return result;
- // END android-changed
}
/**
@@ -183,16 +173,11 @@
* @return the default number of fraction digits for this currency.
*/
public int getDefaultFractionDigits() {
- // BEGIN android-changed
- // return com.ibm.icu.util.Currency.getInstance(currencyCode).getDefaultFractionDigits();
return defaultFractionDigits;
- // END android-changed
}
/**
* Returns this currency's ISO 4217 currency code.
- *
- * @return this currency's ISO 4217 currency code.
*/
@Override
public String toString() {
@@ -202,14 +187,4 @@
private Object readResolve() {
return getInstance(currencyCode);
}
-
- // TODO: remove this in favor of direct access (and no ResourceBundle cruft).
- private static ResourceBundle getCurrencyBundle(final Locale locale) {
- return AccessController.doPrivileged(new PrivilegedAction<ResourceBundle>() {
- public ResourceBundle run() {
- String bundle = "org.apache.harmony.luni.internal.locale.Currency";
- return ResourceBundle.getBundle(bundle, locale);
- }
- });
- }
}
diff --git a/luni/src/main/java/java/util/Date.java b/luni/src/main/java/java/util/Date.java
index 90cd270..0eab8dc 100644
--- a/luni/src/main/java/java/util/Date.java
+++ b/luni/src/main/java/java/util/Date.java
@@ -24,6 +24,7 @@
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
+import libcore.icu.LocaleData;
/**
* {@code Date} represents a specific moment in time, to the millisecond.
@@ -184,7 +185,7 @@
try {
return super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
@@ -470,7 +471,7 @@
throw new IllegalArgumentException();
}
} else if (state == LETTERS && nextState != LETTERS) {
- String text = buffer.toString().toUpperCase();
+ String text = buffer.toString().toUpperCase(Locale.US);
buffer.setLength(0);
if (text.length() == 1) {
throw new IllegalArgumentException();
@@ -653,32 +654,24 @@
}
/**
- * Returns the string representation of this {@code Date} in GMT in the format: 22
- * Jun 1999 13:02:00 GMT
- *
- * @return the string representation of this {@code Date} in GMT.
+ * Returns the string representation of this {@code Date} in GMT in the format
+ * {@code "22 Jun 1999 13:02:00 GMT"}.
*
* @deprecated use {@link DateFormat}
*/
@Deprecated
public String toGMTString() {
- // TODO: why does this insert the year manually instead of using one SimpleDateFormat?
- SimpleDateFormat format1 = new SimpleDateFormat("d MMM ", Locale.US);
- SimpleDateFormat format2 = new SimpleDateFormat(" HH:mm:ss 'GMT'", Locale.US);
+ SimpleDateFormat sdf = new SimpleDateFormat("d MMM y HH:mm:ss 'GMT'", Locale.US);
TimeZone gmtZone = TimeZone.getTimeZone("GMT");
- format1.setTimeZone(gmtZone);
- format2.setTimeZone(gmtZone);
+ sdf.setTimeZone(gmtZone);
GregorianCalendar gc = new GregorianCalendar(gmtZone);
gc.setTimeInMillis(milliseconds);
- return format1.format(this) + gc.get(Calendar.YEAR)
- + format2.format(this);
+ return sdf.format(this);
}
/**
* Returns the string representation of this {@code Date} for the default {@code Locale}.
*
- * @return the string representation of this {@code Date} for the default {@code Locale}.
- *
* @deprecated use {@link DateFormat}
*/
@Deprecated
@@ -693,35 +686,39 @@
* like "Tue Jun 22 13:07:00 PDT 1999". The current default time zone and
* locale are used. If you need control over the time zone or locale,
* use {@code SimpleDateFormat} instead.
- *
- * @return the string representation of this {@code Date}.
*/
@Override
public String toString() {
- // BEGIN android-changed: fixed to use time zone display names ("PST")
- // rather than ids ("America/Los_Angeles").
- // Equivalent to the following one-liner, though that's currently 8x slower
- // at 1655us versus 195us...
+ // TODO: equivalent to the following one-liner, though that's slower on stingray
+ // at 476us versus 69us...
// return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").format(d);
+ LocaleData localeData = LocaleData.get(Locale.US);
Calendar cal = new GregorianCalendar(milliseconds);
TimeZone tz = cal.getTimeZone();
- return dayOfWeekNames[cal.get(Calendar.DAY_OF_WEEK) - 1] + " " + monthNames[cal.get(Calendar.MONTH)]
- + " " + toTwoDigits(cal.get(Calendar.DAY_OF_MONTH)) + " " + toTwoDigits(cal.get(Calendar.HOUR_OF_DAY))
- + ":" + toTwoDigits(cal.get(Calendar.MINUTE)) + ":" + toTwoDigits(cal.get(Calendar.SECOND))
- + " " + tz.getDisplayName(tz.inDaylightTime(this), TimeZone.SHORT) + " " + cal.get(Calendar.YEAR);
- // END android-changed
+ StringBuilder result = new StringBuilder();
+ result.append(localeData.shortWeekdayNames[cal.get(Calendar.DAY_OF_WEEK)]);
+ result.append(' ');
+ result.append(localeData.shortMonthNames[cal.get(Calendar.MONTH)]);
+ result.append(' ');
+ appendTwoDigits(result, cal.get(Calendar.DAY_OF_MONTH));
+ result.append(' ');
+ appendTwoDigits(result, cal.get(Calendar.HOUR_OF_DAY));
+ result.append(':');
+ appendTwoDigits(result, cal.get(Calendar.MINUTE));
+ result.append(':');
+ appendTwoDigits(result, cal.get(Calendar.SECOND));
+ result.append(' ');
+ result.append(tz.getDisplayName(tz.inDaylightTime(this), TimeZone.SHORT));
+ result.append(' ');
+ result.append(cal.get(Calendar.YEAR));
+ return result.toString();
}
- private static final String[] dayOfWeekNames =
- { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
- private static final String[] monthNames =
- { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
- private String toTwoDigits(int n) {
- if (n >= 10) {
- return Integer.toString(n);
- } else {
- return "0" + n;
+ private static void appendTwoDigits(StringBuilder sb, int n) {
+ if (n < 10) {
+ sb.append('0');
}
+ sb.append(n);
}
/**
diff --git a/luni/src/main/java/java/util/EnumMap.java b/luni/src/main/java/java/util/EnumMap.java
index 5da3b86..482a063 100644
--- a/luni/src/main/java/java/util/EnumMap.java
+++ b/luni/src/main/java/java/util/EnumMap.java
@@ -477,7 +477,7 @@
enumMap.initialization(this);
return enumMap;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/EnumSet.java b/luni/src/main/java/java/util/EnumSet.java
index 1b4723e..1a305c8 100644
--- a/luni/src/main/java/java/util/EnumSet.java
+++ b/luni/src/main/java/java/util/EnumSet.java
@@ -15,8 +15,6 @@
*/
package java.util;
-// BEGIN android-added
-
import java.io.Serializable;
import org.apache.harmony.kernel.vm.LangAccess;
@@ -25,14 +23,12 @@
*/
public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
implements Cloneable, Serializable {
- // BEGIN android-added
/*
* null-ok; package access to {@code java.lang}, set during
* first need. This shouldn't be used directly. Instead, use {@link
* SpecialAccess#LANG}, which is guaranteed to be initialized.
*/
static /*package*/ LangAccess LANG_BOOTSTRAP = null;
- // END android-added
private static final long serialVersionUID = 1009687484059888093L;
@@ -57,13 +53,11 @@
if (!elementType.isEnum()) {
throw new ClassCastException(elementType.getClass().getName() + " is not an Enum");
}
- // BEGIN android-changed
E[] enums = SpecialAccess.LANG.getEnumValuesInOrder(elementType);
if (enums.length <= 64) {
return new MiniEnumSet<E>(elementType, enums);
}
return new HugeEnumSet<E>(elementType, enums);
- // END android-changed
}
/**
diff --git a/luni/src/main/java/java/util/Formatter.java b/luni/src/main/java/java/util/Formatter.java
index 490ae8e..845b56c 100644
--- a/luni/src/main/java/java/util/Formatter.java
+++ b/luni/src/main/java/java/util/Formatter.java
@@ -30,8 +30,6 @@
import java.math.BigInteger;
import java.math.MathContext;
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;
@@ -677,9 +675,6 @@
* if the filename does not denote a normal and writable file,
* or if a new file cannot be created, or if any error arises when
* opening or creating the file.
- * @throws SecurityException
- * if there is a {@code SecurityManager} in place which denies permission
- * to write to the file in {@code checkWrite(file.getPath())}.
*/
public Formatter(String fileName) throws FileNotFoundException {
this(new File(fileName));
@@ -703,9 +698,6 @@
* if the filename does not denote a normal and writable file,
* or if a new file cannot be created, or if any error arises when
* opening or creating the file.
- * @throws SecurityException
- * if there is a {@code SecurityManager} in place which denies permission
- * to write to the file in {@code checkWrite(file.getPath())}.
* @throws UnsupportedEncodingException
* if the charset with the specified name is not supported.
*/
@@ -732,9 +724,6 @@
* if the filename does not denote a normal and writable file,
* or if a new file cannot be created, or if any error arises when
* opening or creating the file.
- * @throws SecurityException
- * if there is a {@code SecurityManager} in place which denies permission
- * to write to the file in {@code checkWrite(file.getPath())}.
* @throws UnsupportedEncodingException
* if the charset with the specified name is not supported.
*/
@@ -761,9 +750,6 @@
* if the {@code File} is not a normal and writable {@code File}, or if a
* new {@code File} cannot be created, or if any error rises when opening or
* creating the {@code File}.
- * @throws SecurityException
- * if there is a {@code SecurityManager} in place which denies permission
- * to write to the {@code File} in {@code checkWrite(file.getPath())}.
*/
public Formatter(File file) throws FileNotFoundException {
this(new FileOutputStream(file));
@@ -787,9 +773,6 @@
* if the {@code File} is not a normal and writable {@code File}, or if a
* new {@code File} cannot be created, or if any error rises when opening or
* creating the {@code File}.
- * @throws SecurityException
- * if there is a {@code SecurityManager} in place which denies permission
- * to write to the {@code File} in {@code checkWrite(file.getPath())}.
* @throws UnsupportedEncodingException
* if the charset with the specified name is not supported.
*/
@@ -816,9 +799,6 @@
* if the {@code File} is not a normal and writable {@code File}, or if a
* new {@code File} cannot be created, or if any error rises when opening or
* creating the {@code File}.
- * @throws SecurityException
- * if there is a {@code SecurityManager} in place which denies permission
- * to write to the {@code File} in {@code checkWrite(file.getPath())}.
* @throws UnsupportedEncodingException
* if the charset with the specified name is not supported.
*/
@@ -1632,11 +1612,7 @@
private CharSequence transformFromLineSeparator() {
if (lineSeparator == null) {
- lineSeparator = AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return System.getProperty("line.separator");
- }
- });
+ lineSeparator = System.getProperty("line.separator");
}
return lineSeparator;
}
diff --git a/luni/src/main/java/java/util/GregorianCalendar.java b/luni/src/main/java/java/util/GregorianCalendar.java
index a240708..478e236 100644
--- a/luni/src/main/java/java/util/GregorianCalendar.java
+++ b/luni/src/main/java/java/util/GregorianCalendar.java
@@ -640,9 +640,7 @@
// FIXME: this has to be wrong; useDaylightTime doesn't mean what they think it means!
long newTimeAdjusted = newTime;
if (timeZone.useDaylightTime()) {
- // BEGIN android-changed: removed unnecessary cast
int dstSavings = timeZone.getDSTSavings();
- // END android-changed
newTimeAdjusted += (dstOffset == 0) ? dstSavings : -dstSavings;
}
diff --git a/luni/src/main/java/java/util/HashMap.java b/luni/src/main/java/java/util/HashMap.java
index 7aa6dc2..1b2438b 100644
--- a/luni/src/main/java/java/util/HashMap.java
+++ b/luni/src/main/java/java/util/HashMap.java
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// Completely different implementation from harmony. Runs much faster.
-// BEGIN android-note
-
package java.util;
import java.io.IOException;
@@ -1000,14 +996,8 @@
private static final long serialVersionUID = 362498820763181265L;
- /**
- * Serializable fields.
- *
- * @serialField loadFactor float
- * load factor for this HashMap
- */
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("loadFactor", Float.TYPE)
+ new ObjectStreamField("loadFactor", float.class)
};
private void writeObject(ObjectOutputStream stream) throws IOException {
diff --git a/luni/src/main/java/java/util/HashSet.java b/luni/src/main/java/java/util/HashSet.java
index 2df5299..a35fd56 100644
--- a/luni/src/main/java/java/util/HashSet.java
+++ b/luni/src/main/java/java/util/HashSet.java
@@ -121,7 +121,7 @@
clone.backingMap = (HashMap<E, HashSet<E>>) backingMap.clone();
return clone;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/Hashtable.java b/luni/src/main/java/java/util/Hashtable.java
index 03e80a9..cea29da 100644
--- a/luni/src/main/java/java/util/Hashtable.java
+++ b/luni/src/main/java/java/util/Hashtable.java
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// Completely different implementation from harmony. Runs much faster.
-// BEGIN android-note
-
package java.util;
import java.io.IOException;
@@ -1096,15 +1092,9 @@
private static final long serialVersionUID = 1421746759512286392L;
- /**
- * Serializable fields.
- *
- * @serialField loadFactor float
- * load factor for this Hashtable
- */
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("threshold", Integer.TYPE),
- new ObjectStreamField("loadFactor", Float.TYPE)
+ new ObjectStreamField("threshold", int.class),
+ new ObjectStreamField("loadFactor", float.class),
};
private synchronized void writeObject(ObjectOutputStream stream)
diff --git a/luni/src/main/java/java/util/HugeEnumSet.java b/luni/src/main/java/java/util/HugeEnumSet.java
index 2c6395f..b854372 100644
--- a/luni/src/main/java/java/util/HugeEnumSet.java
+++ b/luni/src/main/java/java/util/HugeEnumSet.java
@@ -31,12 +31,11 @@
private int size;
- // BEGIN android-changed
/**
* Constructs an instance.
*
* @param elementType non-null; type of the elements
- * @param enums non-null; prepopulated array of constants in ordinal
+ * @param enums non-null; pre-populated array of constants in ordinal
* order
*/
HugeEnumSet(Class<E> elementType, E[] enums) {
@@ -44,7 +43,6 @@
this.enums = enums;
bits = new long[(enums.length + BIT_IN_LONG - 1) / BIT_IN_LONG];
}
- // END android-changed
private class HugeEnumSetIterator implements Iterator<E> {
diff --git a/luni/src/main/java/java/util/IdentityHashMap.java b/luni/src/main/java/java/util/IdentityHashMap.java
index 827ffcf..e693f7d 100644
--- a/luni/src/main/java/java/util/IdentityHashMap.java
+++ b/luni/src/main/java/java/util/IdentityHashMap.java
@@ -761,14 +761,12 @@
@Override
public Object clone() {
try {
- IdentityHashMap<K, V> cloneHashMap = (IdentityHashMap<K, V>) super
- .clone();
+ IdentityHashMap<K, V> cloneHashMap = (IdentityHashMap<K, V>) super.clone();
cloneHashMap.elementData = newElementArray(elementData.length);
- System.arraycopy(elementData, 0, cloneHashMap.elementData, 0,
- elementData.length);
+ System.arraycopy(elementData, 0, cloneHashMap.elementData, 0, elementData.length);
return cloneHashMap;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/LinkedHashMap.java b/luni/src/main/java/java/util/LinkedHashMap.java
index 5db8eb6..10fc37c 100644
--- a/luni/src/main/java/java/util/LinkedHashMap.java
+++ b/luni/src/main/java/java/util/LinkedHashMap.java
@@ -15,10 +15,6 @@
* limitations under the License.
*/
-// BEGIN android-note
-// Completely different implementation from harmony. Runs much faster.
-// BEGIN android-note
-
package java.util;
/**
diff --git a/luni/src/main/java/java/util/LinkedList.java b/luni/src/main/java/java/util/LinkedList.java
index 2d264c2..e54438a 100644
--- a/luni/src/main/java/java/util/LinkedList.java
+++ b/luni/src/main/java/java/util/LinkedList.java
@@ -469,7 +469,7 @@
l.addAll(this);
return l;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/Locale.java b/luni/src/main/java/java/util/Locale.java
index 9e26f65..5f3c0b4 100644
--- a/luni/src/main/java/java/util/Locale.java
+++ b/luni/src/main/java/java/util/Locale.java
@@ -22,10 +22,7 @@
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;
/**
* {@code Locale} represents a language/country/variant combination. Locales are used to
@@ -107,89 +104,85 @@
private static final long serialVersionUID = 9149081749638150636L;
- // Initialize a default which is used during static
- // initialization of the default for the platform.
- private static Locale defaultLocale = new Locale();
-
/**
* Locale constant for en_CA.
*/
- public static final Locale CANADA = new Locale("en", "CA");
+ public static final Locale CANADA = new Locale(true, "en", "CA");
/**
* Locale constant for fr_CA.
*/
- public static final Locale CANADA_FRENCH = new Locale("fr", "CA");
+ public static final Locale CANADA_FRENCH = new Locale(true, "fr", "CA");
/**
* Locale constant for zh_CN.
*/
- public static final Locale CHINA = new Locale("zh", "CN");
+ public static final Locale CHINA = new Locale(true, "zh", "CN");
/**
* Locale constant for zh.
*/
- public static final Locale CHINESE = new Locale("zh", "");
+ public static final Locale CHINESE = new Locale(true, "zh", "");
/**
* Locale constant for en.
*/
- public static final Locale ENGLISH = new Locale("en", "");
+ public static final Locale ENGLISH = new Locale(true, "en", "");
/**
* Locale constant for fr_FR.
*/
- public static final Locale FRANCE = new Locale("fr", "FR");
+ public static final Locale FRANCE = new Locale(true, "fr", "FR");
/**
* Locale constant for fr.
*/
- public static final Locale FRENCH = new Locale("fr", "");
+ public static final Locale FRENCH = new Locale(true, "fr", "");
/**
* Locale constant for de.
*/
- public static final Locale GERMAN = new Locale("de", "");
+ public static final Locale GERMAN = new Locale(true, "de", "");
/**
* Locale constant for de_DE.
*/
- public static final Locale GERMANY = new Locale("de", "DE");
+ public static final Locale GERMANY = new Locale(true, "de", "DE");
/**
* Locale constant for it.
*/
- public static final Locale ITALIAN = new Locale("it", "");
+ public static final Locale ITALIAN = new Locale(true, "it", "");
/**
* Locale constant for it_IT.
*/
- public static final Locale ITALY = new Locale("it", "IT");
+ public static final Locale ITALY = new Locale(true, "it", "IT");
/**
* Locale constant for ja_JP.
*/
- public static final Locale JAPAN = new Locale("ja", "JP");
+ public static final Locale JAPAN = new Locale(true, "ja", "JP");
/**
* Locale constant for ja.
*/
- public static final Locale JAPANESE = new Locale("ja", "");
+ public static final Locale JAPANESE = new Locale(true, "ja", "");
/**
* Locale constant for ko_KR.
*/
- public static final Locale KOREA = new Locale("ko", "KR");
+ public static final Locale KOREA = new Locale(true, "ko", "KR");
/**
* Locale constant for ko.
*/
- public static final Locale KOREAN = new Locale("ko", "");
+ public static final Locale KOREAN = new Locale(true, "ko", "");
/**
* Locale constant for zh_CN.
*/
- public static final Locale PRC = new Locale("zh", "CN");
+ public static final Locale PRC = new Locale(true, "zh", "CN");
/**
* Locale constant for the root locale. The root locale has an empty language,
@@ -197,40 +190,46 @@
*
* @since 1.6
*/
- public static final Locale ROOT = new Locale("", "", "");
+ public static final Locale ROOT = new Locale(true, "", "");
/**
* Locale constant for zh_CN.
*/
- public static final Locale SIMPLIFIED_CHINESE = new Locale("zh", "CN");
+ public static final Locale SIMPLIFIED_CHINESE = new Locale(true, "zh", "CN");
/**
* Locale constant for zh_TW.
*/
- public static final Locale TAIWAN = new Locale("zh", "TW");
+ public static final Locale TAIWAN = new Locale(true, "zh", "TW");
/**
* Locale constant for zh_TW.
*/
- public static final Locale TRADITIONAL_CHINESE = new Locale("zh", "TW");
+ public static final Locale TRADITIONAL_CHINESE = new Locale(true, "zh", "TW");
/**
* Locale constant for en_GB.
*/
- public static final Locale UK = new Locale("en", "GB");
+ public static final Locale UK = new Locale(true, "en", "GB");
/**
* Locale constant for en_US.
*/
- public static final Locale US = new Locale("en", "US");
+ public static final Locale US = new Locale(true, "en", "US");
+
+ /**
+ * The current default locale. It is temporarily assigned to US because we
+ * need a default locale to lookup the real default locale.
+ */
+ private static Locale defaultLocale = US;
private static final PropertyPermission setLocalePermission = new PropertyPermission(
"user.language", "write");
static {
- String language = AccessController.doPrivileged(new PriviAction<String>("user.language", "en"));
- String region = AccessController.doPrivileged(new PriviAction<String>("user.region", "US"));
- String variant = AccessController.doPrivileged(new PriviAction<String>("user.variant", ""));
+ String language = System.getProperty("user.language", "en");
+ String region = System.getProperty("user.region", "US");
+ String variant = System.getProperty("user.variant", "");
defaultLocale = new Locale(language, region, variant);
}
@@ -240,13 +239,16 @@
private transient String cachedToStringResult;
/**
- * Constructs a default which is used during static initialization of the
- * default for the platform.
+ * There's a circular dependency between toLowerCase/toUpperCase and
+ * Locale.US. Work around this by avoiding these methods when constructing
+ * the built-in locales.
+ *
+ * @param unused required for this constructor to have a unique signature
*/
- private Locale() {
- languageCode = "en";
- countryCode = "US";
- variantCode = "";
+ private Locale(boolean unused, String lowerCaseLanguageCode, String upperCaseCountryCode) {
+ this.languageCode = lowerCaseLanguageCode;
+ this.countryCode = upperCaseCountryCode;
+ this.variantCode = "";
}
/**
@@ -271,17 +273,14 @@
if (language == null || country == null || variant == null) {
throw new NullPointerException();
}
- if(language.isEmpty() && country.isEmpty()){
+ if (language.isEmpty() && country.isEmpty()) {
languageCode = "";
countryCode = "";
variantCode = variant;
return;
}
- // BEGIN android-changed
- // this.uLocale = new ULocale(language, country, variant);
- // languageCode = uLocale.getLanguage();
- languageCode = Util.toASCIILowerCase(language);
- // END android-changed
+
+ languageCode = language.toLowerCase(Locale.US);
// Map new language codes to the obsolete language
// codes so the correct resource bundles will be used.
if (languageCode.equals("he")) {
@@ -292,11 +291,7 @@
languageCode = "ji";
}
- // countryCode is defined in ASCII character set
- // BEGIN android-changed
- // countryCode = country.length()!=0?uLocale.getCountry():"";
- countryCode = Util.toASCIIUpperCase(country);
- // END android-changed
+ countryCode = country.toUpperCase(Locale.US);
// Work around for be compatible with RI
variantCode = variant;
@@ -560,12 +555,6 @@
if (locale == null) {
throw new NullPointerException();
}
-
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkPermission(setLocalePermission);
- }
-
defaultLocale = locale;
}
@@ -609,10 +598,11 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("country", String.class),
- new ObjectStreamField("hashcode", Integer.TYPE),
- new ObjectStreamField("language", String.class),
- new ObjectStreamField("variant", String.class) };
+ new ObjectStreamField("country", String.class),
+ new ObjectStreamField("hashcode", int.class),
+ new ObjectStreamField("language", String.class),
+ new ObjectStreamField("variant", String.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/util/MapEntry.java b/luni/src/main/java/java/util/MapEntry.java
index b84697b..519b1cd 100644
--- a/luni/src/main/java/java/util/MapEntry.java
+++ b/luni/src/main/java/java/util/MapEntry.java
@@ -43,7 +43,7 @@
try {
return super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/MiniEnumSet.java b/luni/src/main/java/java/util/MiniEnumSet.java
index c4c7364..3876160 100644
--- a/luni/src/main/java/java/util/MiniEnumSet.java
+++ b/luni/src/main/java/java/util/MiniEnumSet.java
@@ -30,19 +30,17 @@
private long bits;
- // BEGIN android-changed
/**
* Constructs an instance.
*
* @param elementType non-null; type of the elements
- * @param enums non-null; prepopulated array of constants in ordinal
+ * @param enums non-null; pre-populated array of constants in ordinal
* order
*/
MiniEnumSet(Class<E> elementType, E[] enums) {
super(elementType);
this.enums = enums;
}
- // END android-changed
private class MiniEnumSetIterator implements Iterator<E> {
diff --git a/luni/src/main/java/java/util/NoSuchElementException.java b/luni/src/main/java/java/util/NoSuchElementException.java
index 3583fb9..ed9476a 100644
--- a/luni/src/main/java/java/util/NoSuchElementException.java
+++ b/luni/src/main/java/java/util/NoSuchElementException.java
@@ -19,12 +19,8 @@
/**
- * A {@code NoSuchElementException} is thrown when trying to retrieve an element
- * past the end of an Enumeration, or the first or last element from an empty
- * Vector.
- *
- * @see Enumeration
- * @see java.lang.RuntimeException
+ * Thrown when trying to retrieve an element
+ * past the end of an Enumeration or Iterator.
*/
public class NoSuchElementException extends RuntimeException {
diff --git a/luni/src/main/java/java/util/Properties.java b/luni/src/main/java/java/util/Properties.java
index bff7ebc..9df3be6 100644
--- a/luni/src/main/java/java/util/Properties.java
+++ b/luni/src/main/java/java/util/Properties.java
@@ -31,11 +31,9 @@
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
-import java.security.AccessController;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-import org.apache.harmony.luni.util.PriviAction;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -557,7 +555,7 @@
*/
public synchronized void store(Writer writer, String comment) throws IOException {
if (lineSeparator == null) {
- lineSeparator = AccessController.doPrivileged(new PriviAction<String>("line.separator"));
+ lineSeparator = System.getProperty("line.separator");
}
if (comment != null) {
diff --git a/luni/src/main/java/java/util/PropertyPermission.java b/luni/src/main/java/java/util/PropertyPermission.java
index b4ac105..a5a4738 100644
--- a/luni/src/main/java/java/util/PropertyPermission.java
+++ b/luni/src/main/java/java/util/PropertyPermission.java
@@ -24,7 +24,6 @@
import java.security.BasicPermission;
import java.security.Permission;
import java.security.PermissionCollection;
-import org.apache.harmony.luni.util.Util;
/**
* {@code PropertyPermission} objects represent a permission to access system
@@ -60,8 +59,7 @@
}
private void decodeActions(String actions) {
- StringTokenizer tokenizer = new StringTokenizer(Util.toASCIILowerCase(actions),
- " \t\n\r,");
+ StringTokenizer tokenizer = new StringTokenizer(actions.toLowerCase(Locale.US), " \t\n\r,");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equals("read")) {
@@ -153,8 +151,9 @@
return new PropertyPermissionCollection();
}
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "actions", String.class) };
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("actions", String.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/util/PropertyPermissionCollection.java b/luni/src/main/java/java/util/PropertyPermissionCollection.java
index 3d4b3a5..6736d32 100644
--- a/luni/src/main/java/java/util/PropertyPermissionCollection.java
+++ b/luni/src/main/java/java/util/PropertyPermissionCollection.java
@@ -76,8 +76,9 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("permissions", Hashtable.class),
- new ObjectStreamField("all_allowed", Boolean.TYPE) };
+ new ObjectStreamField("permissions", Hashtable.class),
+ new ObjectStreamField("all_allowed", boolean.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
diff --git a/luni/src/main/java/java/util/Random.java b/luni/src/main/java/java/util/Random.java
index dac8eec..601e31e 100644
--- a/luni/src/main/java/java/util/Random.java
+++ b/luni/src/main/java/java/util/Random.java
@@ -133,7 +133,7 @@
/**
* Returns a pseudo-random (approximately) normally distributed
* {@code double} with mean 0.0 and standard deviation 1.0.
- * This method uses the <i>polar method<i> of G. E. P. Box, M.
+ * This method uses the <i>polar method</i> of G. E. P. Box, M.
* E. Muller, and G. Marsaglia, as described by Donald E. Knuth in <i>The
* Art of Computer Programming, Volume 2: Seminumerical Algorithms</i>,
* section 3.4.1, subsection C, algorithm P.
diff --git a/luni/src/main/java/java/util/ResourceBundle.java b/luni/src/main/java/java/util/ResourceBundle.java
index 3c4442c..5510f8f 100644
--- a/luni/src/main/java/java/util/ResourceBundle.java
+++ b/luni/src/main/java/java/util/ResourceBundle.java
@@ -24,8 +24,6 @@
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import libcore.io.IoUtils;
/**
@@ -271,16 +269,11 @@
}
private static ClassLoader getLoader() {
- return AccessController
- .doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- ClassLoader cl = this.getClass().getClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- return cl;
- }
- });
+ ClassLoader cl = ResourceBundle.class.getClassLoader();
+ if (cl == null) {
+ cl = ClassLoader.getSystemClassLoader();
+ }
+ return cl;
}
/**
@@ -688,7 +681,6 @@
}
}
- @SuppressWarnings("nls")
/**
* ResourceBundle.Control is a static utility class defines ResourceBundle
* load access methods, its default access order is as the same as before.
@@ -885,24 +877,16 @@
if (format == null || loader == null) {
throw new NullPointerException();
}
- InputStream streams = null;
final String bundleName = toBundleName(baseName, locale);
final ClassLoader clsloader = loader;
ResourceBundle ret;
- Class<?> cls = null;
if (JAVACLASS == format) {
- cls = AccessController
- .doPrivileged(new PrivilegedAction<Class<?>>() {
- public Class<?> run() {
- try {
- return clsloader.loadClass(bundleName);
- } catch (Exception e) {
- return null;
- } catch (NoClassDefFoundError e) {
- return null;
- }
- }
- });
+ Class<?> cls = null;
+ try {
+ cls = clsloader.loadClass(bundleName);
+ } catch (Exception e) {
+ } catch (NoClassDefFoundError e) {
+ }
if (cls == null) {
return null;
}
@@ -915,8 +899,8 @@
}
}
if (JAVAPROPERTIES == format) {
- final String resourceName = toResourceName(bundleName,
- "properties");
+ InputStream streams = null;
+ final String resourceName = toResourceName(bundleName, "properties");
if (reload) {
URL url = null;
try {
@@ -931,13 +915,7 @@
}
} else {
try {
- streams = AccessController
- .doPrivileged(new PrivilegedAction<InputStream>() {
- public InputStream run() {
- return clsloader
- .getResourceAsStream(resourceName);
- }
- });
+ streams = clsloader.getResourceAsStream(resourceName);
} catch (NullPointerException e) {
// do nothing
}
diff --git a/luni/src/main/java/java/util/Scanner.java b/luni/src/main/java/java/util/Scanner.java
index 85de1e7..8f889b3 100644
--- a/luni/src/main/java/java/util/Scanner.java
+++ b/luni/src/main/java/java/util/Scanner.java
@@ -79,20 +79,10 @@
private static final Pattern LINE_PATTERN;
static {
- String terminator = "\n|\r\n|\r|\u0085|\u2028|\u2029";
-
- LINE_TERMINATOR = Pattern.compile(terminator);
-
- // BEGIN android-note
- // consider plain old string concatenation for better performance
- // END android-note
- StringBuilder multiTerminator = new StringBuilder();
- MULTI_LINE_TERMINATOR = Pattern.compile(multiTerminator.append("(")
- .append(terminator).append(")+").toString());
- StringBuilder line = new StringBuilder();
- LINE_PATTERN = Pattern.compile(line.append(".*(")
- .append(terminator).append(")|.+(")
- .append(terminator).append(")?").toString());
+ String NL = "\n|\r\n|\r|\u0085|\u2028|\u2029";
+ LINE_TERMINATOR = Pattern.compile(NL);
+ MULTI_LINE_TERMINATOR = Pattern.compile("(" + NL + ")+");
+ LINE_PATTERN = Pattern.compile(".*(" + NL + ")|.+(" + NL + ")?");
}
// The pattern matches anything.
diff --git a/luni/src/main/java/java/util/ServiceLoader.java b/luni/src/main/java/java/util/ServiceLoader.java
index 8fc232f..beacaab 100644
--- a/luni/src/main/java/java/util/ServiceLoader.java
+++ b/luni/src/main/java/java/util/ServiceLoader.java
@@ -20,8 +20,6 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import libcore.io.IoUtils;
/**
@@ -167,20 +165,16 @@
* @hide
*/
public static <S> S loadFromSystemProperty(final Class<S> service) {
- return AccessController.doPrivileged(new PrivilegedAction<S>() {
- public S run() {
- try {
- final String className = System.getProperty(service.getName());
- if (className != null) {
- Class<?> c = ClassLoader.getSystemClassLoader().loadClass(className);
- return (S) c.newInstance();
- }
- return null;
- } catch (Exception e) {
- throw new Error(e);
- }
+ try {
+ final String className = System.getProperty(service.getName());
+ if (className != null) {
+ Class<?> c = ClassLoader.getSystemClassLoader().loadClass(className);
+ return (S) c.newInstance();
}
- });
+ return null;
+ } catch (Exception e) {
+ throw new Error(e);
+ }
}
@Override
diff --git a/luni/src/main/java/java/util/SimpleTimeZone.java b/luni/src/main/java/java/util/SimpleTimeZone.java
index a57ab9a..628e0d3 100644
--- a/luni/src/main/java/java/util/SimpleTimeZone.java
+++ b/luni/src/main/java/java/util/SimpleTimeZone.java
@@ -74,12 +74,6 @@
private int dstSavings = 3600000;
- // BEGIN android-removed
- // private final transient com.ibm.icu.util.TimeZone icuTZ;
- //
- // private final transient boolean isSimple;
- // END android-removed
-
/**
* Constructs a {@code SimpleTimeZone} with the given base time zone offset from GMT
* and time zone ID. Timezone IDs can be obtained from
@@ -95,16 +89,6 @@
public SimpleTimeZone(int offset, final String name) {
setID(name);
rawOffset = offset;
- // BEGIN android-removed
- // icuTZ = getICUTimeZone(name);
- // if (icuTZ instanceof com.ibm.icu.util.SimpleTimeZone) {
- // isSimple = true;
- // icuTZ.setRawOffset(offset);
- // } else {
- // isSimple = false;
- // }
- // useDaylight = icuTZ.useDaylightTime();
- // END android-removed
}
/**
@@ -228,33 +212,15 @@
public SimpleTimeZone(int offset, String name, int startMonth,
int startDay, int startDayOfWeek, int startTime, int endMonth,
int endDay, int endDayOfWeek, int endTime, int daylightSavings) {
- // BEGIN android-changed
- // icuTZ = getICUTimeZone(name);
- // if (icuTZ instanceof com.ibm.icu.util.SimpleTimeZone) {
- // isSimple = true;
- // com.ibm.icu.util.SimpleTimeZone tz = (com.ibm.icu.util.SimpleTimeZone)icuTZ;
- // tz.setRawOffset(offset);
- // tz.setStartRule(startMonth, startDay, startDayOfWeek, startTime);
- // tz.setEndRule(endMonth, endDay, endDayOfWeek, endTime);
- // tz.setDSTSavings(daylightSavings);
- // } else {
- // isSimple = false;
- // }
- // setID(name);
- // rawOffset = offset;
this(offset, name);
- // END android-changed
if (daylightSavings <= 0) {
throw new IllegalArgumentException("Invalid daylightSavings: " + daylightSavings);
}
dstSavings = daylightSavings;
+ // TODO: do we need to set useDaylight is dstSavings != 0?
setStartRule(startMonth, startDay, startDayOfWeek, startTime);
setEndRule(endMonth, endDay, endDayOfWeek, endTime);
-
- // BEGIN android-removed
- // useDaylight = daylightSavings > 0 || icuTZ.useDaylightTime();
- // END android-removed
}
/**
@@ -375,8 +341,6 @@
checkDay(month, day);
}
- // BEGIN android-changed
- // return icuTZ.getOffset(era, year, month, day, dayOfWeek, time);
if (!useDaylightTime() || era != GregorianCalendar.AD || year < startYear) {
return rawOffset;
}
@@ -495,19 +459,17 @@
}
}
return rawOffset + dstSavings;
- // END android-changed
}
@Override
public int getOffset(long time) {
- // BEGIN android-changed: simplified variant of the ICU4J code.
+ // Simplified variant of the ICU4J code.
if (!useDaylightTime()) {
return rawOffset;
}
int[] fields = Grego.timeToFields(time + rawOffset, null);
return getOffset(GregorianCalendar.AD, fields[0], fields[1], fields[2],
fields[3], fields[5]);
- // END android-changed
}
@Override
@@ -556,9 +518,7 @@
@Override
public boolean inDaylightTime(Date time) {
- // BEGIN android-changed: reuse getOffset.
return useDaylightTime() && getOffset(time.getTime()) != rawOffset;
- // END android-changed
}
private boolean isLeapYear(int year) {
@@ -568,12 +528,10 @@
return year % 4 == 0;
}
- // BEGIN android-added
private int mod7(int num1) {
int rem = num1 % 7;
return (num1 < 0 && rem < 0) ? 7 + rem : rem;
}
- // END android-added
/**
* Sets the daylight savings offset in milliseconds for this {@code SimpleTimeZone}.
@@ -656,12 +614,6 @@
endDayOfWeek = 0; // Initialize this value for hasSameRules()
endTime = time;
setEndMode();
- // BEGIN android-removed
- // if (isSimple) {
- // ((com.ibm.icu.util.SimpleTimeZone) icuTZ).setEndRule(month,
- // dayOfMonth, time);
- // }
- // END android-removed
}
/**
@@ -685,12 +637,6 @@
endDayOfWeek = dayOfWeek;
endTime = time;
setEndMode();
- // BEGIN android-removed
- // if (isSimple) {
- // ((com.ibm.icu.util.SimpleTimeZone) icuTZ).setEndRule(month, day,
- // dayOfWeek, time);
- // }
- // END android-removed
}
/**
@@ -709,19 +655,12 @@
* @param after
* selects the day after or before the day of month.
*/
- public void setEndRule(int month, int day, int dayOfWeek, int time,
- boolean after) {
+ public void setEndRule(int month, int day, int dayOfWeek, int time, boolean after) {
endMonth = month;
endDay = after ? day : -day;
endDayOfWeek = -dayOfWeek;
endTime = time;
setEndMode();
- // BEGIN android-removed
- // if (isSimple) {
- // ((com.ibm.icu.util.SimpleTimeZone) icuTZ).setEndRule(month, day,
- // dayOfWeek, time, after);
- // }
- // END android-removed
}
/**
@@ -733,9 +672,6 @@
@Override
public void setRawOffset(int offset) {
rawOffset = offset;
- // BEGIN android-removed
- // icuTZ.setRawOffset(offset);
- // END android-removed
}
private void setStartMode() {
@@ -787,12 +723,6 @@
startDayOfWeek = 0; // Initialize this value for hasSameRules()
startTime = time;
setStartMode();
- // BEGIN android-removed
- // if (isSimple) {
- // ((com.ibm.icu.util.SimpleTimeZone) icuTZ).setStartRule(month,
- // dayOfMonth, time);
- // }
- // END android-removed
}
/**
@@ -816,12 +746,6 @@
startDayOfWeek = dayOfWeek;
startTime = time;
setStartMode();
- // BEGIN android-removed
- // if (isSimple) {
- // ((com.ibm.icu.util.SimpleTimeZone) icuTZ).setStartRule(month, day,
- // dayOfWeek, time);
- // }
- // END android-removed
}
/**
@@ -840,19 +764,12 @@
* @param after
* selects the day after or before the day of month.
*/
- public void setStartRule(int month, int day, int dayOfWeek, int time,
- boolean after) {
+ public void setStartRule(int month, int day, int dayOfWeek, int time, boolean after) {
startMonth = month;
startDay = after ? day : -day;
startDayOfWeek = -dayOfWeek;
startTime = time;
setStartMode();
- // BEGIN android-removed
- // if (isSimple) {
- // ((com.ibm.icu.util.SimpleTimeZone) icuTZ).setStartRule(month, day,
- // dayOfWeek, time, after);
- // }
- // END android-removed
}
/**
@@ -906,22 +823,23 @@
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("dstSavings", Integer.TYPE),
- new ObjectStreamField("endDay", Integer.TYPE),
- new ObjectStreamField("endDayOfWeek", Integer.TYPE),
- new ObjectStreamField("endMode", Integer.TYPE),
- new ObjectStreamField("endMonth", Integer.TYPE),
- new ObjectStreamField("endTime", Integer.TYPE),
- new ObjectStreamField("monthLength", byte[].class),
- new ObjectStreamField("rawOffset", Integer.TYPE),
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE),
- new ObjectStreamField("startDay", Integer.TYPE),
- new ObjectStreamField("startDayOfWeek", Integer.TYPE),
- new ObjectStreamField("startMode", Integer.TYPE),
- new ObjectStreamField("startMonth", Integer.TYPE),
- new ObjectStreamField("startTime", Integer.TYPE),
- new ObjectStreamField("startYear", Integer.TYPE),
- new ObjectStreamField("useDaylight", Boolean.TYPE), };
+ new ObjectStreamField("dstSavings", int.class),
+ new ObjectStreamField("endDay", int.class),
+ new ObjectStreamField("endDayOfWeek", int.class),
+ new ObjectStreamField("endMode", int.class),
+ new ObjectStreamField("endMonth", int.class),
+ new ObjectStreamField("endTime", int.class),
+ new ObjectStreamField("monthLength", byte[].class),
+ new ObjectStreamField("rawOffset", int.class),
+ new ObjectStreamField("serialVersionOnStream", int.class),
+ new ObjectStreamField("startDay", int.class),
+ new ObjectStreamField("startDayOfWeek", int.class),
+ new ObjectStreamField("startMode", int.class),
+ new ObjectStreamField("startMonth", int.class),
+ new ObjectStreamField("startTime", int.class),
+ new ObjectStreamField("startYear", int.class),
+ new ObjectStreamField("useDaylight", boolean.class),
+ };
private void writeObject(ObjectOutputStream stream) throws IOException {
int sEndDay = endDay, sEndDayOfWeek = endDayOfWeek + 1, sStartDay = startDay, sStartDayOfWeek = startDayOfWeek + 1;
diff --git a/luni/src/main/java/java/util/StringTokenizer.java b/luni/src/main/java/java/util/StringTokenizer.java
index e581088..1b07604 100644
--- a/luni/src/main/java/java/util/StringTokenizer.java
+++ b/luni/src/main/java/java/util/StringTokenizer.java
@@ -18,88 +18,24 @@
package java.util;
/**
- * The {@code StringTokenizer} class allows an application to break a string
- * into tokens by performing code point comparison. The {@code StringTokenizer}
- * methods do not distinguish among identifiers, numbers, and quoted strings,
- * nor do they recognize and skip comments.
- * <p>
- * The set of delimiters (the codepoints that separate tokens) may be specified
- * either at creation time or on a per-token basis.
- * <p>
- * An instance of {@code StringTokenizer} behaves in one of three ways,
- * depending on whether it was created with the {@code returnDelimiters} flag
- * having the value {@code true} or {@code false}:
- * <ul>
- * <li>If returnDelims is {@code false}, delimiter code points serve to separate
- * tokens. A token is a maximal sequence of consecutive code points that are not
- * delimiters.
- * <li>If returnDelims is {@code true}, delimiter code points are themselves
- * considered to be tokens. In this case a token will be received for each
- * delimiter code point.
- * </ul>
- * <p>
- * A token is thus either one delimiter code point, or a maximal sequence of
- * consecutive code points that are not delimiters.
- * <p>
- * A {@code StringTokenizer} object internally maintains a current position
- * within the string to be tokenized. Some operations advance this current
- * position past the code point processed.
- * <p>
- * A token is returned by taking a substring of the string that was used to
- * create the {@code StringTokenizer} object.
- * <p>
- * Here's an example of the use of the default delimiter {@code StringTokenizer}
- * : <blockquote>
+ * Breaks a string into tokens; new code should probably use {@link String#split}.
*
+ * <blockquote>
* <pre>
- * StringTokenizer st = new StringTokenizer("this is a test");
+ * // Legacy code:
+ * StringTokenizer st = new StringTokenizer("a:b:c", ":");
* while (st.hasMoreTokens()) {
- * println(st.nextToken());
+ * System.err.println(st.nextToken());
+ * }
+ *
+ * // New code:
+ * for (String token : "a:b:c".split(":")) {
+ * System.err.println(token);
* }
* </pre>
- *
* </blockquote>
- * <p>
- * This prints the following output: <blockquote>
*
- * <pre>
- * this
- * is
- * a
- * test
- * </pre>
- *
- * </blockquote>
- * <p>
- * Here's an example of how to use a {@code StringTokenizer} with a user
- * specified delimiter: <blockquote>
- *
- * <pre>
- * StringTokenizer st = new StringTokenizer(
- * "this is a test with supplementary characters \ud800\ud800\udc00\udc00",
- * " \ud800\udc00");
- * while (st.hasMoreTokens()) {
- * println(st.nextToken());
- * }
- * </pre>
- *
- * </blockquote>
- * <p>
- * This prints the following output: <blockquote>
- *
- * <pre>
- * this
- * is
- * a
- * test
- * with
- * supplementary
- * characters
- * \ud800
- * \udc00
- * </pre>
- *
- * </blockquote>
+ * @since 1.0
*/
public class StringTokenizer implements Enumeration<Object> {
diff --git a/luni/src/main/java/java/util/TimeZone.java b/luni/src/main/java/java/util/TimeZone.java
index 22ab911..b8d72af 100644
--- a/luni/src/main/java/java/util/TimeZone.java
+++ b/luni/src/main/java/java/util/TimeZone.java
@@ -170,11 +170,14 @@
boolean useDaylight = daylightTime && useDaylightTime();
- String result = TimeZones.getDisplayName(getID(), daylightTime, style, locale);
+ String[][] zoneStrings = TimeZones.getZoneStrings(locale);
+ String result = TimeZones.getDisplayName(zoneStrings, getID(), daylightTime, style);
if (result != null) {
return result;
}
+ // TODO: do we ever get here?
+
int offset = getRawOffset();
if (useDaylight && this instanceof SimpleTimeZone) {
offset += getDSTSavings();
diff --git a/luni/src/main/java/java/util/Timer.java b/luni/src/main/java/java/util/Timer.java
index 15b71c0..bf8a3a0 100644
--- a/luni/src/main/java/java/util/Timer.java
+++ b/luni/src/main/java/java/util/Timer.java
@@ -175,7 +175,7 @@
private boolean finished;
/**
- * Vector consists of scheduled events, sorted according to
+ * Contains scheduled events, sorted according to
* {@code when} field of TaskScheduled object.
*/
private TimerHeap tasks = new TimerHeap();
diff --git a/luni/src/main/java/java/util/TreeSet.java b/luni/src/main/java/java/util/TreeSet.java
index e4f2136..63a51c9 100644
--- a/luni/src/main/java/java/util/TreeSet.java
+++ b/luni/src/main/java/java/util/TreeSet.java
@@ -163,7 +163,7 @@
}
return clone;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/Vector.java b/luni/src/main/java/java/util/Vector.java
index dcd19f2..5a4224f 100644
--- a/luni/src/main/java/java/util/Vector.java
+++ b/luni/src/main/java/java/util/Vector.java
@@ -262,7 +262,7 @@
vector.elementData = elementData.clone();
return vector;
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
}
diff --git a/luni/src/main/java/java/util/concurrent/ExecutorService.java b/luni/src/main/java/java/util/concurrent/ExecutorService.java
index ddd77bf..89688e4 100644
--- a/luni/src/main/java/java/util/concurrent/ExecutorService.java
+++ b/luni/src/main/java/java/util/concurrent/ExecutorService.java
@@ -119,14 +119,6 @@
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {@link #awaitTermination awaitTermination}
* to do that.
- *
- * @throws SecurityException if a security manager exists and
- * shutting down this ExecutorService may manipulate
- * threads that the caller is not permitted to modify
- * because it does not hold {@link
- * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
- * or the security manager's <tt>checkAccess</tt> method
- * denies access.
*/
void shutdown();
@@ -145,13 +137,6 @@
* task that fails to respond to interrupts may never terminate.
*
* @return list of tasks that never commenced execution
- * @throws SecurityException if a security manager exists and
- * shutting down this ExecutorService may manipulate
- * threads that the caller is not permitted to modify
- * because it does not hold {@link
- * java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
- * or the security manager's <tt>checkAccess</tt> method
- * denies access.
*/
List<Runnable> shutdownNow();
diff --git a/luni/src/main/java/java/util/concurrent/ThreadPoolExecutor.java b/luni/src/main/java/java/util/concurrent/ThreadPoolExecutor.java
index da2c4c5..6622af8 100644
--- a/luni/src/main/java/java/util/concurrent/ThreadPoolExecutor.java
+++ b/luni/src/main/java/java/util/concurrent/ThreadPoolExecutor.java
@@ -75,12 +75,7 @@
* alter the thread's name, thread group, priority, daemon status,
* etc. If a {@code ThreadFactory} fails to create a thread when asked
* by returning null from {@code newThread}, the executor will
- * continue, but might not be able to execute any tasks. Threads
- * should possess the "modifyThread" {@code RuntimePermission}. If
- * worker threads or other threads using the pool do not possess this
- * permission, service may be degraded: configuration changes may not
- * take effect in a timely manner, and a shutdown pool may remain in a
- * state in which termination is possible but not completed.</dd>
+ * continue, but might not be able to execute any tasks.</dd>
*
* <dt>Keep-alive times</dt>
*
diff --git a/luni/src/main/java/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java b/luni/src/main/java/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java
index a13c920..e8a0d57 100644
--- a/luni/src/main/java/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java
+++ b/luni/src/main/java/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java
@@ -252,15 +252,6 @@
// END android-changed
modifiers = field.getModifiers();
- // BEGIN android-added
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- int type = Modifier.isPublic(modifiers)
- ? Member.PUBLIC : Member.DECLARED;
- smgr.checkMemberAccess(tclass, type);
- smgr.checkPackageAccess(tclass.getPackage().getName());
- }
- // END android-added
// BEGIN android-removed
// modifiers = field.getModifiers();
// sun.reflect.misc.ReflectUtil.ensureMemberAccess(
diff --git a/luni/src/main/java/java/util/concurrent/atomic/AtomicLongFieldUpdater.java b/luni/src/main/java/java/util/concurrent/atomic/AtomicLongFieldUpdater.java
index 3d6e5d6..21ef748 100644
--- a/luni/src/main/java/java/util/concurrent/atomic/AtomicLongFieldUpdater.java
+++ b/luni/src/main/java/java/util/concurrent/atomic/AtomicLongFieldUpdater.java
@@ -248,15 +248,6 @@
field = tclass.getDeclaredField(fieldName);
caller = VMStack.getStackClass2(); // android-changed
modifiers = field.getModifiers();
- // BEGIN android-added
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- int type = Modifier.isPublic(modifiers)
- ? Member.PUBLIC : Member.DECLARED;
- smgr.checkMemberAccess(tclass, type);
- smgr.checkPackageAccess(tclass.getPackage().getName());
- }
- // END android-added
// BEGIN android-removed
// sun.reflect.misc.ReflectUtil.ensureMemberAccess(
// caller, tclass, null, modifiers);
@@ -342,15 +333,6 @@
field = tclass.getDeclaredField(fieldName);
caller = VMStack.getStackClass2(); // android-changed
modifiers = field.getModifiers();
- // BEGIN android-added
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- int type = Modifier.isPublic(modifiers)
- ? Member.PUBLIC : Member.DECLARED;
- smgr.checkMemberAccess(tclass, type);
- smgr.checkPackageAccess(tclass.getPackage().getName());
- }
- // END android-added
// BEGIN android-removed
// sun.reflect.misc.ReflectUtil.ensureMemberAccess(
// caller, tclass, null, modifiers);
diff --git a/luni/src/main/java/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java b/luni/src/main/java/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java
index e4ae0cf..8b3da0b 100644
--- a/luni/src/main/java/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java
+++ b/luni/src/main/java/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java
@@ -180,15 +180,6 @@
field = tclass.getDeclaredField(fieldName);
caller = VMStack.getStackClass2(); // android-changed
modifiers = field.getModifiers();
- // BEGIN android-added
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- int type = Modifier.isPublic(modifiers)
- ? Member.PUBLIC : Member.DECLARED;
- smgr.checkMemberAccess(tclass, type);
- smgr.checkPackageAccess(tclass.getPackage().getName());
- }
- // END android-added
// BEGIN android-removed
// sun.reflect.misc.ReflectUtil.ensureMemberAccess(
// caller, tclass, null, modifiers);
diff --git a/luni/src/main/java/java/util/jar/Attributes.java b/luni/src/main/java/java/util/jar/Attributes.java
index 9041c26..e751b27 100644
--- a/luni/src/main/java/java/util/jar/Attributes.java
+++ b/luni/src/main/java/java/util/jar/Attributes.java
@@ -18,11 +18,11 @@
package java.util.jar;
import java.nio.charset.Charsets;
+import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
-import org.apache.harmony.archive.util.Util;
/**
* The {@code Attributes} class is used to store values for manifest entries.
@@ -229,12 +229,13 @@
*/
@Override
public boolean equals(Object object) {
- if (object == null || object.getClass() != getClass()
- || object.hashCode() != hashCode()) {
+ if (object == null || object.getClass() != getClass()) {
return false;
}
- return Util.asciiEqualsIgnoreCase(name, ((Name) object).name);
+ byte[] otherName = ((Name) object).name;
+ return Arrays.equals(name, otherName) || new String(name, Charsets.US_ASCII)
+ .equalsIgnoreCase(new String(otherName, Charsets.US_ASCII));
}
/**
@@ -432,7 +433,7 @@
try {
clone = (Attributes) super.clone();
} catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+ throw new AssertionError(e);
}
clone.map = (Map<Object, Object>) ((HashMap) map).clone();
return clone;
diff --git a/luni/src/main/java/java/util/jar/JarFile.java b/luni/src/main/java/java/util/jar/JarFile.java
index 6ec24c6..a26a602 100644
--- a/luni/src/main/java/java/util/jar/JarFile.java
+++ b/luni/src/main/java/java/util/jar/JarFile.java
@@ -27,7 +27,6 @@
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import libcore.io.Streams;
-import org.apache.harmony.archive.util.Util;
/**
* {@code JarFile} is used to read jar entries and their associated data from
@@ -331,7 +330,7 @@
for (ZipEntry entry : metaEntries) {
String entryName = entry.getName();
// Is this the entry for META-INF/MANIFEST.MF ?
- if (manifestEntry == null && Util.asciiEqualsIgnoreCase(MANIFEST_NAME, entryName)) {
+ if (manifestEntry == null && entryName.equalsIgnoreCase(MANIFEST_NAME)) {
manifestEntry = entry;
// If there is no verifier then we don't need to look any further.
if (verifier == null) {
@@ -340,9 +339,9 @@
} else {
// Is this an entry that the verifier needs?
if (verifier != null
- && (Util.asciiEndsWithIgnoreCase(entryName, ".SF")
- || Util.asciiEndsWithIgnoreCase(entryName, ".DSA")
- || Util.asciiEndsWithIgnoreCase(entryName, ".RSA"))) {
+ && (endsWithIgnoreCase(entryName, ".SF")
+ || endsWithIgnoreCase(entryName, ".DSA")
+ || endsWithIgnoreCase(entryName, ".RSA"))) {
signed = true;
InputStream is = super.getInputStream(entry);
try {
@@ -360,6 +359,10 @@
}
}
+ private static boolean endsWithIgnoreCase(String s, String suffix) {
+ return s.regionMatches(true, s.length() - suffix.length(), suffix, 0, suffix.length());
+ }
+
/**
* Return an {@code InputStream} for reading the decompressed contents of
* ZIP entry.
diff --git a/luni/src/main/java/java/util/jar/JarInputStream.java b/luni/src/main/java/java/util/jar/JarInputStream.java
index 76180d2..03f765f 100644
--- a/luni/src/main/java/java/util/jar/JarInputStream.java
+++ b/luni/src/main/java/java/util/jar/JarInputStream.java
@@ -21,9 +21,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-import org.apache.harmony.luni.util.Util;
/**
* The input stream from which the JAR file to be read may be fetched. It is
@@ -58,8 +58,7 @@
* If an error occurs reading entries from the input stream.
* @see ZipInputStream#ZipInputStream(InputStream)
*/
- public JarInputStream(InputStream stream, boolean verify)
- throws IOException {
+ public JarInputStream(InputStream stream, boolean verify) throws IOException {
super(stream);
if (verify) {
verifier = new JarVerifier("JarInputStream");
@@ -67,22 +66,19 @@
if ((mEntry = getNextJarEntry()) == null) {
return;
}
- String name = Util.toASCIIUpperCase(mEntry.getName());
- if (name.equals(JarFile.META_DIR)) {
+ if (mEntry.getName().equalsIgnoreCase(JarFile.META_DIR)) {
mEntry = null; // modifies behavior of getNextJarEntry()
closeEntry();
mEntry = getNextJarEntry();
- name = mEntry.getName().toUpperCase();
}
- if (name.equals(JarFile.MANIFEST_NAME)) {
+ if (mEntry.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
mEntry = null;
manifest = new Manifest(this, verify);
closeEntry();
if (verify) {
verifier.setManifest(manifest);
if (manifest != null) {
- verifier.mainAttributesEnd = manifest
- .getMainAttributesEnd();
+ verifier.mainAttributesEnd = manifest.getMainAttributesEnd();
}
}
@@ -198,8 +194,7 @@
return null;
}
if (verifier != null) {
- isMeta = Util.toASCIIUpperCase(jarEntry.getName()).startsWith(
- JarFile.META_DIR);
+ isMeta = jarEntry.getName().toUpperCase(Locale.US).startsWith(JarFile.META_DIR);
if (isMeta) {
verStream = new ByteArrayOutputStream();
} else {
diff --git a/luni/src/main/java/java/util/jar/JarVerifier.java b/luni/src/main/java/java/util/jar/JarVerifier.java
index cacafa0..81bbe77 100644
--- a/luni/src/main/java/java/util/jar/JarVerifier.java
+++ b/luni/src/main/java/java/util/jar/JarVerifier.java
@@ -25,14 +25,15 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
+import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.harmony.luni.util.Base64;
-import org.apache.harmony.luni.util.Util;
import org.apache.harmony.security.utils.JarUtils;
/**
@@ -171,31 +172,23 @@
return null;
}
- Vector<Certificate> certs = new Vector<Certificate>();
- Iterator<Map.Entry<String, HashMap<String, Attributes>>> it = signatures
- .entrySet().iterator();
+ ArrayList<Certificate> certs = new ArrayList<Certificate>();
+ Iterator<Map.Entry<String, HashMap<String, Attributes>>> it = signatures.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, HashMap<String, Attributes>> entry = it.next();
HashMap<String, Attributes> hm = entry.getValue();
if (hm.get(name) != null) {
// Found an entry for entry name in .SF file
String signatureFile = entry.getKey();
-
- Vector<Certificate> newCerts = getSignerCertificates(
- signatureFile, certificates);
- Iterator<Certificate> iter = newCerts.iterator();
- while (iter.hasNext()) {
- certs.add(iter.next());
- }
+ certs.addAll(getSignerCertificates(signatureFile, certificates));
}
}
// entry is not signed
- if (certs.size() == 0) {
+ if (certs.isEmpty()) {
return null;
}
- Certificate[] certificatesArray = new Certificate[certs.size()];
- certs.toArray(certificatesArray);
+ Certificate[] certificatesArray = certs.toArray(new Certificate[certs.size()]);
String algorithms = attributes.getValue("Digest-Algorithms");
if (algorithms == null) {
@@ -234,7 +227,7 @@
* @see #removeMetaEntries()
*/
void addMetaEntry(String name, byte[] buf) {
- metaEntries.put(Util.toASCIIUpperCase(name), buf);
+ metaEntries.put(name.toUpperCase(Locale.US), buf);
}
/**
diff --git a/luni/src/main/java/java/util/jar/Pack200.java b/luni/src/main/java/java/util/jar/Pack200.java
index 881f53c..0acf241 100644
--- a/luni/src/main/java/java/util/jar/Pack200.java
+++ b/luni/src/main/java/java/util/jar/Pack200.java
@@ -21,8 +21,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.SortedMap;
/**
@@ -52,23 +50,14 @@
* @return an instance of {@code Packer}
*/
public static Pack200.Packer newPacker() {
- return (Packer) AccessController
- .doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- String className = System
- .getProperty(SYSTEM_PROPERTY_PACKER,
- "org.apache.harmony.pack200.Pack200PackerAdapter");
- try {
- // TODO Not sure if this will cause problems with
- // loading the packer
- return ClassLoader.getSystemClassLoader()
- .loadClass(className).newInstance();
- } catch (Exception e) {
- throw new Error("Can't load class " + className, e);
- }
- }
- });
-
+ String className = System.getProperty(SYSTEM_PROPERTY_PACKER, "org.apache.harmony.pack200.Pack200PackerAdapter");
+ try {
+ // TODO Not sure if this will cause problems with
+ // loading the packer
+ return (Packer) ClassLoader.getSystemClassLoader().loadClass(className).newInstance();
+ } catch (Exception e) {
+ throw new Error("Can't load class " + className, e);
+ }
}
/**
@@ -82,20 +71,12 @@
* @return a instance of {@code Unpacker}.
*/
public static Pack200.Unpacker newUnpacker() {
- return (Unpacker) AccessController
- .doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- String className = System
- .getProperty(SYSTEM_PROPERTY_UNPACKER,
- "org.apache.harmony.unpack200.Pack200UnpackerAdapter");
- try {
- return ClassLoader.getSystemClassLoader()
- .loadClass(className).newInstance();
- } catch (Exception e) {
- throw new Error("Can't load class " + className, e);
- }
- }
- });
+ String className = System.getProperty(SYSTEM_PROPERTY_UNPACKER, "org.apache.harmony.unpack200.Pack200UnpackerAdapter");
+ try {
+ return (Unpacker) ClassLoader.getSystemClassLoader().loadClass(className).newInstance();
+ } catch (Exception e) {
+ throw new Error("Can't load class " + className, e);
+ }
}
/**
diff --git a/luni/src/main/java/java/util/logging/ErrorManager.java b/luni/src/main/java/java/util/logging/ErrorManager.java
index d0516ea..10f44c2 100644
--- a/luni/src/main/java/java/util/logging/ErrorManager.java
+++ b/luni/src/main/java/java/util/logging/ErrorManager.java
@@ -56,7 +56,6 @@
*/
public static final int FORMAT_FAILURE = 5;
- @SuppressWarnings("nls")
private static final String[] FAILURES = new String[] { "GENERIC_FAILURE",
"WRITE_FAILURE", "FLUSH_FAILURE", "CLOSE_FAILURE", "OPEN_FAILURE",
"FORMAT_FAILURE" };
diff --git a/luni/src/main/java/java/util/logging/FileHandler.java b/luni/src/main/java/java/util/logging/FileHandler.java
index 0735911..aa9ddb1 100644
--- a/luni/src/main/java/java/util/logging/FileHandler.java
+++ b/luni/src/main/java/java/util/logging/FileHandler.java
@@ -25,8 +25,6 @@
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Hashtable;
import libcore.io.IoUtils;
@@ -146,12 +144,6 @@
*
* @throws IOException
* if any I/O error occurs.
- * @throws SecurityException
- * if a security manager exists and it determines that the
- * caller does not have the required permissions to control this
- * handler; required permissions include
- * {@code LogPermission("control")},
- * {@code FilePermission("write")} etc.
*/
public FileHandler() throws IOException {
init(null, null, null, null);
@@ -216,7 +208,6 @@
setOutputStream(output);
}
- @SuppressWarnings("nls")
private void initProperties(String p, Boolean a, Integer l, Integer c) {
super.initProperties("ALL", null, "java.util.logging.XMLFormatter",
null);
@@ -381,12 +372,6 @@
* the name pattern for the output file.
* @throws IOException
* if any I/O error occurs.
- * @throws SecurityException
- * if a security manager exists and it determines that the
- * caller does not have the required permissions to control this
- * handler; required permissions include
- * {@code LogPermission("control")},
- * {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if the pattern is empty.
* @throws NullPointerException
@@ -413,12 +398,6 @@
* the append mode.
* @throws IOException
* if any I/O error occurs.
- * @throws SecurityException
- * if a security manager exists and it determines that the
- * caller does not have the required permissions to control this
- * handler; required permissions include
- * {@code LogPermission("control")},
- * {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if {@code pattern} is empty.
* @throws NullPointerException
@@ -449,12 +428,6 @@
* the maximum number of files to use, can not be less than one.
* @throws IOException
* if any I/O error occurs.
- * @throws SecurityException
- * if a security manager exists and it determines that the
- * caller does not have the required permissions to control this
- * handler; required permissions include
- * {@code LogPermission("control")},
- * {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if {@code pattern} is empty, {@code limit < 0} or
* {@code count < 1}.
@@ -491,12 +464,6 @@
* the append mode.
* @throws IOException
* if any I/O error occurs.
- * @throws SecurityException
- * if a security manager exists and it determines that the
- * caller does not have the required permissions to control this
- * handler; required permissions include
- * {@code LogPermission("control")},
- * {@code FilePermission("write")} etc.
* @throws IllegalArgumentException
* if {@code pattern} is empty, {@code limit < 0} or
* {@code count < 1}.
@@ -515,13 +482,6 @@
/**
* Flushes and closes all opened files.
- *
- * @throws SecurityException
- * if a security manager exists and it determines that the
- * caller does not have the required permissions to control this
- * handler; required permissions include
- * {@code LogPermission("control")},
- * {@code FilePermission("write")} etc.
*/
@Override
public void close() {
@@ -550,12 +510,7 @@
super.publish(record);
flush();
if (limit > 0 && output.getLength() >= limit) {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- findNextGeneration();
- return null;
- }
- });
+ findNextGeneration();
}
}
diff --git a/luni/src/main/java/java/util/logging/Handler.java b/luni/src/main/java/java/util/logging/Handler.java
index 21e77d7..5a6c14e 100644
--- a/luni/src/main/java/java/util/logging/Handler.java
+++ b/luni/src/main/java/java/util/logging/Handler.java
@@ -19,8 +19,6 @@
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
-import java.security.AccessController;
-import java.security.PrivilegedExceptionAction;
/**
* A {@code Handler} object accepts a logging request and exports the desired
@@ -78,18 +76,12 @@
}
// get a instance from given class name, using context classloader
- private Object getCustomizeInstance(final String className)
- throws Exception {
- Class<?> c = AccessController
- .doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
- public Class<?> run() throws Exception {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if (loader == null) {
- loader = ClassLoader.getSystemClassLoader();
- }
- return loader.loadClass(className);
- }
- });
+ private Object getCustomizeInstance(final String className) throws Exception {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ if (loader == null) {
+ loader = ClassLoader.getSystemClassLoader();
+ }
+ Class<?> c = loader.loadClass(className);
return c.newInstance();
}
@@ -159,10 +151,6 @@
* Closes this handler. A flush operation will be performed and all the
* associated resources will be freed. Client applications should not use
* this handler after closing it.
- *
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public abstract void close();
@@ -194,9 +182,6 @@
* logging.
*
* @return the error manager used by this handler.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public ErrorManager getErrorManager() {
LogManager.getLogManager().checkAccess();
@@ -298,14 +283,10 @@
*
* @param encoding
* the character encoding to set.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
* @throws UnsupportedEncodingException
* if the specified encoding is not supported by the runtime.
*/
- public void setEncoding(String encoding) throws SecurityException,
- UnsupportedEncodingException {
+ public void setEncoding(String encoding) throws UnsupportedEncodingException {
LogManager.getLogManager().checkAccess();
internalSetEncoding(encoding);
}
@@ -317,9 +298,6 @@
* the error manager to set.
* @throws NullPointerException
* if {@code em} is {@code null}.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setErrorManager(ErrorManager em) {
LogManager.getLogManager().checkAccess();
@@ -334,9 +312,6 @@
*
* @param newFilter
* the filter to set, may be {@code null}.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setFilter(Filter newFilter) {
LogManager.getLogManager().checkAccess();
@@ -364,9 +339,6 @@
* the formatter to set.
* @throws NullPointerException
* if {@code newFormatter} is {@code null}.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setFormatter(Formatter newFormatter) {
LogManager.getLogManager().checkAccess();
@@ -381,9 +353,6 @@
* the logging level to set.
* @throws NullPointerException
* if {@code newLevel} is {@code null}.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setLevel(Level newLevel) {
if (newLevel == null) {
diff --git a/luni/src/main/java/java/util/logging/Level.java b/luni/src/main/java/java/util/logging/Level.java
index 3671fb2..d4cc82f 100644
--- a/luni/src/main/java/java/util/logging/Level.java
+++ b/luni/src/main/java/java/util/logging/Level.java
@@ -209,9 +209,7 @@
if (resourceBundleName != null) {
try {
rb = ResourceBundle.getBundle(resourceBundleName,
- // BEGIN android-changed
Locale.getDefault(), VMStack.getCallingClassLoader());
- // BEGIN android-changed
} catch (MissingResourceException e) {
rb = null;
}
diff --git a/luni/src/main/java/java/util/logging/LogManager.java b/luni/src/main/java/java/util/logging/LogManager.java
index fac3602..0abc697 100644
--- a/luni/src/main/java/java/util/logging/LogManager.java
+++ b/luni/src/main/java/java/util/logging/LogManager.java
@@ -17,12 +17,6 @@
package java.util.logging;
-// BEGIN android-note
-// this file contains cleaned up documentation and style for contribution
-// upstream.
-// javax.management support (MBeans) has been dropped.
-// END android-note
-
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedInputStream;
@@ -30,8 +24,6 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
@@ -125,7 +117,7 @@
public class LogManager {
/** The line separator of the underlying OS. */
- private static final String lineSeparator = getPrivilegedSystemProperty("line.separator");
+ private static final String lineSeparator = System.getProperty("line.separator");
/** The shared logging permission. */
private static final LoggingPermission perm = new LoggingPermission("control", null);
@@ -159,34 +151,28 @@
static {
// init LogManager singleton instance
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- String className = System.getProperty("java.util.logging.manager");
+ String className = System.getProperty("java.util.logging.manager");
+ if (className != null) {
+ manager = (LogManager) getInstanceByClass(className);
+ }
+ if (manager == null) {
+ manager = new LogManager();
+ }
- if (className != null) {
- manager = (LogManager) getInstanceByClass(className);
- }
- if (manager == null) {
- manager = new LogManager();
- }
+ // read configuration
+ try {
+ manager.readConfiguration();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
- // read configuration
- try {
- manager.readConfiguration();
- } catch (Exception e) {
- e.printStackTrace();
- }
+ // if global logger has been initialized, set root as its parent
+ Logger root = new Logger("", null);
+ root.setLevel(Level.INFO);
+ Logger.global.setParent(root);
- // if global logger has been initialized, set root as its parent
- Logger root = new Logger("", null);
- root.setLevel(Level.INFO);
- Logger.global.setParent(root);
-
- manager.addLogger(root);
- manager.addLogger(Logger.global);
- return null;
- }
- });
+ manager.addLogger(root);
+ manager.addLogger(Logger.global);
}
/**
@@ -201,15 +187,9 @@
listeners = new PropertyChangeSupport(this);
// add shutdown hook to ensure that the associated resource will be
// freed when JVM exits
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- reset();
- }
- });
- return null;
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ @Override public void run() {
+ reset();
}
});
}
@@ -223,20 +203,9 @@
}
/**
- * Check that the caller has {@code LoggingPermission("control")} so
- * that it is trusted to modify the configuration for logging framework. If
- * the check passes, just return, otherwise {@code SecurityException}
- * will be thrown.
- *
- * @throws SecurityException
- * if there is a security manager in operation and the invoker
- * of this method does not have the required security permission
- * {@code LoggingPermission("control")}
+ * Does nothing.
*/
public void checkAccess() {
- if (System.getSecurityManager() != null) {
- System.getSecurityManager().checkPermission(perm);
- }
}
/**
@@ -295,16 +264,9 @@
Collection<Logger> allLoggers = loggers.values();
for (final Logger child : allLoggers) {
Logger oldParent = child.getParent();
- if (parent == oldParent
- && (name.length() == 0 || child.getName().startsWith(
- nameDot))) {
+ if (parent == oldParent && (name.length() == 0 || child.getName().startsWith(nameDot))) {
final Logger thisLogger = logger;
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- child.setParent(thisLogger);
- return null;
- }
- });
+ child.setParent(thisLogger);
if (oldParent != null) {
// -- remove from old parent as the parent has been changed
oldParent.children.remove(child);
@@ -362,9 +324,6 @@
*
* @throws IOException
* if any IO related problems happened.
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to perform this action.
*/
public void readConfiguration() throws IOException {
// check config class
@@ -397,15 +356,6 @@
}
}
- // use privilege code to get system property
- static String getPrivilegedSystemProperty(final String key) {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return System.getProperty(key);
- }
- });
- }
-
// use SystemClassLoader to load class from system classpath
static Object getInstanceByClass(final String className) {
try {
@@ -421,7 +371,6 @@
return null;
}
}
-
}
// actual initialization process from a given input stream
@@ -469,9 +418,6 @@
* the input stream
* @throws IOException
* if any IO related problems happened.
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to perform this action.
*/
public void readConfiguration(InputStream ins) throws IOException {
checkAccess();
@@ -480,15 +426,10 @@
/**
* Reset configuration.
- * <p>
- * All handlers are closed and removed from any named loggers. All loggers'
+ *
+ * <p>All handlers are closed and removed from any named loggers. All loggers'
* level is set to null, except the root logger's level is set to
* {@code Level.INFO}.
- * </p>
- *
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to perform this action.
*/
public synchronized void reset() {
checkAccess();
@@ -513,9 +454,6 @@
*
* @param l
* the {@code PropertyChangeListener} to be added.
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to perform this action.
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
if (l == null) {
@@ -531,9 +469,6 @@
*
* @param l
* the {@code PropertyChangeListener} to be removed.
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to perform this action.
*/
public void removePropertyChangeListener(PropertyChangeListener l) {
checkAccess();
@@ -570,7 +505,7 @@
setLevelRecursively(logger, null);
}
newParent.children.add(logger);
- logger.updateDalvikLogHandler(); // android-only
+ logger.updateDalvikLogHandler();
}
/**
diff --git a/luni/src/main/java/java/util/logging/LogRecord.java b/luni/src/main/java/java/util/logging/LogRecord.java
index fd34eb4..66cabcc 100644
--- a/luni/src/main/java/java/util/logging/LogRecord.java
+++ b/luni/src/main/java/java/util/logging/LogRecord.java
@@ -135,7 +135,7 @@
private transient Object[] parameters;
// If the source method and source class has been initialized
- private transient boolean sourceInited;
+ private transient boolean sourceInitialized;
/**
* Constructs a {@code LogRecord} object using the supplied the logging
@@ -360,8 +360,7 @@
* Init the sourceClass and sourceMethod fields.
*/
private void initSource() {
- // BEGIN android-changed
- if (sourceInited) {
+ if (sourceInitialized) {
return;
}
@@ -377,8 +376,7 @@
}
}
- sourceInited = true;
- // END android-changed
+ sourceInitialized = true;
}
/**
@@ -389,7 +387,7 @@
* {@code null}.
*/
public void setSourceClassName(String sourceClassName) {
- sourceInited = true;
+ sourceInitialized = true;
this.sourceClassName = sourceClassName;
}
@@ -411,7 +409,7 @@
* {@code null}.
*/
public void setSourceMethodName(String sourceMethodName) {
- sourceInited = true;
+ sourceInitialized = true;
this.sourceMethodName = sourceMethodName;
}
diff --git a/luni/src/main/java/java/util/logging/Logger.java b/luni/src/main/java/java/util/logging/Logger.java
index 6c7dabb..fb4f5d0 100644
--- a/luni/src/main/java/java/util/logging/Logger.java
+++ b/luni/src/main/java/java/util/logging/Logger.java
@@ -17,17 +17,8 @@
package java.util.logging;
-// BEGIN android-note
-// this file contains cleaned up documentation and style for contribution
-// upstream
-// It also contains Android-specific optimizations that aren't appropriate for
-// general purpose platforms
-// END android-note
-
import dalvik.system.DalvikLogHandler;
import dalvik.system.DalvikLogging;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -81,7 +72,6 @@
*/
public class Logger {
- // BEGIN android-only
/** A handler for use when no handler optimization is possible. */
private static final DalvikLogHandler GENERAL_LOG_HANDLER = new DalvikLogHandler() {
public void publish(Logger source, String tag, Level level, String message) {
@@ -91,7 +81,6 @@
source.log(record);
}
};
- // END android-only
/**
* The name of the global logger. Before using this, see the discussion of how to use
@@ -107,7 +96,7 @@
* documentation.
*/
@Deprecated
- public final static Logger global = new Logger(GLOBAL_LOGGER_NAME, null);
+ public static final Logger global = new Logger(GLOBAL_LOGGER_NAME, null);
/**
* When converting the concurrent collection of handlers to an array, we
@@ -170,7 +159,6 @@
*/
final List<Logger> children = new ArrayList<Logger>();
- // BEGIN android-only
/** the tag used for optimized logging. Derived from the logger name. */
private final String androidTag;
@@ -245,7 +233,6 @@
logger.updateDalvikLogHandler();
}
}
- // END android-only
/**
* Constructs a {@code Logger} object with the supplied name and resource
@@ -265,10 +252,8 @@
protected Logger(String name, String resourceBundleName) {
this.name = name;
initResourceBundle(resourceBundleName);
- // BEGIN android-only
this.androidTag = DalvikLogging.loggerNameToTag(name);
updateDalvikLogHandler();
- // END android-only
}
/**
@@ -282,12 +267,7 @@
*/
static ResourceBundle loadResourceBundle(String resourceBundleName) {
// try context class loader to load the resource
- ClassLoader cl = AccessController
- .doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return Thread.currentThread().getContextClassLoader();
- }
- });
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
try {
return ResourceBundle.getBundle(resourceBundleName, Locale
@@ -297,42 +277,25 @@
}
}
// try system class loader to load the resource
- cl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return ClassLoader.getSystemClassLoader();
- }
- });
+ cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
try {
- return ResourceBundle.getBundle(resourceBundleName, Locale
- .getDefault(), cl);
+ return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl);
} catch (MissingResourceException e) {
// Failed to load using system classloader, ignore
}
}
// try all class loaders up the class stack
- final Class<?>[] classes = AccessController
- .doPrivileged(new PrivilegedAction<Class<?>[]>() {
- public Class<?>[] run() {
- return (new PrivateSecurityManager())
- .privateGetClassContext();
- }
- });
+ final Class<?>[] classes = new PrivateSecurityManager().privateGetClassContext();
// the first class, which is PrivateSecurityManager, is skipped
for (int i = 1; i < classes.length; i++) {
final int index = i;
try {
- cl = AccessController
- .doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return classes[index].getClassLoader();
- }
- });
+ cl = classes[index].getClassLoader();
if (cl == null) {
continue;
}
- return ResourceBundle.getBundle(resourceBundleName, Locale
- .getDefault(), cl);
+ return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl);
} catch (MissingResourceException e) {
// Failed to load using the current class's classloader, ignore
}
@@ -444,9 +407,6 @@
*
* @param handler
* the handler object to add, cannot be {@code null}.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void addHandler(Handler handler) {
if (handler == null) {
@@ -457,14 +417,13 @@
LogManager.getLogManager().checkAccess();
}
this.handlers.add(handler);
- updateDalvikLogHandler(); // android-only
+ updateDalvikLogHandler();
}
/**
* Set the logger's manager and initializes its configuration from the
* manager's properties.
*/
- @SuppressWarnings("nls")
void setManager(LogManager manager) {
String levelProperty = manager.getProperty(name + ".level");
if (levelProperty != null) {
@@ -504,7 +463,7 @@
}
}
- updateDalvikLogHandler(); // android-only
+ updateDalvikLogHandler();
}
/**
@@ -522,9 +481,6 @@
*
* @param handler
* the handler to be removed.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void removeHandler(Handler handler) {
// Anonymous loggers can always remove handlers
@@ -535,7 +491,7 @@
return;
}
this.handlers.remove(handler);
- updateDalvikLogHandler(); // android-only
+ updateDalvikLogHandler();
}
/**
@@ -552,9 +508,6 @@
*
* @param newFilter
* the filter to set, may be {@code null}.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setFilter(Filter newFilter) {
// Anonymous loggers can always set the filter
@@ -580,9 +533,6 @@
*
* @param newLevel
* the logging level to set.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setLevel(Level newLevel) {
// Anonymous loggers can always set the level
@@ -611,9 +561,6 @@
*
* @param notifyParentHandlers
* the new flag indicating whether to use the parent's handlers.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setUseParentHandlers(boolean notifyParentHandlers) {
// Anonymous loggers can always set the useParentHandlers flag
@@ -621,7 +568,7 @@
LogManager.getLogManager().checkAccess();
}
this.notifyParentHandlers = notifyParentHandlers;
- updateDalvikLogHandler(); // android-only
+ updateDalvikLogHandler();
}
/**
@@ -640,9 +587,6 @@
*
* @param parent
* the parent logger to set.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
public void setParent(Logger parent) {
if (parent == null) {
@@ -795,7 +739,6 @@
* @param params
* an array of parameters for the method call.
*/
- @SuppressWarnings("nls")
public void entering(String sourceClass, String sourceMethod,
Object[] params) {
if (!internalIsLoggable(Level.FINER)) {
@@ -986,10 +929,7 @@
if (!internalIsLoggable(logLevel)) {
return;
}
-
- // BEGIN android-only
dalvikLogHandler.publish(this, androidTag, logLevel, msg);
- // END android-only
}
/**
@@ -1408,6 +1348,6 @@
}
}
- updateDalvikLogHandler(); // android-only
+ updateDalvikLogHandler();
}
}
diff --git a/luni/src/main/java/java/util/logging/LoggingMXBean.java b/luni/src/main/java/java/util/logging/LoggingMXBean.java
index f2e9554..a36a9d4 100644
--- a/luni/src/main/java/java/util/logging/LoggingMXBean.java
+++ b/luni/src/main/java/java/util/logging/LoggingMXBean.java
@@ -73,9 +73,6 @@
* @throws IllegalArgumentException
* if {@code loggerName} is not a registered logger or if
* {@code levelName} is not null and not valid.
- * @throws SecurityException
- * if a security manager exists and the caller doesn't have
- * LoggingPermission("control").
* @see Level#parse(String)
*/
void setLoggerLevel(String loggerName, String levelName);
diff --git a/luni/src/main/java/java/util/logging/LoggingPermission.java b/luni/src/main/java/java/util/logging/LoggingPermission.java
index ec53956..0f06154 100644
--- a/luni/src/main/java/java/util/logging/LoggingPermission.java
+++ b/luni/src/main/java/java/util/logging/LoggingPermission.java
@@ -22,30 +22,15 @@
import java.security.Guard;
/**
- * The permission required to control the logging when run with a
- * {@code SecurityManager}.
+ * Legacy security code; this class exists for compatibility only.
*/
-public final class LoggingPermission extends BasicPermission implements Guard,
- Serializable {
+public final class LoggingPermission extends BasicPermission implements Guard, Serializable {
// for serialization compatibility with J2SE 1.4.2
private static final long serialVersionUID = 63564341580231582L;
/**
- * Constructs a {@code LoggingPermission} object required to control the
- * logging. The {@code SecurityManager} checks the permissions.
- * <p>
- * {@code LoggingPermission} objects are created by the security policy code
- * and depends on the security policy file, therefore programmers shouldn't
- * normally use them directly.
- * </p>
- *
- * @param name
- * currently must be "control".
- * @param actions
- * currently must be either {@code null} or the empty string.
- * @throws IllegalArgumentException
- * if name null or different from {@code string} control.
+ * Legacy security code; this class exists for compatibility only.
*/
public LoggingPermission(String name, String actions) {
super(name, actions);
diff --git a/luni/src/main/java/java/util/logging/MemoryHandler.java b/luni/src/main/java/java/util/logging/MemoryHandler.java
index 4e7be49..607fcc4 100644
--- a/luni/src/main/java/java/util/logging/MemoryHandler.java
+++ b/luni/src/main/java/java/util/logging/MemoryHandler.java
@@ -17,9 +17,6 @@
package java.util.logging;
-import java.security.AccessController;
-import java.security.PrivilegedExceptionAction;
-
/**
* A {@code Handler} put the description of log events into a cycled memory
* buffer.
@@ -92,17 +89,11 @@
// init target
final String targetName = manager.getProperty(className + ".target");
try {
- Class<?> targetClass = AccessController
- .doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
- public Class<?> run() throws Exception {
- ClassLoader loader = Thread.currentThread()
- .getContextClassLoader();
- if (loader == null) {
- loader = ClassLoader.getSystemClassLoader();
- }
- return loader.loadClass(targetName);
- }
- });
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ if (loader == null) {
+ loader = ClassLoader.getSystemClassLoader();
+ }
+ Class<?> targetClass = loader.loadClass(targetName);
target = (Handler) targetClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot load target handler '" + targetName + "'");
@@ -166,10 +157,6 @@
/**
* Close this handler and target handler, free all associated resources.
- *
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to control this handler.
*/
@Override
public void close() {
@@ -268,9 +255,6 @@
*
* @param newLevel
* the new level to set.
- * @throws SecurityException
- * if security manager exists and it determines that caller
- * does not have the required permissions to control this handler.
*/
public void setPushLevel(Level newLevel) {
manager.checkAccess();
diff --git a/luni/src/main/java/java/util/logging/SocketHandler.java b/luni/src/main/java/java/util/logging/SocketHandler.java
index bcaee09..85a9e6c 100644
--- a/luni/src/main/java/java/util/logging/SocketHandler.java
+++ b/luni/src/main/java/java/util/logging/SocketHandler.java
@@ -71,9 +71,6 @@
* if failed to connect to the specified host and port.
* @throws IllegalArgumentException
* if the host name or port number is illegal.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission to control this handler.
*/
public SocketHandler() throws IOException {
super(DEFAULT_LEVEL, null, DEFAULT_FORMATTER, null);
@@ -96,9 +93,6 @@
* if failed to connect to the specified host and port.
* @throws IllegalArgumentException
* if the host name or port number is illegal.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission to control this handler.
*/
public SocketHandler(String host, int port) throws IOException {
super(DEFAULT_LEVEL, null, DEFAULT_FORMATTER, null);
@@ -134,10 +128,6 @@
/**
* Closes this handler. The network connection to the host is also closed.
- *
- * @throws SecurityException
- * If a security manager determines that the caller does not
- * have the required permission to control this handler.
*/
@Override
public void close() {
diff --git a/luni/src/main/java/java/util/logging/StreamHandler.java b/luni/src/main/java/java/util/logging/StreamHandler.java
index 42a02a3..7581835 100644
--- a/luni/src/main/java/java/util/logging/StreamHandler.java
+++ b/luni/src/main/java/java/util/logging/StreamHandler.java
@@ -162,9 +162,6 @@
*
* @param os
* the new output stream.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
* @throws NullPointerException
* if {@code os} is {@code null}.
*/
@@ -185,15 +182,11 @@
*
* @param encoding
* the character encoding to set.
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
* @throws UnsupportedEncodingException
* if the specified encoding is not supported by the runtime.
*/
@Override
- public void setEncoding(String encoding) throws SecurityException,
- UnsupportedEncodingException {
+ public void setEncoding(String encoding) throws UnsupportedEncodingException {
// flush first before set new encoding
this.flush();
super.setEncoding(encoding);
@@ -247,10 +240,6 @@
* this handler is written out. A flush operation and a subsequent close
* operation is then performed upon the output stream. Client applications
* should not use a handler after closing it.
- *
- * @throws SecurityException
- * if a security manager determines that the caller does not
- * have the required permission.
*/
@Override
public void close() {
diff --git a/luni/src/main/java/java/util/logging/XMLFormatter.java b/luni/src/main/java/java/util/logging/XMLFormatter.java
index 5e461c4..c4f9eee 100644
--- a/luni/src/main/java/java/util/logging/XMLFormatter.java
+++ b/luni/src/main/java/java/util/logging/XMLFormatter.java
@@ -17,8 +17,6 @@
package java.util.logging;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.Date;
import java.util.ResourceBundle;
@@ -32,8 +30,7 @@
*/
public class XMLFormatter extends Formatter {
- private static final String lineSeperator = LogManager
- .getSystemLineSeparator();
+ private static final String lineSeperator = LogManager.getSystemLineSeparator();
private static final String indent = " ";
@@ -51,7 +48,6 @@
* the log record to be formatted.
* @return the log record formatted as an XML string.
*/
- @SuppressWarnings("nls")
@Override
public String format(LogRecord r) {
// call a method of LogRecord to ensure not null
@@ -99,7 +95,6 @@
return sb.toString();
}
- @SuppressWarnings("nls")
private void formatMessages(LogRecord r, StringBuilder sb) {
// get localized message if has, but don't call Formatter.formatMessage
// to parse pattern string
@@ -134,7 +129,6 @@
}
}
- @SuppressWarnings("nls")
private void formatThrowable(LogRecord r, StringBuilder sb) {
Throwable t;
if ((t = r.getThrown()) != null) {
@@ -171,7 +165,6 @@
* the output handler, may be {@code null}.
* @return the header string for log records formatted as XML strings.
*/
- @SuppressWarnings("nls")
@Override
public String getHead(Handler h) {
String encoding = null;
@@ -179,7 +172,7 @@
encoding = h.getEncoding();
}
if (encoding == null) {
- encoding = getSystemProperty("file.encoding");
+ encoding = System.getProperty("file.encoding");
}
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"").append(encoding).append(
@@ -201,13 +194,4 @@
public String getTail(Handler h) {
return "</log>";
}
-
- // use privilege code to get system property
- private static String getSystemProperty(final String key) {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return System.getProperty(key);
- }
- });
- }
}
diff --git a/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java b/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java
index 0fd8466..bd367a6 100644
--- a/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java
+++ b/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java
@@ -18,8 +18,6 @@
import java.io.File;
import java.io.FilenameFilter;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
@@ -35,41 +33,14 @@
*/
class FilePreferencesImpl extends AbstractPreferences {
- /*
- * --------------------------------------------------------------
- * Class fields
- * --------------------------------------------------------------
- */
-
//prefs file name
private static final String PREFS_FILE_NAME = "prefs.xml";
//home directory for user prefs
- private static String USER_HOME;
+ private static String USER_HOME = System.getProperty("user.home") + "/.java/.userPrefs";
//home directory for system prefs
- private static String SYSTEM_HOME;
-
- /*
- * --------------------------------------------------------------
- * Class initializer
- * --------------------------------------------------------------
- */
- static {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- USER_HOME = System.getProperty("user.home") + "/.java/.userPrefs";
- SYSTEM_HOME = System.getProperty("java.home") + "/.systemPrefs";
- return null;
- }
- });
- }
-
- /*
- * --------------------------------------------------------------
- * Instance fields
- * --------------------------------------------------------------
- */
+ private static String SYSTEM_HOME = System.getProperty("java.home") + "/.systemPrefs";
//file path for this preferences node
private String path;
@@ -117,26 +88,16 @@
private void initPrefs() {
dir = new File(path);
- newNode = (AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
- public Boolean run() {
- return Boolean.valueOf(!dir.exists());
- }
- })).booleanValue();
+ newNode = !dir.exists();
prefsFile = new File(path + File.separator + PREFS_FILE_NAME);
- prefs = XMLParser.loadFilePrefs(prefsFile);
+ prefs = XMLParser.readXmlPreferences(prefsFile);
}
@Override
protected String[] childrenNamesSpi() throws BackingStoreException {
- String[] names = AccessController
- .doPrivileged(new PrivilegedAction<String[]>() {
- public String[] run() {
- return dir.list(new FilenameFilter() {
- public boolean accept(File parent, String name) {
- return new File(path + File.separator + name).isDirectory();
- }
- });
-
+ String[] names = dir.list(new FilenameFilter() {
+ public boolean accept(File parent, String name) {
+ return new File(path + File.separator + name).isDirectory();
}
});
if (names == null) {// file is not a directory, exception case
@@ -160,7 +121,7 @@
return;
}
// reload
- Properties currentPrefs = XMLParser.loadFilePrefs(prefsFile);
+ Properties currentPrefs = XMLParser.readXmlPreferences(prefsFile);
// merge
Iterator<String> it = removed.iterator();
while (it.hasNext()) {
@@ -175,7 +136,7 @@
updated.clear();
// flush
prefs = currentPrefs;
- XMLParser.flushFilePrefs(prefsFile, prefs);
+ XMLParser.writeXmlPreferences(prefsFile, prefs);
} catch (Exception e) {
throw new BackingStoreException(e);
}
@@ -185,7 +146,7 @@
protected String getSpi(String key) {
try {
if (prefs == null) {
- prefs = XMLParser.loadFilePrefs(prefsFile);
+ prefs = XMLParser.readXmlPreferences(prefsFile);
}
return prefs.getProperty(key);
} catch (Exception e) {
@@ -208,12 +169,8 @@
@Override
protected void removeNodeSpi() throws BackingStoreException {
- boolean removeSucceed = (AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
- public Boolean run() {
- prefsFile.delete();
- return Boolean.valueOf(dir.delete());
- }
- })).booleanValue();
+ prefsFile.delete();
+ boolean removeSucceed = dir.delete();
if (!removeSucceed) {
throw new BackingStoreException("Cannot remove " + toString());
}
diff --git a/luni/src/main/java/java/util/prefs/Preferences.java b/luni/src/main/java/java/util/prefs/Preferences.java
index 94eb2ab..df9c0bc3 100644
--- a/luni/src/main/java/java/util/prefs/Preferences.java
+++ b/luni/src/main/java/java/util/prefs/Preferences.java
@@ -98,9 +98,6 @@
*/
public static final int MAX_VALUE_LENGTH = 8192;
- //permission
- private static final RuntimePermission PREFS_PERM = new RuntimePermission("preferences");
-
//factory used to get user/system prefs root
private static final PreferencesFactory factory = findPreferencesFactory();
@@ -440,12 +437,8 @@
* valid XML document.
* @throws IOException
* if an error occurs while importing.
- * @throws SecurityException
- * if {@code RuntimePermission("preferences")} is denied by a
- * SecurityManager.
*/
public static void importPreferences (InputStream istream) throws InvalidPreferencesFormatException, IOException {
- checkSecurity();
if (istream == null){
throw new MalformedURLException("Inputstream cannot be null");
}
@@ -803,12 +796,8 @@
* @return the system preference node for the package of the given class.
* @throws NullPointerException
* if the given class is {@code null}.
- * @throws SecurityException
- * if the {@code RuntimePermission("preferences")} is denied by
- * a SecurityManager.
*/
public static Preferences systemNodeForPackage (Class<?> c) {
- checkSecurity();
return factory.systemRoot().node(getNodeName(c));
}
@@ -816,23 +805,11 @@
* Returns the root node of the system preference hierarchy.
*
* @return the system preference hierarchy root node.
- * @throws SecurityException
- * if the {@code RuntimePermission("preferences")} is denied by
- * a SecurityManager.
*/
public static Preferences systemRoot() {
- checkSecurity();
return factory.systemRoot();
}
- //check the RuntimePermission("preferences")
- private static void checkSecurity() {
- SecurityManager manager = System.getSecurityManager();
- if (manager != null){
- manager.checkPermission(PREFS_PERM);
- }
- }
-
/**
* Returns the user preference node for the package of the given class.
* The absolute path of the returned node is one slash followed by the given
@@ -849,12 +826,8 @@
* @return the user preference node for the package of the given class.
* @throws NullPointerException
* if the given class is {@code null}.
- * @throws SecurityException
- * if the {@code RuntimePermission("preferences")} is denied by
- * a SecurityManager.
*/
public static Preferences userNodeForPackage (Class<?> c) {
- checkSecurity();
return factory.userRoot().node(getNodeName(c));
}
@@ -871,12 +844,8 @@
* Returns the root node of the user preference hierarchy.
*
* @return the user preference hierarchy root node.
- * @throws SecurityException
- * if the {@code RuntimePermission("preferences")} is denied by
- * a SecurityManager.
*/
public static Preferences userRoot() {
- checkSecurity();
return factory.userRoot();
}
diff --git a/luni/src/main/java/java/util/prefs/XMLParser.java b/luni/src/main/java/java/util/prefs/XMLParser.java
index 97fce86..2cd69f5 100644
--- a/luni/src/main/java/java/util/prefs/XMLParser.java
+++ b/luni/src/main/java/java/util/prefs/XMLParser.java
@@ -27,20 +27,14 @@
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
+import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
-import libcore.util.EmptyArray;
import libcore.io.IoUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -111,9 +105,7 @@
*/
static {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- // BEGIN android-changed
factory.setValidating(false);
- // END android-changed
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
@@ -370,22 +362,12 @@
} catch (SAXException e) {
throw new InvalidPreferencesFormatException(e);
}
- // BEGIN android-removed
- // catch (TransformerException e) {
- // throw new InvalidPreferencesFormatException(e);
- // }
- // END android-removed
}
private static void loadNode(Preferences prefs, Element node) {
- // BEGIN android-note
- // removed throw clause for TransformerException
- // END android-note
// load preferences
- // BEGIN android-changed
NodeList children = selectNodeList(node, "node");
NodeList entries = selectNodeList(node, "map/entry");
- // END android-changed
int childNumber = children.getLength();
Preferences[] prefChildren = new Preferences[childNumber];
int entryNumber = entries.getLength();
@@ -413,7 +395,6 @@
}
}
- // BEGIN android-added
// TODO dirty implementation of a method from javax.xml.xpath
// should be replaced with a call to a good impl of this method
private static NodeList selectNodeList(Element documentElement, String string) {
@@ -460,40 +441,21 @@
return result;
}
- // END android-added
- /***************************************************************************
- * utilities for FilePreferencesImpl, which is default implementation of Linux platform
- **************************************************************************/
/**
- * load preferences from file, if cannot load, create a new one FIXME: need
- * lock or not?
- *
- * @param file the XML file to be read
- * @return Properties instance which indicates the preferences key-value pairs
+ * Returns the preferences from {@code xmlFile}. Returns empty properties if
+ * any errors occur.
*/
- static Properties loadFilePrefs(final File file) {
- return AccessController.doPrivileged(new PrivilegedAction<Properties>() {
- public Properties run() {
- return loadFilePrefsImpl(file);
- }
- });
- }
-
- static Properties loadFilePrefsImpl(final File file) {
+ static Properties readXmlPreferences(File xmlFile) {
Properties result = new Properties();
- if (!file.exists()) {
- file.getParentFile().mkdirs();
- } else if (file.canRead()) {
+ if (!xmlFile.exists()) {
+ xmlFile.getParentFile().mkdirs();
+ } else if (xmlFile.canRead()) {
Reader reader = null;
- FileLock lock = null;
try {
- FileInputStream fileInputStream = new FileInputStream(file);
- reader = new InputStreamReader(fileInputStream, "UTF-8");
- FileChannel channel = fileInputStream.getChannel();
- lock = channel.lock(0L, Long.MAX_VALUE, true);
- Document doc = builder.parse(new InputSource(reader));
- NodeList entries = selectNodeList(doc.getDocumentElement(), "entry");
+ reader = new InputStreamReader(new FileInputStream(xmlFile), "UTF-8");
+ Document document = builder.parse(new InputSource(reader));
+ NodeList entries = selectNodeList(document.getDocumentElement(), "entry");
int length = entries.getLength();
for (int i = 0; i < length; i++) {
Element node = (Element) entries.item(i);
@@ -501,70 +463,47 @@
String value = node.getAttribute("value");
result.setProperty(key, value);
}
- return result;
- } catch (IOException e) {
- } catch (SAXException e) {
+ } catch (IOException ignored) {
+ } catch (SAXException ignored) {
} finally {
- releaseQuietly(lock);
IoUtils.closeQuietly(reader);
}
} else {
- file.delete();
+ // TODO: why delete files that cannot be read? http://b/3431233
+ xmlFile.delete();
}
return result;
}
/**
- *
- * @param file
- * @param prefs
- * @throws PrivilegedActionException
+ * Writes the preferences to {@code xmlFile}.
*/
- static void flushFilePrefs(final File file, final Properties prefs) throws PrivilegedActionException {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws IOException {
- flushFilePrefsImpl(file, prefs);
- return null;
- }
- });
- }
+ static void writeXmlPreferences(File xmlFile, Properties properties) throws IOException {
+ File parent = xmlFile.getParentFile();
+ File temporaryForWriting = new File(parent, "prefs-" + UUID.randomUUID() + ".xml.tmp");
- static void flushFilePrefsImpl(File file, Properties prefs) throws IOException {
BufferedWriter out = null;
- FileLock lock = null;
try {
- FileOutputStream ostream = new FileOutputStream(file);
- out = new BufferedWriter(new OutputStreamWriter(ostream, "UTF-8"));
- FileChannel channel = ostream.getChannel();
- lock = channel.lock();
+ out = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(temporaryForWriting), "UTF-8"));
out.write(HEADER);
out.newLine();
out.write(FILE_PREFS);
out.newLine();
- if (prefs.size() == 0) {
- exportEntries(EmptyArray.STRING, EmptyArray.STRING, out);
- } else {
- String[] keys = prefs.keySet().toArray(new String[prefs.size()]);
- int length = keys.length;
- String[] values = new String[length];
- for (int i = 0; i < length; i++) {
- values[i] = prefs.getProperty(keys[i]);
- }
- exportEntries(keys, values, out);
+ String[] keys = properties.keySet().toArray(new String[properties.size()]);
+ int length = keys.length;
+ String[] values = new String[length];
+ for (int i = 0; i < length; i++) {
+ values[i] = properties.getProperty(keys[i]);
}
- out.flush();
+ exportEntries(keys, values, out);
+ out.close();
+ if (!temporaryForWriting.renameTo(xmlFile)) {
+ throw new IOException("Failed to write preferences to " + xmlFile);
+ }
} finally {
- releaseQuietly(lock);
IoUtils.closeQuietly(out);
+ temporaryForWriting.delete(); // no-op unless something failed
}
}
-
- private static void releaseQuietly(FileLock lock) {
- if (lock == null) {
- return;
- }
- try {
- lock.release();
- } catch (IOException e) {}
- }
}
diff --git a/luni/src/main/java/java/util/regex/PatternSyntaxException.java b/luni/src/main/java/java/util/regex/PatternSyntaxException.java
index 2bbdb46..a8dec47 100644
--- a/luni/src/main/java/java/util/regex/PatternSyntaxException.java
+++ b/luni/src/main/java/java/util/regex/PatternSyntaxException.java
@@ -82,13 +82,12 @@
/**
* Returns a detailed error message for the exception. The message is
* potentially multi-line, and it might include a detailed description, the
- * original regular expression, and the index at which the error occured.
+ * original regular expression, and the index at which the error occurred.
*
* @return the error message.
*/
@Override
public String getMessage() {
- // BEGIN android-changed
StringBuilder builder = new StringBuilder("Syntax error");
if (desc != null) {
@@ -114,7 +113,6 @@
}
return builder.toString();
- // END android-changed
}
/**
diff --git a/luni/src/main/java/java/util/zip/GZIPInputStream.java b/luni/src/main/java/java/util/zip/GZIPInputStream.java
index 6a8f456..3e9b24d 100644
--- a/luni/src/main/java/java/util/zip/GZIPInputStream.java
+++ b/luni/src/main/java/java/util/zip/GZIPInputStream.java
@@ -56,7 +56,7 @@
/**
* The magic header for the GZIP format.
*/
- public final static int GZIP_MAGIC = 0x8b1f;
+ public static final int GZIP_MAGIC = 0x8b1f;
/**
* The checksum algorithm used when handling uncompressed data.
diff --git a/luni/src/main/java/java/util/zip/Inflater.java b/luni/src/main/java/java/util/zip/Inflater.java
index 9f430a8..ee10aa7 100644
--- a/luni/src/main/java/java/util/zip/Inflater.java
+++ b/luni/src/main/java/java/util/zip/Inflater.java
@@ -309,7 +309,6 @@
private native void setInputImpl(byte[] buf, int offset, int byteCount, long handle);
- // BEGIN android-only
synchronized int setFileInput(FileDescriptor fd, long offset, int byteCount) {
checkOpen();
inRead = 0;
@@ -318,7 +317,6 @@
}
private native int setFileInputImpl(FileDescriptor fd, long offset, int byteCount, long handle);
- // END android-only
private void checkOpen() {
if (streamHandle == -1) {
diff --git a/luni/src/main/java/java/util/zip/InflaterInputStream.java b/luni/src/main/java/java/util/zip/InflaterInputStream.java
index 35a3d9d..99fe8af 100644
--- a/luni/src/main/java/java/util/zip/InflaterInputStream.java
+++ b/luni/src/main/java/java/util/zip/InflaterInputStream.java
@@ -62,7 +62,7 @@
static final int BUF_SIZE = 512;
- int nativeEndBufSize = 0; // android-only
+ int nativeEndBufSize = 0;
/**
* This is the most basic constructor. You only need to pass the {@code
@@ -110,13 +110,11 @@
throw new IllegalArgumentException();
}
this.inf = inflater;
- // BEGIN android-only
if (is instanceof ZipFile.RAFStream) {
nativeEndBufSize = bsize;
} else {
buf = new byte[bsize];
}
- // END android-only
}
/**
@@ -193,7 +191,6 @@
*/
protected void fill() throws IOException {
checkClosed();
- // BEGIN android-only
if (nativeEndBufSize > 0) {
ZipFile.RAFStream is = (ZipFile.RAFStream)in;
synchronized (is.mSharedRaf) {
@@ -207,7 +204,6 @@
inf.setInput(buf, 0, len);
}
}
- // END android-only
}
/**
diff --git a/luni/src/main/java/java/util/zip/ZipFile.java b/luni/src/main/java/java/util/zip/ZipFile.java
index 06be579..9d389da 100644
--- a/luni/src/main/java/java/util/zip/ZipFile.java
+++ b/luni/src/main/java/java/util/zip/ZipFile.java
@@ -26,8 +26,6 @@
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;
@@ -60,7 +58,7 @@
* versions of PKZIP recognize this bit for any
* compression method.)
*/
- static final int GPBF_DATA_DESCRIPTOR_FLAG = 1 << 3; // android-added
+ static final int GPBF_DATA_DESCRIPTOR_FLAG = 1 << 3;
/**
* General Purpose Bit Flags, Bit 11.
@@ -68,7 +66,7 @@
* the filename and comment fields for this file
* must be encoded using UTF-8.
*/
- static final int GPBF_UTF8_FLAG = 1 << 11; // android-added
+ static final int GPBF_UTF8_FLAG = 1 << 11;
/**
* Open ZIP file for read.
@@ -122,14 +120,7 @@
throw new IllegalArgumentException();
}
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- security.checkRead(fileName);
- }
if ((mode & OPEN_DELETE) != 0) {
- if (security != null) {
- security.checkDelete(fileName);
- }
fileToDeleteOnClose = file; // file.deleteOnExit();
} else {
fileToDeleteOnClose = null;
@@ -183,13 +174,7 @@
raf.close();
}
if (fileToDeleteOnClose != null) {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- new File(fileName).delete();
- return null;
- }
- });
- // fileToDeleteOnClose.delete();
+ fileToDeleteOnClose.delete();
fileToDeleteOnClose = null;
}
}
diff --git a/luni/src/main/java/java/util/zip/ZipOutputStream.java b/luni/src/main/java/java/util/zip/ZipOutputStream.java
index 55a52bf..f0c79b2 100644
--- a/luni/src/main/java/java/util/zip/ZipOutputStream.java
+++ b/luni/src/main/java/java/util/zip/ZipOutputStream.java
@@ -21,8 +21,8 @@
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charsets;
+import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Vector;
/**
* This class provides an implementation of {@code FilterOutputStream} that
@@ -78,7 +78,7 @@
private String comment;
- private final Vector<String> entries = new Vector<String>();
+ private final ArrayList<String> entries = new ArrayList<String>();
private int compressMethod = DEFLATED;
@@ -223,7 +223,7 @@
if (cDir == null) {
return;
}
- if (entries.size() == 0) {
+ if (entries.isEmpty()) {
throw new ZipException("No entries");
}
if (currentEntry != null) {
@@ -292,7 +292,7 @@
if (currentEntry.getMethod() == -1) {
currentEntry.setMethod(compressMethod);
}
- // BEGIN android-changed
+
// Local file header.
// http://www.pkware.com/documents/casestudies/APPNOTE.TXT
int flags = currentEntry.getMethod() == STORED ? 0 : ZipFile.GPBF_DATA_DESCRIPTOR_FLAG;
@@ -308,7 +308,6 @@
}
writeShort(out, currentEntry.time);
writeShort(out, currentEntry.modDate);
- // END android-changed
if (currentEntry.getMethod() == STORED) {
if (currentEntry.size == -1) {
diff --git a/luni/src/main/java/javax/crypto/Cipher.java b/luni/src/main/java/javax/crypto/Cipher.java
index aaf6b35..06cfa70 100644
--- a/luni/src/main/java/javax/crypto/Cipher.java
+++ b/luni/src/main/java/javax/crypto/Cipher.java
@@ -32,7 +32,6 @@
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Set;
-import java.util.StringTokenizer;
import org.apache.harmony.crypto.internal.NullCipherSpi;
import org.apache.harmony.security.fortress.Engine;
@@ -327,31 +326,33 @@
return c;
}
- private static String[] checkTransformation(String transformation)
- throws NoSuchAlgorithmException {
- String[] transf = { null, null, null };
- StringTokenizer st;
- int i = 0;
- for (st = new StringTokenizer(transformation, "/"); st.hasMoreElements();) {
- if (i > 2) {
- throw invalidTransformation(transformation);
- }
- transf[i] = st.nextToken();
- if (transf[i] != null) {
- transf[i] = transf[i].trim();
- if (transf[i].isEmpty()) {
- transf[i] = null;
- }
- i++;
- }
+ private static String[] checkTransformation(String transformation) throws NoSuchAlgorithmException {
+ // ignore an extra prefix / characters such as in
+ // "/DES/CBC/PKCS5Paddin" http://b/3387688
+ if (transformation.startsWith("/")) {
+ transformation = transformation.substring(1);
}
- if (transf[0] == null) {
+ // 'transformation' should be of the form "algorithm/mode/padding".
+ String[] pieces = transformation.split("/");
+ if (pieces.length > 3) {
throw invalidTransformation(transformation);
}
- if (!(transf[1] == null && transf[2] == null) && (transf[1] == null || transf[2] == null)) {
+ // Empty or missing pieces are represented by null.
+ String[] result = new String[3];
+ for (int i = 0; i < pieces.length; ++i) {
+ String piece = pieces[i].trim();
+ if (!piece.isEmpty()) {
+ result[i] = piece;
+ }
+ }
+ // You MUST specify an algorithm.
+ if (result[0] == null) {
throw invalidTransformation(transformation);
}
- return transf;
+ if (!(result[1] == null && result[2] == null) && (result[1] == null || result[2] == null)) {
+ throw invalidTransformation(transformation);
+ }
+ return result;
}
/**
diff --git a/luni/src/main/java/javax/crypto/SealedObject.java b/luni/src/main/java/javax/crypto/SealedObject.java
index c6f8221..c9c1534 100644
--- a/luni/src/main/java/javax/crypto/SealedObject.java
+++ b/luni/src/main/java/javax/crypto/SealedObject.java
@@ -146,11 +146,9 @@
public final Object getObject(Key key)
throws IOException, ClassNotFoundException,
NoSuchAlgorithmException, InvalidKeyException {
- // BEGIN android-added
if (key == null) {
throw new InvalidKeyException("key == null");
}
- // END android-added
try {
Cipher cipher = Cipher.getInstance(sealAlg);
if ((paramsAlg != null) && (paramsAlg.length() != 0)) {
diff --git a/luni/src/main/java/javax/crypto/spec/SecretKeySpec.java b/luni/src/main/java/javax/crypto/spec/SecretKeySpec.java
index 99701ff..cb70643 100644
--- a/luni/src/main/java/javax/crypto/spec/SecretKeySpec.java
+++ b/luni/src/main/java/javax/crypto/spec/SecretKeySpec.java
@@ -98,11 +98,9 @@
if (key.length == 0) {
throw new IllegalArgumentException("key.length == 0");
}
- // BEGIN android-changed
if (len < 0 || offset < 0) {
throw new ArrayIndexOutOfBoundsException("len < 0 || offset < 0");
}
- // END android-changed
if (key.length - offset < len) {
throw new IllegalArgumentException("key too short");
}
diff --git a/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java b/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
index dc17202..61a5392 100644
--- a/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
+++ b/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
@@ -27,7 +27,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Locale;
-import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -51,7 +50,7 @@
* Looks like we're the only implementation guarding against this.
* Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
*/
- private final static String[] BAD_COUNTRY_2LDS =
+ private static final String[] BAD_COUNTRY_2LDS =
{ "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
"lg", "ne", "net", "or", "org" };
@@ -159,12 +158,10 @@
* I tested it with "花子.co.jp" and it worked fine.
*/
String subjectPrincipal = cert.getSubjectX500Principal().toString();
- StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
- while (st.hasMoreTokens()) {
- String tok = st.nextToken();
- int x = tok.indexOf("CN=");
+ for (String token : subjectPrincipal.split(",")) {
+ int x = token.indexOf("CN=");
if (x >= 0) {
- return tok.substring(x + 3);
+ return token.substring(x + 3);
}
}
return null;
@@ -189,7 +186,7 @@
.log(Level.FINE, "Error parsing certificate.", cpe);
return Collections.emptyList();
}
-
+
if (subjectAlternativeNames == null) {
return Collections.emptyList();
}
diff --git a/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java b/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java
index c5c9196..82ce8a1 100644
--- a/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java
+++ b/luni/src/main/java/javax/net/ssl/KeyManagerFactory.java
@@ -17,13 +17,11 @@
package javax.net.ssl;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
-import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
@@ -51,11 +49,7 @@
* @return the default algorithm name.
*/
public static final String getDefaultAlgorithm() {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTY_NAME);
- }
- });
+ return Security.getProperty(PROPERTY_NAME);
}
/**
diff --git a/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java b/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
index e8a7071..5cb3163 100644
--- a/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
+++ b/luni/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
@@ -17,9 +17,7 @@
package javax.net.ssl;
-import java.security.AccessController;
import java.security.NoSuchAlgorithmException;
-import java.security.PrivilegedAction;
import java.security.Security;
import javax.net.ServerSocketFactory;
@@ -46,23 +44,18 @@
return defaultServerSocketFactory;
}
if (defaultName == null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- defaultName = Security.getProperty("ssl.ServerSocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> ssfc = Class.forName(defaultName, true, cl);
- defaultServerSocketFactory = (ServerSocketFactory) ssfc.newInstance();
- } catch (Exception e) {
- }
- }
- return null;
+ defaultName = Security.getProperty("ssl.ServerSocketFactory.provider");
+ if (defaultName != null) {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if (cl == null) {
+ cl = ClassLoader.getSystemClassLoader();
}
- });
+ try {
+ final Class<?> ssfc = Class.forName(defaultName, true, cl);
+ defaultServerSocketFactory = (ServerSocketFactory) ssfc.newInstance();
+ } catch (Exception e) {
+ }
+ }
}
if (defaultServerSocketFactory == null) {
SSLContext context;
diff --git a/luni/src/main/java/javax/net/ssl/SSLSession.java b/luni/src/main/java/javax/net/ssl/SSLSession.java
index 14a312a..c4ca0a6 100644
--- a/luni/src/main/java/javax/net/ssl/SSLSession.java
+++ b/luni/src/main/java/javax/net/ssl/SSLSession.java
@@ -150,13 +150,7 @@
public String getProtocol();
/**
- * Returns the context of this session. If a context is available and a
- * security manager is installed, the
- * {@code SSLPermission("getSSLSessionContext"} is checked with the security
- * manager.
- *
- * @return the context of this session or {@code null} if no context is
- * available.
+ * Returns the context of this session, or null if no context is available.
*/
public SSLSessionContext getSessionContext();
diff --git a/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java b/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java
index b31d4e2..1f3aa42 100644
--- a/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java
+++ b/luni/src/main/java/javax/net/ssl/SSLSocketFactory.java
@@ -19,9 +19,7 @@
import java.io.IOException;
import java.net.Socket;
-import java.security.AccessController;
import java.security.NoSuchAlgorithmException;
-import java.security.PrivilegedAction;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -46,32 +44,22 @@
*/
public static synchronized SocketFactory getDefault() {
if (defaultSocketFactory != null) {
- // BEGIN android-added
- // log("SSLSocketFactory", "Using factory " + defaultSocketFactory, null);
- // END android-added
return defaultSocketFactory;
}
if (defaultName == null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- defaultName = Security.getProperty("ssl.SocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> sfc = Class.forName(defaultName, true, cl);
- defaultSocketFactory = (SocketFactory) sfc.newInstance();
- } catch (Exception e) {
- // BEGIN android-added
- log("SSLSocketFactory", "Problem creating " + defaultName, e);
- // END android-added
- }
- }
- return null;
+ defaultName = Security.getProperty("ssl.SocketFactory.provider");
+ if (defaultName != null) {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if (cl == null) {
+ cl = ClassLoader.getSystemClassLoader();
}
- });
+ try {
+ final Class<?> sfc = Class.forName(defaultName, true, cl);
+ defaultSocketFactory = (SocketFactory) sfc.newInstance();
+ } catch (Exception e) {
+ log("SSLSocketFactory", "Problem creating " + defaultName, e);
+ }
+ }
}
if (defaultSocketFactory == null) {
@@ -89,18 +77,13 @@
// Use internal implementation
defaultSocketFactory = new DefaultSSLSocketFactory("No SSLSocketFactory installed");
}
- // BEGIN android-added
- // log("SSLSocketFactory", "Using factory " + defaultSocketFactory, null);
- // END android-added
return defaultSocketFactory;
}
- // BEGIN android-added
@SuppressWarnings("unchecked")
private static void log(String tag, String msg, Throwable throwable) {
Logger.getLogger(tag).log(Level.INFO, msg, throwable);
}
- // END android-added
/**
* Creates a new {@code SSLSocketFactory}.
diff --git a/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java b/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java
index 04633a4..fc692ca 100644
--- a/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java
+++ b/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java
@@ -17,13 +17,11 @@
package javax.net.ssl;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
-import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.Security;
import org.apache.harmony.security.fortress.Engine;
@@ -50,11 +48,7 @@
* @return the default algorithm name.
*/
public static final String getDefaultAlgorithm() {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- });
+ return Security.getProperty(PROPERTYNAME);
}
/**
diff --git a/luni/src/main/java/javax/security/auth/Subject.java b/luni/src/main/java/javax/security/auth/Subject.java
index ac0fab4..adb0e44 100644
--- a/luni/src/main/java/javax/security/auth/Subject.java
+++ b/luni/src/main/java/javax/security/auth/Subject.java
@@ -140,9 +140,6 @@
*/
@SuppressWarnings("unchecked")
public static <T> T doAs(Subject subject, PrivilegedAction<T> action) {
-
- checkPermission(_AS);
-
return doAs_PrivilegedAction(subject, action, AccessController.getContext());
}
@@ -164,9 +161,6 @@
@SuppressWarnings("unchecked")
public static <T> T doAsPrivileged(Subject subject, PrivilegedAction<T> action,
AccessControlContext context) {
-
- checkPermission(_AS_PRIVILEGED);
-
if (context == null) {
return doAs_PrivilegedAction(subject, action, new AccessControlContext(
new ProtectionDomain[0]));
@@ -192,7 +186,6 @@
PrivilegedAction dccAction = new PrivilegedAction() {
public Object run() {
-
return new AccessControlContext(context, combiner);
}
};
@@ -217,9 +210,6 @@
@SuppressWarnings("unchecked")
public static <T> T doAs(Subject subject, PrivilegedExceptionAction<T> action)
throws PrivilegedActionException {
-
- checkPermission(_AS);
-
return doAs_PrivilegedExceptionAction(subject, action, AccessController.getContext());
}
@@ -244,9 +234,6 @@
public static <T> T doAsPrivileged(Subject subject,
PrivilegedExceptionAction<T> action, AccessControlContext context)
throws PrivilegedActionException {
-
- checkPermission(_AS_PRIVILEGED);
-
if (context == null) {
return doAs_PrivilegedExceptionAction(subject, action,
new AccessControlContext(new ProtectionDomain[0]));
@@ -406,8 +393,6 @@
* works though.
*/
public void setReadOnly() {
- checkPermission(_READ_ONLY);
-
readOnly = true;
}
@@ -482,7 +467,6 @@
* context} provided as argument.
*/
public static Subject getSubject(final AccessControlContext context) {
- checkPermission(_SUBJECT);
if (context == null) {
throw new NullPointerException("AccessControlContext cannot be null");
}
@@ -499,14 +483,6 @@
return ((SubjectDomainCombiner) combiner).getSubject();
}
- // checks passed permission
- private static void checkPermission(Permission p) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(p);
- }
- }
-
private void checkState() {
if (readOnly) {
throw new IllegalStateException("Set is read-only");
@@ -596,7 +572,6 @@
verifyElement(o);
checkState();
- checkPermission(permission);
if (!elements.contains(o)) {
elements.add(o);
@@ -622,8 +597,6 @@
@Override
public SST next() {
SST obj = iterator.next();
- checkPermission(new PrivateCredentialPermission(obj
- .getClass().getName(), principals));
return obj;
}
};
@@ -727,8 +700,6 @@
private void writeObject(ObjectOutputStream out) throws IOException {
if (permission == _PRIVATE_CREDENTIALS) {
- // iteration causes checkPermission to be called for each element
- for (SST unused : this) {}
setType = SET_PrivCred;
} else if (permission == _PRINCIPALS) {
setType = SET_Principal;
@@ -763,7 +734,6 @@
*/
public void remove() {
checkState();
- checkPermission(permission);
iterator.remove();
}
}
diff --git a/luni/src/main/java/javax/security/auth/SubjectDomainCombiner.java b/luni/src/main/java/javax/security/auth/SubjectDomainCombiner.java
index 7d990a1..e7cc971 100644
--- a/luni/src/main/java/javax/security/auth/SubjectDomainCombiner.java
+++ b/luni/src/main/java/javax/security/auth/SubjectDomainCombiner.java
@@ -55,11 +55,6 @@
* @return the entity to which this domain combiner is associated.
*/
public Subject getSubject() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(_GET);
- }
-
return subject;
}
diff --git a/luni/src/main/java/javax/security/auth/x500/X500Principal.java b/luni/src/main/java/javax/security/auth/x500/X500Principal.java
index 9e1fb9a..f13dd4f 100644
--- a/luni/src/main/java/javax/security/auth/x500/X500Principal.java
+++ b/luni/src/main/java/javax/security/auth/x500/X500Principal.java
@@ -223,7 +223,7 @@
String rfc1779Name = dn.getName(RFC1779);
String rfc2253Name = dn.getName(RFC2253);
- if (format.toUpperCase().equals("RFC1779")) {
+ if (format.equalsIgnoreCase("RFC1779")) {
StringBuilder resultName = new StringBuilder(rfc1779Name);
int fromIndex = resultName.length();
int equalIndex = -1;
@@ -243,7 +243,7 @@
fromIndex = commaIndex;
}
return resultName.toString();
- } else if (format.toUpperCase().equals("RFC2253")) {
+ } else if (format.equalsIgnoreCase("RFC2253")) {
StringBuilder resultName = new StringBuilder(rfc2253Name);
StringBuilder subsidyName = new StringBuilder(rfc1779Name);
diff --git a/luni/src/main/java/javax/security/cert/X509Certificate.java b/luni/src/main/java/javax/security/cert/X509Certificate.java
index fe5b9f7..1854692 100644
--- a/luni/src/main/java/javax/security/cert/X509Certificate.java
+++ b/luni/src/main/java/javax/security/cert/X509Certificate.java
@@ -21,7 +21,6 @@
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.math.BigInteger;
-import java.security.AccessController;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
@@ -47,19 +46,11 @@
public abstract class X509Certificate extends Certificate {
private static Constructor constructor;
-
static {
try {
- String classname = (String) AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
- return Security.getProperty("cert.provider.x509v1");
- }
- }
- );
+ String classname = Security.getProperty("cert.provider.x509v1");
Class cl = Class.forName(classname);
- constructor =
- cl.getConstructor(new Class[] {InputStream.class});
+ constructor = cl.getConstructor(new Class[] {InputStream.class});
} catch (Throwable e) {
}
}
diff --git a/luni/src/main/java/libcore/icu/CharsetDecoderICU.java b/luni/src/main/java/libcore/icu/CharsetDecoderICU.java
deleted file mode 100644
index 86ba13b..0000000
--- a/luni/src/main/java/libcore/icu/CharsetDecoderICU.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2006, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*******************************************************************************
-*/
- /**
- * A JNI interface for ICU converters.
- *
- *
- * @author Ram Viswanadha, IBM
- */
-package libcore.icu;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.CodingErrorAction;
-
-public final class CharsetDecoderICU extends CharsetDecoder {
- private static final int MAX_CHARS_PER_BYTE = 2;
-
- private static final int INPUT_OFFSET = 0;
- private static final int OUTPUT_OFFSET = 1;
- private static final int INVALID_BYTES = 2;
- private static final int INPUT_HELD = 3;
- /*
- * data[INPUT_OFFSET] = on input contains the start of input and on output the number of input bytes consumed
- * data[OUTPUT_OFFSET] = on input contains the start of output and on output the number of output chars written
- * data[INVALID_BYTES] = number of invalid bytes
- * data[INPUT_HELD] = number of input bytes held in the converter's state
- */
- private int[] data = new int[4];
-
- /* handle to the ICU converter that is opened */
- private long converterHandle = 0;
-
- private byte[] input = null;
- private char[] output= null;
-
- // BEGIN android-added
- private byte[] allocatedInput = null;
- private char[] allocatedOutput = null;
- // END android-added
-
- // These instance variables are always assigned in the methods before being used. This class
- // is inherently thread-unsafe so we don't have to worry about synchronization.
- private int inEnd;
- private int outEnd;
- private int ec;
- private int savedInputHeldLen;
-
- public static CharsetDecoderICU newInstance(Charset cs, String icuCanonicalName) {
- // This complexity is necessary to ensure that even if the constructor, superclass
- // constructor, or call to updateCallback throw, we still free the native peer.
- long address = 0;
- try {
- address = NativeConverter.openConverter(icuCanonicalName);
- float averageCharsPerByte = NativeConverter.getAveCharsPerByte(address);
- CharsetDecoderICU result = new CharsetDecoderICU(cs, averageCharsPerByte, address);
- address = 0; // CharsetDecoderICU has taken ownership; its finalizer will do the free.
- result.updateCallback();
- return result;
- } finally {
- if (address != 0) {
- NativeConverter.closeConverter(address);
- }
- }
- }
-
- private CharsetDecoderICU(Charset cs, float averageCharsPerByte, long address) {
- super(cs, averageCharsPerByte, MAX_CHARS_PER_BYTE);
- this.converterHandle = address;
- }
-
- /**
- * Sets this decoders replacement string. Substitutes the string in input if an
- * unmappable or illegal sequence is encountered
- * @param newReplacement to replace the error bytes with
- * @stable ICU 2.4
- */
- protected void implReplaceWith(String newReplacement) {
- if (converterHandle > 0) {
- if (newReplacement.length() > NativeConverter.getMaxBytesPerChar(converterHandle)) {
- throw new IllegalArgumentException();
- }
- updateCallback();
- }
- }
-
- /**
- * Sets the action to be taken if an illegal sequence is encountered
- * @param newAction action to be taken
- * @exception IllegalArgumentException
- * @stable ICU 2.4
- */
- protected final void implOnMalformedInput(CodingErrorAction newAction) {
- updateCallback();
- }
-
- /**
- * Sets the action to be taken if an illegal sequence is encountered
- * @param newAction action to be taken
- * @exception IllegalArgumentException
- * @stable ICU 2.4
- */
- protected final void implOnUnmappableCharacter(CodingErrorAction newAction) {
- updateCallback();
- }
-
- private void updateCallback() {
- ec = NativeConverter.setCallbackDecode(converterHandle, this);
- if (ErrorCode.isFailure(ec)) {
- throw ErrorCode.throwException(ec);
- }
- }
-
- /**
- * Flushes any characters saved in the converter's internal buffer and
- * resets the converter.
- * @param out action to be taken
- * @return result of flushing action and completes the decoding all input.
- * Returns CoderResult.UNDERFLOW if the action succeeds.
- * @stable ICU 2.4
- */
- protected final CoderResult implFlush(CharBuffer out) {
- try {
- data[OUTPUT_OFFSET] = getArray(out);
- ec = NativeConverter.flushByteToChar(
- converterHandle, /* Handle to ICU Converter */
- output, /* input array of chars */
- outEnd, /* input index+1 to be written */
- data /* contains data, inOff,outOff */
- );
-
- /* If we don't have room for the output, throw an exception*/
- if (ErrorCode.isFailure(ec)) {
- if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
- return CoderResult.OVERFLOW;
- } else if (ec == ErrorCode.U_TRUNCATED_CHAR_FOUND) {//CSDL: add this truncated character error handling
- if (data[INPUT_OFFSET] > 0) {
- return CoderResult.malformedForLength(data[INPUT_OFFSET]);
- }
- } else {
- throw ErrorCode.throwException(ec);
- }
- }
- return CoderResult.UNDERFLOW;
- } finally {
- /* save the flushed data */
- setPosition(out);
- implReset();
- }
- }
-
- protected void implReset() {
- NativeConverter.resetByteToChar(converterHandle);
- data[INPUT_OFFSET] = 0;
- data[OUTPUT_OFFSET] = 0;
- data[INVALID_BYTES] = 0;
- data[INPUT_HELD] = 0;
- savedInputHeldLen = 0;
- output = null;
- input = null;
- allocatedInput = null;
- allocatedOutput = null;
- ec = 0;
- inEnd = 0;
- outEnd = 0;
- }
-
- /**
- * Decodes one or more bytes. The default behavior of the converter
- * is stop and report if an error in input stream is encountered.
- * To set different behavior use @see CharsetDecoder.onMalformedInput()
- * This method allows a buffer by buffer conversion of a data stream.
- * The state of the conversion is saved between calls to convert.
- * Among other things, this means multibyte input sequences can be
- * split between calls. If a call to convert results in an Error, the
- * conversion may be continued by calling convert again with suitably
- * modified parameters.All conversions should be finished with a call to
- * the flush method.
- * @param in buffer to decode
- * @param out buffer to populate with decoded result
- * @return result of decoding action. Returns CoderResult.UNDERFLOW if the decoding
- * action succeeds or more input is needed for completing the decoding action.
- * @stable ICU 2.4
- */
- protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out){
- if (!in.hasRemaining()){
- return CoderResult.UNDERFLOW;
- }
-
- data[INPUT_OFFSET] = getArray(in);
- data[OUTPUT_OFFSET]= getArray(out);
- data[INPUT_HELD] = 0;
-
- try{
- ec = NativeConverter.decode(
- converterHandle, /* Handle to ICU Converter */
- input, /* input array of bytes */
- inEnd, /* last index+1 to be converted */
- output, /* input array of chars */
- outEnd, /* input index+1 to be written */
- data, /* contains data, inOff,outOff */
- false /* don't flush the data */
- );
-
- // Return an error.
- if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
- return CoderResult.OVERFLOW;
- } else if (ec == ErrorCode.U_INVALID_CHAR_FOUND) {
- return CoderResult.unmappableForLength(data[INVALID_BYTES]);
- } else if (ec == ErrorCode.U_ILLEGAL_CHAR_FOUND) {
- return CoderResult.malformedForLength(data[INVALID_BYTES]);
- }
- // Decoding succeeded: give us more data.
- return CoderResult.UNDERFLOW;
- } finally {
- setPosition(in);
- setPosition(out);
- }
- }
-
- /**
- * Releases the system resources by cleanly closing ICU converter opened
- * @stable ICU 2.4
- */
- @Override protected void finalize() throws Throwable {
- try {
- NativeConverter.closeConverter(converterHandle);
- converterHandle = 0;
- } finally {
- super.finalize();
- }
- }
-
- //------------------------------------------
- // private utility methods
- //------------------------------------------
-
- private int getArray(CharBuffer out) {
- if (out.hasArray()) {
- // BEGIN android-changed: take arrayOffset into account
- output = out.array();
- outEnd = out.arrayOffset() + out.limit();
- return out.arrayOffset() + out.position();
- // END android-changed
- } else {
- outEnd = out.remaining();
- // BEGIN android-added
- if (allocatedOutput == null || (outEnd > allocatedOutput.length)) {
- allocatedOutput = new char[outEnd];
- }
- output = allocatedOutput;
- // END android-added
- //since the new
- // buffer start position
- // is 0
- return 0;
- }
- }
-
- private int getArray(ByteBuffer in) {
- if (in.hasArray()) {
- // BEGIN android-changed: take arrayOffset into account
- input = in.array();
- inEnd = in.arrayOffset() + in.limit();
- return in.arrayOffset() + in.position() + savedInputHeldLen;/*exclude the number fo bytes held in previous conversion*/
- // END android-changed
- } else {
- inEnd = in.remaining();
- // BEGIN android-added
- if (allocatedInput == null || (inEnd > allocatedInput.length)) {
- allocatedInput = new byte[inEnd];
- }
- input = allocatedInput;
- // END android-added
- // save the current position
- int pos = in.position();
- in.get(input,0,inEnd);
- // reset the position
- in.position(pos);
- // the start position
- // of the new buffer
- // is whatever is savedInputLen
- return savedInputHeldLen;
- }
- }
-
- private void setPosition(CharBuffer out) {
- if (out.hasArray()) {
- out.position(out.position() + data[OUTPUT_OFFSET] - out.arrayOffset());
- } else {
- out.put(output, 0, data[OUTPUT_OFFSET]);
- }
- // release reference to output array, which may not be ours
- output = null;
- }
-
- private void setPosition(ByteBuffer in) {
- // ok was there input held in the previous invocation of decodeLoop
- // that resulted in output in this invocation?
- in.position(in.position() + data[INPUT_OFFSET] + savedInputHeldLen - data[INPUT_HELD]);
- savedInputHeldLen = data[INPUT_HELD];
- // release reference to input array, which may not be ours
- input = null;
- }
-}
diff --git a/luni/src/main/java/libcore/icu/CharsetEncoderICU.java b/luni/src/main/java/libcore/icu/CharsetEncoderICU.java
deleted file mode 100644
index 2855a4c..0000000
--- a/luni/src/main/java/libcore/icu/CharsetEncoderICU.java
+++ /dev/null
@@ -1,378 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2006, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*******************************************************************************
-*/
-/**
- * A JNI interface for ICU converters.
- *
- *
- * @author Ram Viswanadha, IBM
- */
-package libcore.icu;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.CodingErrorAction;
-import java.util.HashMap;
-import java.util.Map;
-
-public final class CharsetEncoderICU extends CharsetEncoder {
- private static final Map<String, byte[]> DEFAULT_REPLACEMENTS = new HashMap<String, byte[]>();
- static {
- // ICU has different default replacements to the RI in some cases. There are many
- // additional cases, but this covers all the charsets that Java guarantees will be
- // available, which is where compatibility seems most important. (The RI even uses
- // the byte corresponding to '?' in ASCII as the replacement byte for charsets where that
- // byte corresponds to an entirely different character.)
- // It's odd that UTF-8 doesn't use U+FFFD, given that (unlike ISO-8859-1 and US-ASCII) it
- // can represent it, but this is what the RI does...
- byte[] questionMark = new byte[] { (byte) '?' };
- DEFAULT_REPLACEMENTS.put("UTF-8", questionMark);
- DEFAULT_REPLACEMENTS.put("ISO-8859-1", questionMark);
- DEFAULT_REPLACEMENTS.put("US-ASCII", questionMark);
- }
-
- private static final int INPUT_OFFSET = 0;
- private static final int OUTPUT_OFFSET = 1;
- private static final int INVALID_CHARS = 2;
- private static final int INPUT_HELD = 3;
- /*
- * data[INPUT_OFFSET] = on input contains the start of input and on output the number of input chars consumed
- * data[OUTPUT_OFFSET] = on input contains the start of output and on output the number of output bytes written
- * data[INVALID_CHARS] = number of invalid chars
- * data[INPUT_HELD] = number of input chars held in the converter's state
- */
- private int[] data = new int[4];
- /* handle to the ICU converter that is opened */
- private long converterHandle=0;
-
- private char[] input = null;
- private byte[] output = null;
-
- // BEGIN android-added
- private char[] allocatedInput = null;
- private byte[] allocatedOutput = null;
- // END android-added
-
- // These instance variables are always assigned in the methods before being used. This class
- // is inherently thread-unsafe so we don't have to worry about synchronization.
- private int inEnd;
- private int outEnd;
- private int ec;
- private int savedInputHeldLen;
-
- public static CharsetEncoderICU newInstance(Charset cs, String icuCanonicalName) {
- // This complexity is necessary to ensure that even if the constructor, superclass
- // constructor, or call to updateCallback throw, we still free the native peer.
- long address = 0;
- try {
- address = NativeConverter.openConverter(icuCanonicalName);
- float averageBytesPerChar = NativeConverter.getAveBytesPerChar(address);
- float maxBytesPerChar = NativeConverter.getMaxBytesPerChar(address);
- byte[] replacement = makeReplacement(icuCanonicalName, address);
- CharsetEncoderICU result = new CharsetEncoderICU(cs, averageBytesPerChar, maxBytesPerChar, replacement, address);
- address = 0; // CharsetEncoderICU has taken ownership; its finalizer will do the free.
- result.updateCallback();
- return result;
- } finally {
- if (address != 0) {
- NativeConverter.closeConverter(address);
- }
- }
- }
-
- private static byte[] makeReplacement(String icuCanonicalName, long address) {
- // We have our own map of RI-compatible default replacements (where ICU disagrees)...
- byte[] replacement = DEFAULT_REPLACEMENTS.get(icuCanonicalName);
- if (replacement != null) {
- return replacement.clone();
- }
- // ...but fall back to asking ICU.
- return NativeConverter.getSubstitutionBytes(address);
- }
-
- private CharsetEncoderICU(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement, long address) {
- super(cs, averageBytesPerChar, maxBytesPerChar, replacement);
- this.converterHandle = address;
- }
-
- /**
- * Sets this encoders replacement string. Substitutes the string in output if an
- * unmappable or illegal sequence is encountered
- * @param newReplacement to replace the error chars with
- * @stable ICU 2.4
- */
- protected void implReplaceWith(byte[] newReplacement) {
- if (converterHandle != 0) {
- if (newReplacement.length > NativeConverter.getMaxBytesPerChar(converterHandle)) {
- throw new IllegalArgumentException("Number of replacement Bytes are greater than max bytes per char");
- }
- updateCallback();
- }
- }
-
- /**
- * Sets the action to be taken if an illegal sequence is encountered
- * @param newAction action to be taken
- * @exception IllegalArgumentException
- * @stable ICU 2.4
- */
- protected void implOnMalformedInput(CodingErrorAction newAction) {
- updateCallback();
- }
-
- /**
- * Sets the action to be taken if an illegal sequence is encountered
- * @param newAction action to be taken
- * @exception IllegalArgumentException
- * @stable ICU 2.4
- */
- protected void implOnUnmappableCharacter(CodingErrorAction newAction) {
- updateCallback();
- }
-
- private void updateCallback() {
- ec = NativeConverter.setCallbackEncode(converterHandle, this);
- if (ErrorCode.isFailure(ec)) {
- throw ErrorCode.throwException(ec);
- }
- }
-
- /**
- * Flushes any characters saved in the converter's internal buffer and
- * resets the converter.
- * @param out action to be taken
- * @return result of flushing action and completes the decoding all input.
- * Returns CoderResult.UNDERFLOW if the action succeeds.
- * @stable ICU 2.4
- */
- protected CoderResult implFlush(ByteBuffer out) {
- try {
- data[OUTPUT_OFFSET] = getArray(out);
- ec = NativeConverter.flushCharToByte(converterHandle,/* Handle to ICU Converter */
- output, /* output array of chars */
- outEnd, /* output index+1 to be written */
- data /* contains data, inOff,outOff */
- );
-
- /* If we don't have room for the output, throw an exception*/
- if (ErrorCode.isFailure(ec)) {
- if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
- return CoderResult.OVERFLOW;
- } else if (ec == ErrorCode.U_TRUNCATED_CHAR_FOUND) {//CSDL: add this truncated character error handling
- if (data[INPUT_OFFSET] > 0) {
- return CoderResult.malformedForLength(data[INPUT_OFFSET]);
- }
- } else {
- throw ErrorCode.throwException(ec);
- }
- }
- return CoderResult.UNDERFLOW;
- } finally {
- setPosition(out);
- implReset();
- }
- }
-
- /**
- * Resets the from Unicode mode of converter
- * @stable ICU 2.4
- */
- protected void implReset() {
- NativeConverter.resetCharToByte(converterHandle);
- data[INPUT_OFFSET] = 0;
- data[OUTPUT_OFFSET] = 0;
- data[INVALID_CHARS] = 0;
- data[INPUT_HELD] = 0;
- savedInputHeldLen = 0;
- }
-
- /**
- * Encodes one or more chars. The default behavior of the
- * converter is stop and report if an error in input stream is encountered.
- * To set different behavior use @see CharsetEncoder.onMalformedInput()
- * @param in buffer to decode
- * @param out buffer to populate with decoded result
- * @return result of decoding action. Returns CoderResult.UNDERFLOW if the decoding
- * action succeeds or more input is needed for completing the decoding action.
- * @stable ICU 2.4
- */
- protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
- if (!in.hasRemaining()) {
- return CoderResult.UNDERFLOW;
- }
-
- data[INPUT_OFFSET] = getArray(in);
- data[OUTPUT_OFFSET]= getArray(out);
- data[INPUT_HELD] = 0;
- // BEGIN android-added
- data[INVALID_CHARS] = 0; // Make sure we don't see earlier errors.
- // END android added
-
- try {
- /* do the conversion */
- ec = NativeConverter.encode(converterHandle,/* Handle to ICU Converter */
- input, /* input array of bytes */
- inEnd, /* last index+1 to be converted */
- output, /* output array of chars */
- outEnd, /* output index+1 to be written */
- data, /* contains data, inOff,outOff */
- false /* don't flush the data */
- );
- if (ErrorCode.isFailure(ec)) {
- /* If we don't have room for the output return error */
- if (ec == ErrorCode.U_BUFFER_OVERFLOW_ERROR) {
- return CoderResult.OVERFLOW;
- } else if (ec == ErrorCode.U_INVALID_CHAR_FOUND) {
- return CoderResult.unmappableForLength(data[INVALID_CHARS]);
- } else if (ec == ErrorCode.U_ILLEGAL_CHAR_FOUND) {
- // in.position(in.position() - 1);
- return CoderResult.malformedForLength(data[INVALID_CHARS]);
- }
- }
- return CoderResult.UNDERFLOW;
- } finally {
- /* save state */
- setPosition(in);
- setPosition(out);
- }
- }
-
- public boolean canEncode(char c) {
- return canEncode((int) c);
- }
-
- public boolean canEncode(int codePoint) {
- return NativeConverter.canEncode(converterHandle, codePoint);
- }
-
- /**
- * Releases the system resources by cleanly closing ICU converter opened
- * @exception Throwable exception thrown by super class' finalize method
- * @stable ICU 2.4
- */
- @Override protected void finalize() throws Throwable {
- try {
- NativeConverter.closeConverter(converterHandle);
- converterHandle=0;
- } finally {
- super.finalize();
- }
- }
-
- //------------------------------------------
- // private utility methods
- //------------------------------------------
- private int getArray(ByteBuffer out) {
- if (out.hasArray()) {
- // BEGIN android-changed: take arrayOffset into account
- output = out.array();
- outEnd = out.arrayOffset() + out.limit();
- return out.arrayOffset() + out.position();
- // END android-changed
- } else {
- outEnd = out.remaining();
- // BEGIN android-added
- if (allocatedOutput == null || (outEnd > allocatedOutput.length)) {
- allocatedOutput = new byte[outEnd];
- }
- output = allocatedOutput;
- // END android-added
- //since the new
- // buffer start position
- // is 0
- return 0;
- }
- }
-
- private int getArray(CharBuffer in) {
- if (in.hasArray()) {
- // BEGIN android-changed: take arrayOffset into account
- input = in.array();
- inEnd = in.arrayOffset() + in.limit();
- return in.arrayOffset() + in.position() + savedInputHeldLen;/*exclude the number fo bytes held in previous conversion*/
- // END android-changed
- } else {
- inEnd = in.remaining();
- // BEGIN android-added
- if (allocatedInput == null || (inEnd > allocatedInput.length)) {
- allocatedInput = new char[inEnd];
- }
- input = allocatedInput;
- // END android-added
- // save the current position
- int pos = in.position();
- in.get(input,0,inEnd);
- // reset the position
- in.position(pos);
- // the start position
- // of the new buffer
- // is whatever is savedInputLen
- return savedInputHeldLen;
- }
-
- }
- private void setPosition(ByteBuffer out) {
-
- if (out.hasArray()) {
- // in getArray method we accessed the
- // array backing the buffer directly and wrote to
- // it, so just just set the position and return.
- // This is done to avoid the creation of temp array.
- // BEGIN android-changed: take arrayOffset into account
- out.position(out.position() + data[OUTPUT_OFFSET] - out.arrayOffset());
- // END android-changed
- } else {
- out.put(output, 0, data[OUTPUT_OFFSET]);
- }
- // BEGIN android-added
- // release reference to output array, which may not be ours
- output = null;
- // END android-added
- }
- private void setPosition(CharBuffer in){
-
-// BEGIN android-removed
-// // was there input held in the previous invocation of encodeLoop
-// // that resulted in output in this invocation?
-// if(data[OUTPUT_OFFSET]>0 && savedInputHeldLen>0){
-// int len = in.position() + data[INPUT_OFFSET] + savedInputHeldLen;
-// in.position(len);
-// savedInputHeldLen = data[INPUT_HELD];
-// }else{
-// in.position(in.position() + data[INPUT_OFFSET] + savedInputHeldLen);
-// savedInputHeldLen = data[INPUT_HELD];
-// in.position(in.position() - savedInputHeldLen);
-// }
-// END android-removed
-
-// BEGIN android-added
- // Slightly rewired original code to make it cleaner. Also
- // added a fix for the problem where input characters got
- // lost when invalid characters were encountered. Not sure
- // what happens when data[INVALID_CHARS] is > 1, though,
- // since we never saw that happening.
- int len = in.position() + data[INPUT_OFFSET] + savedInputHeldLen;
- len -= data[INVALID_CHARS]; // Otherwise position becomes wrong.
- in.position(len);
- savedInputHeldLen = data[INPUT_HELD];
- // was there input held in the previous invocation of encodeLoop
- // that resulted in output in this invocation?
- if(!(data[OUTPUT_OFFSET]>0 && savedInputHeldLen>0)){
- in.position(in.position() - savedInputHeldLen);
- }
-// END android-added
-
- // BEGIN android-added
- // release reference to input array, which may not be ours
- input = null;
- // END android-added
- }
-}
diff --git a/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java b/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
index 6d85718..05caa0b 100644
--- a/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
+++ b/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
@@ -99,11 +99,9 @@
NativeCollation.setText(address, source);
}
- // BEGIN android-added
public void setText(CharacterIterator source) {
NativeCollation.setText(address, source.toString());
}
- // END android-added
/**
* Get the offset of the current source character.
diff --git a/luni/src/main/java/libcore/icu/ICU.java b/luni/src/main/java/libcore/icu/ICU.java
index 3359305..8fee63c 100644
--- a/luni/src/main/java/libcore/icu/ICU.java
+++ b/luni/src/main/java/libcore/icu/ICU.java
@@ -123,6 +123,16 @@
return localesFromStrings(getAvailableNumberFormatLocalesNative());
}
+ /**
+ * Returns the ICU version in use. This is "4.4" for gingerbread, for example.
+ */
+ public static native String getIcuVersion();
+
+ /**
+ * Returns the Unicode version our ICU supports. This is "5.2" for gingerbread, for example.
+ */
+ public static native String getUnicodeVersion();
+
// --- Case mapping.
public static native String toLowerCase(String s, String localeName);
diff --git a/luni/src/main/java/libcore/icu/NativeConverter.java b/luni/src/main/java/libcore/icu/NativeConverter.java
index 6165c61..2d8630c 100644
--- a/luni/src/main/java/libcore/icu/NativeConverter.java
+++ b/luni/src/main/java/libcore/icu/NativeConverter.java
@@ -15,83 +15,12 @@
import java.nio.charset.CodingErrorAction;
public final class NativeConverter {
- /**
- * Converts an array of bytes containing characters in an external
- * encoding into an array of Unicode characters. This method allows
- * buffer-by-buffer conversion of a data stream. The state of the
- * conversion is saved between calls. Among other things,
- * this means multibyte input sequences can be split between calls.
- * If a call to results in an error, the conversion may be
- * continued by calling this method again with suitably modified parameters.
- * All conversions should be finished with a call to the flush method.
- *
- * @param converterHandle Address of converter object created by C code
- * @param input byte array containing text to be converted.
- * @param inEnd stop conversion at this offset in input array (exclusive).
- * @param output character array to receive conversion result.
- * @param outEnd stop writing to output array at this offset (exclusive).
- * @param data integer array containing the following data
- * data[0] = inputOffset
- * data[1] = outputOffset
- * @return int error code returned by ICU
- * @internal ICU 2.4
- */
public static native int decode(long converterHandle, byte[] input, int inEnd,
char[] output, int outEnd, int[] data, boolean flush);
- /**
- * Converts an array of Unicode chars to an array of bytes in an external encoding.
- * This method allows a buffer by buffer conversion of a data stream. The state of the
- * conversion is saved between calls to convert. Among other things,
- * this means multibyte input sequences can be split between calls.
- * If a call results in an error, the conversion may be
- * continued by calling this method again with suitably modified parameters.
- * All conversions should be finished with a call to the flush method.
- *
- * @param converterHandle Address of converter object created by C code
- * @param input char array containing text to be converted.
- * @param inEnd stop conversion at this offset in input array (exclusive).
- * @param output byte array to receive conversion result.
- * @param outEnd stop writing to output array at this offset (exclusive).
- * @param data integer array containing the following data
- * data[0] = inputOffset
- * data[1] = outputOffset
- * @return int error code returned by ICU
- * @internal ICU 2.4
- */
public static native int encode(long converterHandle, char[] input, int inEnd,
byte[] output, int outEnd, int[] data, boolean flush);
- /**
- * Writes any remaining output to the output buffer and resets the
- * converter to its initial state.
- *
- * @param converterHandle Address of converter object created by C code
- * @param output byte array to receive flushed output.
- * @param outEnd stop writing to output array at this offset (exclusive).
- * @return int error code returned by ICU
- * @param data integer array containing the following data
- * data[0] = inputOffset
- * data[1] = outputOffset
- * @internal ICU 2.4
- */
- public static native int flushCharToByte(long converterHandle, byte[] output, int outEnd, int[] data);
-
- /**
- * Writes any remaining output to the output buffer and resets the
- * converter to its initial state.
- *
- * @param converterHandle Address of converter object created by the native code
- * @param output char array to receive flushed output.
- * @param outEnd stop writing to output array at this offset (exclusive).
- * @return int error code returned by ICU
- * @param data integer array containing the following data
- * data[0] = inputOffset
- * data[1] = outputOffset
- * @internal ICU 2.4
- */
- public static native int flushByteToChar(long converterHandle, char[] output, int outEnd, int[] data);
-
public static native long openConverter(String encoding);
public static native void closeConverter(long converterHandle);
@@ -129,9 +58,9 @@
return setCallbackDecode(converterHandle,
translateCodingErrorAction(decoder.malformedInputAction()),
translateCodingErrorAction(decoder.unmappableCharacterAction()),
- decoder.replacement().toCharArray());
+ decoder.replacement());
}
- private static native int setCallbackDecode(long converterHandle, int onMalformedInput, int onUnmappableInput, char[] subChars);
+ private static native int setCallbackDecode(long converterHandle, int onMalformedInput, int onUnmappableInput, String subChars);
public static int setCallbackEncode(long converterHandle, CharsetEncoder encoder) {
return setCallbackEncode(converterHandle,
diff --git a/luni/src/main/java/libcore/icu/TimeZones.java b/luni/src/main/java/libcore/icu/TimeZones.java
index 1b5de15..6479aeb 100644
--- a/luni/src/main/java/libcore/icu/TimeZones.java
+++ b/luni/src/main/java/libcore/icu/TimeZones.java
@@ -16,10 +16,13 @@
package libcore.icu;
+import java.util.Arrays;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
+import libcore.util.BasicLruCache;
/**
* Provides access to ICU's time zone data.
@@ -27,129 +30,92 @@
public final class TimeZones {
private static final String[] availableTimeZones = TimeZone.getAvailableIDs();
+ private static final ZoneStringsCache cachedZoneStrings = new ZoneStringsCache();
+ static {
+ // Ensure that we pull in the zone strings for en_US and the user's default locale.
+ // (All devices must support Locale.US, and it's used for things like HTTP headers.)
+ // This is especially useful on Android because we'll share this via the Zygote.
+ cachedZoneStrings.get(Locale.US);
+ cachedZoneStrings.get(Locale.getDefault());
+ }
+
+ public static class ZoneStringsCache extends BasicLruCache<Locale, String[][]> {
+ // De-duplicate the strings (http://b/2672057).
+ private final HashMap<String, String> internTable = new HashMap<String, String>();
+
+ public ZoneStringsCache() {
+ // We make room for all the time zones known to the system, since each set of strings
+ // isn't particularly large (and we remove duplicates), but is currently (Honeycomb)
+ // really expensive to compute.
+ // If you change this, you might want to change the scope of the intern table too.
+ super(availableTimeZones.length);
+ }
+
+ @Override protected String[][] create(Locale locale) {
+ long start, nativeStart;
+ start = nativeStart = System.currentTimeMillis();
+ String[][] result = getZoneStringsImpl(locale.toString(), availableTimeZones);
+ long nativeEnd = System.currentTimeMillis();
+ internStrings(result);
+ // Ending up in this method too often is an easy way to make your app slow, so we ensure
+ // it's easy to tell from the log (a) what we were doing, (b) how long it took, and
+ // (c) that it's all ICU's fault.
+ long end = System.currentTimeMillis();
+ long duration = end - start;
+ long nativeDuration = nativeEnd - nativeStart;
+ Logger.global.info("Loaded time zone names for " + locale + " in " + duration + "ms" +
+ " (" + nativeDuration + "ms in ICU).");
+ return result;
+ }
+
+ private synchronized void internStrings(String[][] result) {
+ for (int i = 0; i < result.length; ++i) {
+ for (int j = 1; j <= 4; ++j) {
+ String original = result[i][j];
+ String nonDuplicate = internTable.get(original);
+ if (nonDuplicate == null) {
+ internTable.put(original, original);
+ } else {
+ result[i][j] = nonDuplicate;
+ }
+ }
+ }
+ }
+ }
+
+ private static final Comparator<String[]> ZONE_STRINGS_COMPARATOR = new Comparator<String[]>() {
+ public int compare(String[] lhs, String[] rhs) {
+ return lhs[0].compareTo(rhs[0]);
+ }
+ };
+
private TimeZones() {}
/**
- * Implements TimeZone.getDisplayName by asking ICU.
+ * Returns the appropriate string from 'zoneStrings'. Used with getZoneStrings.
*/
- public static String getDisplayName(String id, boolean daylight, int style, Locale locale) {
- // If we already have the strings, linear search through them is 10x quicker than
- // calling ICU for just the one we want.
- if (CachedTimeZones.locale.equals(locale)) {
- String result = lookupDisplayName(CachedTimeZones.names, id, daylight, style);
- if (result != null) {
- return result;
- }
- }
- return getDisplayNameImpl(id, daylight, style, locale.toString());
- }
-
- public static String lookupDisplayName(String[][] zoneStrings, String id, boolean daylight, int style) {
- for (String[] row : zoneStrings) {
- if (row[0].equals(id)) {
- if (daylight) {
- return (style == TimeZone.LONG) ? row[3] : row[4];
- } else {
- return (style == TimeZone.LONG) ? row[1] : row[2];
- }
+ public static String getDisplayName(String[][] zoneStrings, String id, boolean daylight, int style) {
+ String[] needle = new String[] { id };
+ int index = Arrays.binarySearch(zoneStrings, needle, ZONE_STRINGS_COMPARATOR);
+ if (index >= 0) {
+ String[] row = zoneStrings[index];
+ if (daylight) {
+ return (style == TimeZone.LONG) ? row[3] : row[4];
+ } else {
+ return (style == TimeZone.LONG) ? row[1] : row[2];
}
}
return null;
}
/**
- * Initialization holder for default time zone names. This class will
- * be preloaded by the zygote to share the time and space costs of setting
- * up the list of time zone names, so although it looks like the lazy
- * initialization idiom, it's actually the opposite.
- */
- private static class CachedTimeZones {
- /**
- * Name of default locale at the time this class was initialized.
- */
- private static final Locale locale = Locale.getDefault();
-
- /**
- * Names of time zones for the default locale.
- */
- private static final String[][] names = createZoneStringsFor(locale);
- }
-
- /**
- * Creates array of time zone names for the given locale.
- * This method takes about 2s to run on a 400MHz ARM11.
- */
- private static String[][] createZoneStringsFor(Locale locale) {
- long start = System.currentTimeMillis();
-
- /*
- * The following code is optimized for fast native response (the time a
- * method call can be in native code is limited). It prepares an empty
- * array to keep native code from having to create new Java objects. It
- * also fill in the time zone IDs to speed things up a bit. There's one
- * array for each time zone name type. (standard/long, standard/short,
- * daylight/long, daylight/short) The native method that fetches these
- * strings is faster if it can do all entries of one type, before having
- * to change to the next type. That's why the array passed down to
- * native has 5 entries, each providing space for all time zone names of
- * one type. Likely this access to the fields is much faster in the
- * native code because there's less array access overhead.
- */
- String[][] arrayToFill = new String[5][];
- arrayToFill[0] = availableTimeZones.clone();
- arrayToFill[1] = new String[availableTimeZones.length];
- arrayToFill[2] = new String[availableTimeZones.length];
- arrayToFill[3] = new String[availableTimeZones.length];
- arrayToFill[4] = new String[availableTimeZones.length];
-
- // Don't be distracted by all the code either side of this line: this is the expensive bit!
- getZoneStringsImpl(arrayToFill, locale.toString());
-
- // Reorder the entries so we get the expected result.
- // We also take the opportunity to de-duplicate the names (http://b/2672057).
- HashMap<String, String> internTable = new HashMap<String, String>();
- String[][] result = new String[availableTimeZones.length][5];
- for (int i = 0; i < availableTimeZones.length; ++i) {
- result[i][0] = arrayToFill[0][i];
- for (int j = 1; j <= 4; ++j) {
- String original = arrayToFill[j][i];
- String nonDuplicate = internTable.get(original);
- if (nonDuplicate == null) {
- internTable.put(original, original);
- nonDuplicate = original;
- }
- result[i][j] = nonDuplicate;
- }
- }
-
- long duration = System.currentTimeMillis() - start;
- Logger.global.info("Loaded time zone names for " + locale + " in " + duration + "ms.");
-
- return result;
- }
-
- /**
* Returns an array of time zone strings, as used by DateFormatSymbols.getZoneStrings.
*/
public static String[][] getZoneStrings(Locale locale) {
if (locale == null) {
locale = Locale.getDefault();
}
-
- // TODO: We should force a reboot if the default locale changes.
- if (CachedTimeZones.locale.equals(locale)) {
- return clone2dStringArray(CachedTimeZones.names);
- }
-
- return createZoneStringsFor(locale);
- }
-
- public static String[][] clone2dStringArray(String[][] array) {
- String[][] result = new String[array.length][];
- for (int i = 0; i < array.length; ++i) {
- result[i] = array[i].clone();
- }
- return result;
+ return cachedZoneStrings.get(locale);
}
/**
@@ -162,6 +128,5 @@
}
private static native String[] forCountryCode(String countryCode);
- private static native void getZoneStringsImpl(String[][] arrayToFill, String locale);
- private static native String getDisplayNameImpl(String id, boolean isDST, int style, String locale);
+ private static native String[][] getZoneStringsImpl(String locale, String[] timeZoneIds);
}
diff --git a/luni/src/main/java/libcore/net/MimeUtils.java b/luni/src/main/java/libcore/net/MimeUtils.java
index 28d9c7c..67dfdf9 100644
--- a/luni/src/main/java/libcore/net/MimeUtils.java
+++ b/luni/src/main/java/libcore/net/MimeUtils.java
@@ -20,7 +20,6 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
@@ -369,6 +368,31 @@
extensionToMimeTypeMap.put(extension, mimeType);
}
+ private static InputStream getContentTypesPropertiesStream() {
+ // User override?
+ String userTable = System.getProperty("content.types.user.table");
+ if (userTable != null) {
+ File f = new File(userTable);
+ if (f.exists()) {
+ try {
+ return new FileInputStream(f);
+ } catch (IOException ignored) {
+ }
+ }
+ }
+
+ // Standard location?
+ File f = new File(System.getProperty("java.home"), "lib" + File.separator + "content-types.properties");
+ if (f.exists()) {
+ try {
+ return new FileInputStream(f);
+ } catch (IOException ignored) {
+ }
+ }
+
+ return null;
+ }
+
/**
* This isn't what the RI does. The RI doesn't have hard-coded defaults, so supplying your
* own "content.types.user.table" means you don't get any of the built-ins, and the built-ins
@@ -376,34 +400,7 @@
*/
private static void applyOverrides() {
// Get the appropriate InputStream to read overrides from, if any.
- InputStream stream = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
- public InputStream run() {
- // User override?
- String userTable = System.getProperty("content.types.user.table");
- if (userTable != null) {
- File f = new File(userTable);
- if (f.exists()) {
- try {
- return new FileInputStream(f);
- } catch (IOException ignored) {
- }
- }
- }
-
- // Standard location?
- File f = new File(System.getProperty("java.home"),
- "lib" + File.separator + "content-types.properties");
- if (f.exists()) {
- try {
- return new FileInputStream(f);
- } catch (IOException ignored) {
- }
- }
-
- return null;
- }
- });
-
+ InputStream stream = getContentTypesPropertiesStream();
if (stream == null) {
return;
}
diff --git a/luni/src/main/java/libcore/net/UriCodec.java b/luni/src/main/java/libcore/net/UriCodec.java
new file mode 100644
index 0000000..46a93b8
--- /dev/null
+++ b/luni/src/main/java/libcore/net/UriCodec.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 libcore.net;
+
+import java.io.ByteArrayOutputStream;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.nio.charset.Charsets;
+
+/**
+ * Encodes and decodes {@code application/x-www-form-urlencoded} content.
+ * Subclasses define exactly which characters are legal.
+ *
+ * <p>By default, UTF-8 is used to encode escaped characters. A single input
+ * character like "\u0080" may be encoded to multiple octets like %C2%80.
+ */
+public abstract class UriCodec {
+
+ /**
+ * Returns true if {@code c} does not need to be escaped.
+ */
+ protected abstract boolean isRetained(char c);
+
+ /**
+ * Throws if {@code s} is invalid according to this encoder.
+ */
+ public void validate(String s) throws URISyntaxException {
+ for (int i = 0; i < s.length();) {
+ char ch = s.charAt(i);
+ if ((ch >= 'a' && ch <= 'z')
+ || (ch >= 'A' && ch <= 'Z')
+ || (ch >= '0' && ch <= '9')
+ || isRetained(ch)) {
+ i++;
+ } else if (ch == '%') {
+ if (i + 2 >= s.length()) {
+ throw new URISyntaxException(s, "Incomplete % sequence", i);
+ }
+ int d1 = hexToInt(s.charAt(i + 1));
+ int d2 = hexToInt(s.charAt(i + 2));
+ if (d1 == -1 || d2 == -1) {
+ throw new URISyntaxException(s, "Invalid % sequence: " +
+ s.substring(i, i + 3), i);
+ }
+ i += 3;
+ } else {
+ throw new URISyntaxException(s, "Illegal character", i);
+ }
+ }
+ }
+
+ /**
+ * Throws if {@code s} contains characters that are not letters, digits or
+ * in {@code legal}.
+ */
+ public static void validateSimple(String s, String legal) throws URISyntaxException {
+ for (int i = 0; i < s.length(); i++) {
+ char ch = s.charAt(i);
+ if (!((ch >= 'a' && ch <= 'z')
+ || (ch >= 'A' && ch <= 'Z')
+ || (ch >= '0' && ch <= '9')
+ || legal.indexOf(ch) > -1)) {
+ throw new URISyntaxException(s, "Illegal character", i);
+ }
+ }
+ }
+
+ /**
+ * Encodes {@code s} and appends the result to {@code builder}.
+ *
+ * @param isPartiallyEncoded true to fix input that has already been
+ * partially or fully encoded. For example, input of "hello%20world" is
+ * unchanged with isPartiallyEncoded=true but would be double-escaped to
+ * "hello%2520world" otherwise.
+ */
+ private void appendEncoded(StringBuilder builder, String s, Charset charset,
+ boolean isPartiallyEncoded) {
+ if (s == null) {
+ throw new NullPointerException();
+ }
+
+ int escapeStart = -1;
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if ((c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9')
+ || isRetained(c)
+ || (c == '%' && isPartiallyEncoded)) {
+ if (escapeStart != -1) {
+ appendHex(builder, s.substring(escapeStart, i), charset);
+ escapeStart = -1;
+ }
+ if (c == '%' && isPartiallyEncoded) {
+ // this is an encoded 3-character sequence like "%20"
+ builder.append(s, i, i + 3);
+ i += 2;
+ } else if (c == ' ') {
+ builder.append('+');
+ } else {
+ builder.append(c);
+ }
+ } else if (escapeStart == -1) {
+ escapeStart = i;
+ }
+ }
+ if (escapeStart != -1) {
+ appendHex(builder, s.substring(escapeStart, s.length()), charset);
+ }
+ }
+
+ public String encode(String s, Charset charset) {
+ // Guess a bit larger for encoded form
+ StringBuilder builder = new StringBuilder(s.length() + 16);
+ appendEncoded(builder, s, charset, false);
+ return builder.toString();
+ }
+
+ public void appendEncoded(StringBuilder builder, String s) {
+ appendEncoded(builder, s, Charsets.UTF_8, false);
+ }
+
+ public void appendPartiallyEncoded(StringBuilder builder, String s) {
+ appendEncoded(builder, s, Charsets.UTF_8, true);
+ }
+
+ /**
+ * @param convertPlus true to convert '+' to ' '.
+ */
+ public static String decode(String s, boolean convertPlus, Charset charset) {
+ if (s.indexOf('%') == -1 && (!convertPlus || s.indexOf('+') == -1)) {
+ return s;
+ }
+
+ StringBuilder result = new StringBuilder(s.length());
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ for (int i = 0; i < s.length();) {
+ char c = s.charAt(i);
+ if (c == '%') {
+ do {
+ if (i + 2 >= s.length()) {
+ throw new IllegalArgumentException("Incomplete % sequence at: " + i);
+ }
+ int d1 = hexToInt(s.charAt(i + 1));
+ int d2 = hexToInt(s.charAt(i + 2));
+ if (d1 == -1 || d2 == -1) {
+ throw new IllegalArgumentException("Invalid % sequence " +
+ s.substring(i, i + 3) + " at " + i);
+ }
+ out.write((byte) ((d1 << 4) + d2));
+ i += 3;
+ } while (i < s.length() && s.charAt(i) == '%');
+ result.append(new String(out.toByteArray(), charset));
+ out.reset();
+ } else {
+ if (convertPlus && c == '+') {
+ c = ' ';
+ }
+ result.append(c);
+ i++;
+ }
+ }
+ return result.toString();
+ }
+
+ /**
+ * Like {@link Character#digit}, but without support for non-ASCII
+ * characters.
+ */
+ private static int hexToInt(char c) {
+ if ('0' <= c && c <= '9') {
+ return c - '0';
+ } else if ('a' <= c && c <= 'f') {
+ return 10 + (c - 'a');
+ } else if ('A' <= c && c <= 'F') {
+ return 10 + (c - 'A');
+ } else {
+ return -1;
+ }
+ }
+
+ public static String decode(String s) {
+ return decode(s, false, Charsets.UTF_8);
+ }
+
+ private static void appendHex(StringBuilder builder, String s, Charset charset) {
+ for (byte b : s.getBytes(charset)) {
+ appendHex(builder, b);
+ }
+ }
+
+ private static void appendHex(StringBuilder sb, byte b) {
+ sb.append('%');
+ sb.append(Byte.toHexString(b, true));
+ }
+}
diff --git a/luni/src/main/java/org/apache/harmony/archive/util/Util.java b/luni/src/main/java/org/apache/harmony/archive/util/Util.java
deleted file mode 100644
index 0875540..0000000
--- a/luni/src/main/java/org/apache/harmony/archive/util/Util.java
+++ /dev/null
@@ -1,129 +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.util;
-
-/**
- * Helpers for the archive module.
- */
-public class Util {
-
- /**
- * Returns whether the given source string ends with the suffix, ignoring
- * case and assuming that the strings are ascii encoded.
- *
- * @param source
- * the string to match.
- * @param suffix
- * the suffix to test.
- * @return {@code true} if the source does end with the given suffix, or
- * {@code false} if not.
- */
- public static boolean asciiEndsWithIgnoreCase(String source, String suffix) {
- int length = suffix.length();
- if (length > source.length()) {
- return false;
- }
- int offset = source.length() - length;
- for (int i = 0; i < length; i++) {
- char c1 = source.charAt(i + offset);
- char c2 = suffix.charAt(i);
- if (c1 != c2 && toASCIIUpperCase(c1) != toASCIIUpperCase(c2)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Compares the given byte arrays and returns whether they are equal,
- * ignoring case differences and assuming they are ascii-encoded strings.
- *
- * @param buf1
- * first byte array to compare.
- * @param buf2
- * second byte array to compare.
- * @return the result of the comparison.
- */
- public static boolean asciiEqualsIgnoreCase(byte[] buf1, byte[] buf2) {
- if (buf1 == null || buf2 == null) {
- return false;
- }
- if (buf1 == buf2) {
- return true;
- }
- if (buf1.length != buf2.length) {
- return false;
- }
-
- for (int i = 0; i < buf1.length; i++) {
- byte b1 = buf1[i];
- byte b2 = buf2[i];
- if (b1 != b2 && toASCIIUpperCase(b1) != toASCIIUpperCase(b2)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Compares the given strings and returns whether they are equal, ignoring
- * case differences and assuming they are ascii-encoded strings.
- *
- * @param s1
- * first string to compare.
- * @param s2
- * second string to compare.
- * @return the result of the comparison.
- */
- public static boolean asciiEqualsIgnoreCase(String s1, String s2) {
- if (s1 == null || s2 == null) {
- return false;
- }
- if (s1 == s2) {
- return true;
- }
-
- int length = s1.length();
- if (length != s2.length()) {
- return false;
- }
-
- for (int i = 0; i < length; i++) {
- char c1 = s1.charAt(i);
- char c2 = s2.charAt(i);
- if (c1 != c2 && toASCIIUpperCase(c1) != toASCIIUpperCase(c2)) {
- return false;
- }
- }
- return true;
- }
-
- private static final byte toASCIIUpperCase(byte b) {
- if ('a' <= b && b <= 'z') {
- return (byte) (b - ('a' - 'A'));
- }
- return b;
- }
-
- private static final char toASCIIUpperCase(char c) {
- if ('a' <= c && c <= 'z') {
- return (char) (c - ('a' - 'A'));
- }
- return c;
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/kernel/vm/VM.java b/luni/src/main/java/org/apache/harmony/kernel/vm/VM.java
index 2e2ccc0..3f45408 100644
--- a/luni/src/main/java/org/apache/harmony/kernel/vm/VM.java
+++ b/luni/src/main/java/org/apache/harmony/kernel/vm/VM.java
@@ -81,7 +81,7 @@
* @param loader ClassLoader the ClassLoader instance
* @param bootLoader boolean true for the bootstrap class loader
*/
- public final static void initializeClassLoader(ClassLoader loader, boolean bootLoader) {
+ public static final void initializeClassLoader(ClassLoader loader, boolean bootLoader) {
return;
};
diff --git a/luni/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java b/luni/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java
index 45a6c75..69237c0 100644
--- a/luni/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java
+++ b/luni/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java
@@ -25,8 +25,6 @@
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -215,14 +213,7 @@
}
try {
if (!el.definingMethod.isAccessible()) {
- AccessController.doPrivileged(new PrivilegedAction<Object>(){
- public Object run() {
- try {
- el.definingMethod.setAccessible(true);
- } catch (Exception ignore) {}
- return null;
- }
- });
+ el.definingMethod.setAccessible(true);
}
Object otherValue = el.definingMethod.invoke(obj);
if (otherValue != null ) {
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 3fb49fd..f591132 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
@@ -26,9 +26,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
+import libcore.net.UriCodec;
import java.net.URL;
import java.net.URLConnection;
-import org.apache.harmony.luni.util.Util;
/**
* This subclass extends <code>URLConnection</code>.
@@ -60,7 +60,7 @@
if (fileName == null) {
fileName = "";
}
- fileName = Util.decode(fileName, false);
+ fileName = UriCodec.decode(fileName);
}
/**
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnectionPool.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnectionPool.java
index bb5e6e1..801645c 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnectionPool.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnectionPool.java
@@ -35,9 +35,6 @@
* <p>This class <i>doesn't</i> adjust its configuration as system properties
* are changed. This assumes that the applications that set these parameters do
* so before making HTTP connections, and that this class is initialized lazily.
- *
- * <p>If a security manager is in place, HTTP connection pooling will be
- * disabled and these system properties will be ignored.
*/
public final class HttpConnectionPool {
@@ -48,12 +45,6 @@
= new HashMap<HttpConnection.Address, List<HttpConnection>>();
private HttpConnectionPool() {
- SecurityManager security = System.getSecurityManager();
- if (security != null) {
- maxConnections = 0;
- return;
- }
-
String keepAlive = System.getProperty("http.keepAlive");
if (keepAlive != null && !Boolean.parseBoolean(keepAlive)) {
maxConnections = 0;
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 1d2eacd..d9976bc 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
@@ -40,9 +40,7 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charsets;
-import java.security.AccessController;
import java.security.Permission;
-import java.security.PrivilegedAction;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@@ -52,7 +50,6 @@
import java.util.zip.GZIPInputStream;
import libcore.io.Streams;
import org.apache.harmony.luni.util.Base64;
-import org.apache.harmony.luni.util.PriviAction;
/**
* This subclass extends <code>HttpURLConnection</code> which in turns extends
@@ -187,12 +184,7 @@
super(url);
defaultPort = port;
requestHeader = new HttpHeaders(defaultRequestHeader);
-
- responseCache = AccessController.doPrivileged(new PrivilegedAction<ResponseCache>() {
- public ResponseCache run() {
- return ResponseCache.getDefault();
- }
- });
+ responseCache = ResponseCache.getDefault();
}
/**
@@ -906,8 +898,8 @@
}
private String getDefaultUserAgent() {
- String agent = getSystemProperty("http.agent");
- return agent != null ? agent : ("Java" + getSystemProperty("java.version"));
+ String agent = System.getProperty("http.agent");
+ return agent != null ? agent : ("Java" + System.getProperty("java.version"));
}
private boolean hasConnectionCloseHeader() {
@@ -1002,10 +994,6 @@
: url.getHost();
}
- private String getSystemProperty(final String property) {
- return AccessController.doPrivileged(new PriviAction<String>(property));
- }
-
@Override public final boolean usingProxy() {
return (proxy != null && proxy.type() != Proxy.Type.DIRECT);
}
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 9864350..1e01a34 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
@@ -27,10 +27,9 @@
import java.net.ContentHandlerFactory;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
+import libcore.net.UriCodec;
import java.net.URL;
-import java.security.AccessController;
import java.security.Permission;
-import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -38,7 +37,6 @@
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipFile;
-import org.apache.harmony.luni.util.Util;
/**
* This subclass extends {@code URLConnection}.
@@ -136,54 +134,43 @@
}
}
- @SuppressWarnings("nls")
JarFile openJarFile() throws IOException {
- JarFile jar = null;
if (jarFileURL.getProtocol().equals("file")) {
- jar = new JarFile(new File(Util.decode(jarFileURL.getFile(), false,
- "UTF-8")), true, ZipFile.OPEN_READ);
+ String decodedFile = UriCodec.decode(jarFileURL.getFile());
+ return new JarFile(new File(decodedFile), true, ZipFile.OPEN_READ);
} else {
final InputStream is = jarFileURL.openConnection().getInputStream();
try {
- jar = AccessController
- .doPrivileged(new PrivilegedAction<JarFile>() {
- public JarFile run() {
- FileOutputStream fos = null;
- JarFile result = null;
- try {
- File tempJar = File.createTempFile("hyjar_", ".tmp", null);
- tempJar.deleteOnExit();
- fos = new FileOutputStream(tempJar);
- byte[] buf = new byte[4096];
- int nbytes = 0;
- while ((nbytes = is.read(buf)) > -1) {
- fos.write(buf, 0, nbytes);
- }
- fos.close();
- result = new JarFile(tempJar, true,
- ZipFile.OPEN_READ | ZipFile.OPEN_DELETE);
- } catch (IOException e) {
- return null;
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException ex) {
- result = null;
- }
- }
- }
- return result;
- }
- });
+ FileOutputStream fos = null;
+ JarFile result = null;
+ try {
+ File tempJar = File.createTempFile("hyjar_", ".tmp", null);
+ tempJar.deleteOnExit();
+ fos = new FileOutputStream(tempJar);
+ byte[] buf = new byte[4096];
+ int nbytes = 0;
+ while ((nbytes = is.read(buf)) > -1) {
+ fos.write(buf, 0, nbytes);
+ }
+ fos.close();
+ return new JarFile(tempJar, true, ZipFile.OPEN_READ | ZipFile.OPEN_DELETE);
+ } catch (IOException e) {
+ return null;
+ } finally {
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (IOException ex) {
+ return null;
+ }
+ }
+ }
} finally {
if (is != null) {
is.close();
}
}
}
-
- return jar;
}
/**
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 e22740e..a8b0691 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
@@ -44,7 +44,7 @@
private static final int SO_BROADCAST = 32;
- final static int IP_MULTICAST_TTL = 17;
+ private static final int IP_MULTICAST_TTL = 17;
private volatile boolean isNativeConnected;
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 4952cf6..75dd4cd 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
@@ -33,8 +33,6 @@
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.OSMemory;
import org.apache.harmony.luni.platform.Platform;
@@ -120,18 +118,14 @@
* gets SocketImpl field by reflection.
*/
private Field getSocketImplField(final String fieldName) {
- return AccessController.doPrivileged(new PrivilegedAction<Field>() {
- public Field run() {
- Field field = null;
- try {
- field = SocketImpl.class.getDeclaredField(fieldName);
- field.setAccessible(true);
- } catch (NoSuchFieldException e) {
- throw new Error(e);
- }
- return field;
- }
- });
+ Field field = null;
+ try {
+ field = SocketImpl.class.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ } catch (NoSuchFieldException e) {
+ throw new AssertionError(e);
+ }
+ return field;
}
public void initLocalPort(int localPort) {
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 46a8b0e..2fcef68 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
@@ -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.FileDescriptor;
@@ -105,12 +101,6 @@
public long transfer(int fileHandler, FileDescriptor socketDescriptor,
long offset, long count) throws IOException;
- // BEGIN android-deleted
- // public long ttyAvailable() throws IOException;
- // public long ttyRead(byte[] bytes, int offset, int length) throws IOException;
- // END android-deleted
-
- // BEGIN android-added
public int ioctlAvailable(FileDescriptor fileDescriptor) throws IOException;
public static class SeekPipeException extends IOException {
@@ -118,6 +108,5 @@
super(message);
}
}
- // END android-added
}
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 682ec3a..c073c41 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
@@ -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.FileDescriptor;
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/OSFileSystem.java b/luni/src/main/java/org/apache/harmony/luni/platform/OSFileSystem.java
index 254cf74..03b3352 100644
--- a/luni/src/main/java/org/apache/harmony/luni/platform/OSFileSystem.java
+++ b/luni/src/main/java/org/apache/harmony/luni/platform/OSFileSystem.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.FileDescriptor;
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java b/luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java
index ac3275e..8fa04fd 100644
--- a/luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java
+++ b/luni/src/main/java/org/apache/harmony/luni/util/DeleteOnExit.java
@@ -22,7 +22,6 @@
import java.util.ArrayList;
import java.util.Collections;
-// BEGIN android-changed
/**
* Implements the actual DeleteOnExit mechanism. Is registered as a shutdown
* hook in the Runtime, once it is actually being used.
@@ -77,4 +76,3 @@
}
}
}
-// END android-changed
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 1feb323..e08e560 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
@@ -26,15 +26,18 @@
private static final class StringExponentPair {
String s;
-
- int e;
-
+ long e;
boolean negative;
- StringExponentPair(String s, int e, boolean negative) {
- this.s = s;
- this.e = e;
- this.negative = negative;
+ // Flags for two special non-error failure cases.
+ boolean infinity;
+ boolean zero;
+
+ public float specialValue() {
+ if (infinity) {
+ return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
+ }
+ return negative ? -0.0f : 0.0f;
}
}
@@ -43,16 +46,7 @@
* 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
+ * exponent. Returns the closest double value to the real number, or Double.longBitsToDouble(-1).
*/
private static native double parseDblImpl(String s, int e);
@@ -61,16 +55,7 @@
* 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
+ * exponent. Returns the closest float value to the real number, or Float.intBitsToFloat(-1).
*/
private static native float parseFltImpl(String s, int e);
@@ -79,33 +64,22 @@
}
/**
- * Takes a String and does some initial parsing. Should return a
- * StringExponentPair containing a String with no leading or trailing white
+ * Returns 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;
-
- start = 0;
+ StringExponentPair result = new StringExponentPair();
if (length == 0) {
throw invalidReal(s, isDouble);
}
- c = s.charAt(length - 1);
+ result.negative = (s.charAt(0) == '-');
+
+ // We ignore trailing double or float indicators; the method you called determines
+ // what you'll get.
+ char c = s.charAt(length - 1);
if (c == 'D' || c == 'd' || c == 'F' || c == 'f') {
length--;
if (length == 0) {
@@ -113,28 +87,49 @@
}
}
- end = Math.max(s.indexOf('E'), s.indexOf('e'));
- if (end > -1) {
+ int end = Math.max(s.indexOf('E'), s.indexOf('e'));
+ if (end != -1) {
+ // Is there anything after the 'e'?
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 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);
+ // Do we have an optional explicit sign?
+ int exponentOffset = end + 1;
+ boolean negativeExponent = false;
+ char firstExponentChar = s.charAt(exponentOffset);
+ if (firstExponentChar == '+' || firstExponentChar == '-') {
+ negativeExponent = (firstExponentChar == '-');
+ ++exponentOffset;
}
+ // Do we have a valid positive integer?
+ String exponentString = s.substring(exponentOffset, length);
+ if (exponentString.isEmpty()) {
+ throw invalidReal(s, isDouble);
+ }
+ for (int i = 0; i < exponentString.length(); ++i) {
+ char ch = exponentString.charAt(i);
+ if (ch < '0' || ch > '9') {
+ throw invalidReal(s, isDouble);
+ }
+ }
+
+ // Parse the integer exponent.
+ try {
+ result.e = Integer.parseInt(exponentString);
+ if (negativeExponent) {
+ result.e = -result.e;
+ }
+ } catch (NumberFormatException ex) {
+ // We already checked the string, so the exponent must have been out of range for an int.
+ if (negativeExponent) {
+ result.zero = true;
+ } else {
+ result.infinity = true;
+ }
+ return result;
+ }
} else {
end = length;
}
@@ -142,11 +137,12 @@
throw invalidReal(s, isDouble);
}
+ int start = 0;
c = s.charAt(start);
if (c == '-') {
++start;
--length;
- negative = true;
+ result.negative = true;
} else if (c == '+') {
++start;
--length;
@@ -155,9 +151,9 @@
throw invalidReal(s, isDouble);
}
- decimal = s.indexOf('.');
+ int decimal = s.indexOf('.');
if (decimal > -1) {
- e -= end - decimal - 1;
+ result.e -= end - decimal - 1;
s = s.substring(start, decimal) + s.substring(decimal + 1, end);
} else {
s = s.substring(start, end);
@@ -178,84 +174,60 @@
}
if (end != length || start != 0) {
- e += length - end;
+ result.e += length - end;
s = s.substring(start, end);
}
+ // This is a hack for https://issues.apache.org/jira/browse/HARMONY-329
// Trim the length of very small numbers, natives can only handle down
// to E-309
final int APPROX_MIN_MAGNITUDE = -359;
final int MAX_DIGITS = 52;
length = s.length();
- if (length > MAX_DIGITS && e < APPROX_MIN_MAGNITUDE) {
- int d = Math.min(APPROX_MIN_MAGNITUDE - e, length - 1);
+ if (length > MAX_DIGITS && result.e < APPROX_MIN_MAGNITUDE) {
+ int d = Math.min(APPROX_MIN_MAGNITUDE - (int) result.e, length - 1);
s = s.substring(0, length - d);
- e += d;
+ result.e += d;
}
- return new StringExponentPair(s, e, negative);
+ // This is a hack for https://issues.apache.org/jira/browse/HARMONY-6641
+ // The magic 1024 was determined experimentally; the more plausible -324 and +309 were
+ // not sufficient to pass both our tests and harmony's tests.
+ if (result.e < -1024) {
+ result.zero = true;
+ return result;
+ } else if (result.e > 1024) {
+ result.infinity = true;
+ return result;
+ }
+
+ result.s = s;
+ return result;
}
- /*
- * 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);
- }
-
+ // Parses "+Nan", "NaN", "-Nan", "+Infinity", "Infinity", and "-Infinity", case-insensitively.
+ private static float parseName(String name, boolean isDouble) {
+ // Explicit sign?
boolean negative = false;
int i = 0;
- char firstChar = namedDouble.charAt(i);
+ int length = name.length();
+ char firstChar = name.charAt(i);
if (firstChar == '-') {
negative = true;
++i;
+ --length;
} else if (firstChar == '+') {
++i;
+ --length;
}
- if (namedDouble.regionMatches(false, i, "Infinity", 0, 8)) {
- return negative ? Double.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
- }
-
- if (namedDouble.regionMatches(false, i, "NaN", 0, 3)) {
- return Double.NaN;
- }
-
- 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 invalidReal(namedFloat, false);
- }
-
- boolean negative = false;
- int i = 0;
- char firstChar = namedFloat.charAt(i);
- if (firstChar == '-') {
- negative = true;
- ++i;
- } else if (firstChar == '+') {
- ++i;
- }
-
- if (namedFloat.regionMatches(false, i, "Infinity", 0, 8)) {
+ if (length == 8 && name.regionMatches(false, i, "Infinity", 0, 8)) {
return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
}
-
- if (namedFloat.regionMatches(false, i, "NaN", 0, 3)) {
+ if (length == 3 && name.regionMatches(false, i, "NaN", 0, 3)) {
return Float.NaN;
}
-
- throw invalidReal(namedFloat, false);
+ throw invalidReal(name, isDouble);
}
/**
@@ -278,25 +250,25 @@
// See if this could be a named double
char last = s.charAt(length - 1);
- if ((last == 'y') || (last == 'N')) {
- return parseDblName(s, length);
+ if (last == 'y' || last == 'N') {
+ return parseName(s, true);
}
- // See if it could be a hexadecimal representation
- if (s.toLowerCase().indexOf("0x") != -1) {
+ // See if it could be a hexadecimal representation.
+ // We don't use startsWith because there might be a leading sign.
+ if (s.indexOf("0x") != -1 || s.indexOf("0X") != -1) {
return HexStringParser.parseDouble(s);
}
StringExponentPair info = initialParse(s, length, true);
-
- double result = parseDblImpl(info.s, info.e);
+ if (info.infinity || info.zero) {
+ return info.specialValue();
+ }
+ double result = parseDblImpl(info.s, (int) info.e);
if (Double.doubleToRawLongBits(result) == 0xffffffffffffffffL) {
throw invalidReal(s, true);
}
- if (info.negative) {
- result = -result;
- }
- return result;
+ return info.negative ? -result : result;
}
/**
@@ -319,23 +291,24 @@
// See if this could be a named float
char last = s.charAt(length - 1);
- if ((last == 'y') || (last == 'N')) {
- return parseFltName(s, length);
+ if (last == 'y' || last == 'N') {
+ return parseName(s, false);
}
// See if it could be a hexadecimal representation
- if (s.toLowerCase().indexOf("0x") != -1) {
+ // We don't use startsWith because there might be a leading sign.
+ if (s.indexOf("0x") != -1 || s.indexOf("0X") != -1) {
return HexStringParser.parseFloat(s);
}
StringExponentPair info = initialParse(s, length, false);
- float result = parseFltImpl(info.s, info.e);
+ if (info.infinity || info.zero) {
+ return info.specialValue();
+ }
+ float result = parseFltImpl(info.s, (int) info.e);
if (Float.floatToRawIntBits(result) == 0xffffffff) {
throw invalidReal(s, false);
}
- if (info.negative) {
- result = -result;
- }
- return result;
+ return info.negative ? -result : result;
}
}
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/PriviAction.java b/luni/src/main/java/org/apache/harmony/luni/util/PriviAction.java
deleted file mode 100644
index 9a12825..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/util/PriviAction.java
+++ /dev/null
@@ -1,139 +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.reflect.AccessibleObject;
-import java.security.Policy;
-import java.security.PrivilegedAction;
-import java.security.Security;
-
-/**
- * Helper class to avoid multiple anonymous inner class for
- * <code>{@link java.security.AccessController#doPrivileged(PrivilegedAction)}</code>
- * calls.
- */
-public class PriviAction<T> implements PrivilegedAction<T> {
-
- private Object arg1;
-
- private Object arg2;
-
- private int action;
-
- private static final int GET_SYSTEM_PROPERTY = 1;
-
- private static final int GET_SECURITY_POLICY = 2;
-
- private static final int SET_ACCESSIBLE = 3;
-
- private static final int GET_SECURITY_PROPERTY = 4;
-
- /**
- * Creates a PrivilegedAction to get the security property with the given
- * name.
- *
- * @param property
- * the name of the property
- *
- * @see Security#getProperty
- */
- public static PrivilegedAction<String> getSecurityProperty(String property) {
- return new PriviAction<String>(GET_SECURITY_PROPERTY, property);
- }
-
- private PriviAction(int action, Object arg) {
- this.action = action;
- this.arg1 = arg;
- }
-
- /**
- * Creates a PrivilegedAction to get the current security policy object.
- *
- * @see Policy#getPolicy
- */
- public PriviAction() {
- action = GET_SECURITY_POLICY;
- }
-
- /**
- * Creates a PrivilegedAction to disable the access checks to the given
- * object.
- *
- * @param object
- * the object whose accessible flag will be set to
- * <code>true</code>
- *
- * @see AccessibleObject#setAccessible(boolean)
- */
- public PriviAction(AccessibleObject object) {
- action = SET_ACCESSIBLE;
- arg1 = object;
- }
-
- /**
- * Creates a PrivilegedAction to return the value of the system property
- * with the given key.
- *
- * @param property
- * the key of the system property
- *
- * @see System#getProperty(String)
- */
- public PriviAction(String property) {
- action = GET_SYSTEM_PROPERTY;
- arg1 = property;
- }
-
- /**
- * Creates a PrivilegedAction to return the value of the system property
- * with the given key.
- *
- * @param property
- * the key of the system property
- * @param defaultAnswer
- * the return value if the system property does not exist
- *
- * @see System#getProperty(String, String)
- */
- public PriviAction(String property, String defaultAnswer) {
- action = GET_SYSTEM_PROPERTY;
- arg1 = property;
- arg2 = defaultAnswer;
- }
-
- /**
- * Performs the actual privileged computation as defined by the constructor.
- *
- * @see java.security.PrivilegedAction#run()
- */
- @SuppressWarnings("unchecked")
- public T run() {
- switch (action) {
- case GET_SYSTEM_PROPERTY:
- return (T)System.getProperty((String) arg1, (String) arg2);
- case GET_SECURITY_PROPERTY:
- return (T)Security.getProperty((String) arg1);
- case GET_SECURITY_POLICY:
- return (T)Policy.getPolicy();
- case SET_ACCESSIBLE:
- ((AccessibleObject) arg1).setAccessible(true);
- }
- return null;
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/Util.java b/luni/src/main/java/org/apache/harmony/luni/util/Util.java
deleted file mode 100644
index dfc7c20..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/util/Util.java
+++ /dev/null
@@ -1,116 +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.io.ByteArrayOutputStream;
-import java.io.UnsupportedEncodingException;
-
-public final class Util {
- /**
- * '%' and two following hex digit characters are converted to the
- * equivalent byte value. All other characters are passed through
- * unmodified. e.g. "ABC %24%25" -> "ABC $%"
- *
- * @param s
- * java.lang.String The encoded string.
- * @return java.lang.String The decoded version.
- */
- public static String decode(String s, boolean convertPlus) {
- return decode(s, convertPlus, null);
- }
-
- /**
- * '%' and two following hex digit characters are converted to the
- * equivalent byte value. All other characters are passed through
- * unmodified. e.g. "ABC %24%25" -> "ABC $%"
- *
- * @param s
- * java.lang.String The encoded string.
- * @param encoding
- * the specified encoding
- * @return java.lang.String The decoded version.
- */
- public static String decode(String s, boolean convertPlus, String encoding) {
- if (!convertPlus && s.indexOf('%') == -1)
- return s;
- StringBuilder result = new StringBuilder(s.length());
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for (int i = 0; i < s.length();) {
- char c = s.charAt(i);
- if (convertPlus && c == '+')
- result.append(' ');
- else if (c == '%') {
- out.reset();
- do {
- if (i + 2 >= s.length()) {
- throw new IllegalArgumentException("Incomplete % sequence at: " + i);
- }
- int d1 = Character.digit(s.charAt(i + 1), 16);
- int d2 = Character.digit(s.charAt(i + 2), 16);
- if (d1 == -1 || d2 == -1) {
- throw new IllegalArgumentException("Invalid % sequence " +
- s.substring(i, i + 3) + " at " + i);
- }
- out.write((byte) ((d1 << 4) + d2));
- i += 3;
- } while (i < s.length() && s.charAt(i) == '%');
- if (encoding == null) {
- result.append(out.toString());
- } else {
- try {
- result.append(out.toString(encoding));
- } catch (UnsupportedEncodingException e) {
- throw new IllegalArgumentException(e);
- }
- }
- continue;
- } else
- result.append(c);
- i++;
- }
- return result.toString();
- }
-
- public static String toASCIILowerCase(String s) {
- int len = s.length();
- StringBuilder buffer = new StringBuilder(len);
- for (int i = 0; i < len; i++) {
- char c = s.charAt(i);
- if ('A' <= c && c <= 'Z') {
- buffer.append((char) (c + ('a' - 'A')));
- } else {
- buffer.append(c);
- }
- }
- return buffer.toString();
- }
-
- public static String toASCIIUpperCase(String s) {
- int len = s.length();
- StringBuilder buffer = new StringBuilder(len);
- for (int i = 0; i < len; i++) {
- char c = s.charAt(i);
- if ('a' <= c && c <= 'z') {
- buffer.append((char) (c - ('a' - 'A')));
- } else {
- buffer.append(c);
- }
- }
- return buffer.toString();
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java b/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java
index ddbac0a..f2cc0d2 100644
--- a/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java
+++ b/luni/src/main/java/org/apache/harmony/security/DefaultPolicyScanner.java
@@ -125,9 +125,9 @@
break parsing;
case StreamTokenizer.TT_WORD:
- if (Util.equalsIgnoreCase("keystore", st.sval)) {
+ if (st.sval.equalsIgnoreCase("keystore")) {
keystoreEntries.add(readKeystoreEntry(st));
- } else if (Util.equalsIgnoreCase("grant", st.sval)) {
+ } else if (st.sval.equalsIgnoreCase("grant")) {
grantEntries.add(readGrantEntry(st));
} else {
handleUnexpectedToken(st, "Expected entries are \"grant\" or \"keystore\"");
@@ -206,19 +206,19 @@
switch (st.nextToken()) {
case StreamTokenizer.TT_WORD:
- if (Util.equalsIgnoreCase("signedby", st.sval)) {
+ if (st.sval.equalsIgnoreCase("signedby")) {
if (st.nextToken() == '"') {
ge.signers = st.sval;
} else {
handleUnexpectedToken(st, "Expected syntax is signedby \"name1,...,nameN\"");
}
- } else if (Util.equalsIgnoreCase("codebase", st.sval)) {
+ } else if (st.sval.equalsIgnoreCase("codebase")) {
if (st.nextToken() == '"') {
ge.codebase = st.sval;
} else {
handleUnexpectedToken(st, "Expected syntax is codebase \"url\"");
}
- } else if (Util.equalsIgnoreCase("principal", st.sval)) {
+ } else if (st.sval.equalsIgnoreCase("principal")) {
ge.addPrincipal(readPrincipalEntry(st));
} else {
handleUnexpectedToken(st);
@@ -306,7 +306,7 @@
switch (st.nextToken()) {
case StreamTokenizer.TT_WORD:
- if (Util.equalsIgnoreCase("permission", st.sval)) {
+ if (st.sval.equalsIgnoreCase("permission")) {
PermissionEntry pe = new PermissionEntry();
if (st.nextToken() == StreamTokenizer.TT_WORD) {
pe.klass = st.sval;
@@ -324,7 +324,7 @@
}
}
if (st.ttype == StreamTokenizer.TT_WORD
- && Util.equalsIgnoreCase("signedby", st.sval)) {
+ && st.sval.equalsIgnoreCase("signedby")) {
if (st.nextToken() == '"') {
pe.signers = st.sval;
} else {
diff --git a/luni/src/main/java/org/apache/harmony/security/Util.java b/luni/src/main/java/org/apache/harmony/security/Util.java
deleted file mode 100644
index e6e764f..0000000
--- a/luni/src/main/java/org/apache/harmony/security/Util.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.security;
-
-public class Util {
-
- public static String toUpperCase(String s) {
- return org.apache.harmony.luni.util.Util.toASCIIUpperCase(s);
- }
-
- public static boolean equalsIgnoreCase(String s1, String s2) {
- s1 = org.apache.harmony.luni.util.Util.toASCIIUpperCase(s1);
- s2 = org.apache.harmony.luni.util.Util.toASCIIUpperCase(s2);
- return s1.equals(s2);
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Any.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Any.java
index 59f8779..d55f2bd 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Any.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Any.java
@@ -30,10 +30,9 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public final class ASN1Any extends ASN1Type {
-public class ASN1Any extends ASN1Type {
-
- // default implementation
+ /** default implementation */
private static final ASN1Any ASN1= new ASN1Any();
/**
@@ -60,12 +59,6 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
/**
* Tests provided identifier.
*
@@ -77,7 +70,6 @@
}
public Object decode(BerInputStream in) throws IOException {
-
// only read content, doesn't check it
in.readContent();
@@ -91,8 +83,7 @@
* Extracts array of bytes that represents full encoding from BER input
* stream.
*
- * @param in -
- * BER input stream
+ * @param in BER input stream
* @return array of bytes
*/
public Object getDecodedObject(BerInputStream in) throws IOException {
@@ -102,12 +93,6 @@
return bytesEncoded;
}
- //
- //
- // Encode
- //
- //
-
public void encodeASN(BerOutputStream out) {
out.encodeANY();
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1BitString.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1BitString.java
index 7b5336c..a1ac7b6 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1BitString.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1BitString.java
@@ -23,13 +23,13 @@
package org.apache.harmony.security.asn1;
import java.io.IOException;
+import libcore.util.EmptyArray;
/**
* This class represents ASN.1 Bitstring type.
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class ASN1BitString extends ASN1StringType {
// default implementation
@@ -60,14 +60,7 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
- public Object decode(BerInputStream in) throws IOException {
-
+ @Override public Object decode(BerInputStream in) throws IOException {
in.readBitString();
if (in.isVerify) {
@@ -82,31 +75,21 @@
* @param in - BER input stream
* @return BitString object
*/
- public Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
byte[] bytes = new byte[in.length - 1];
System.arraycopy(in.buffer, in.contentOffset + 1, bytes, 0,
in.length - 1);
return new BitString(bytes, in.buffer[in.contentOffset]);
}
- //
- // Encode
- //
-
- public void encodeContent(BerOutputStream out) {
+ @Override public void encodeContent(BerOutputStream out) {
out.encodeBitString();
}
- public void setEncodingContent(BerOutputStream out) {
+ @Override public void setEncodingContent(BerOutputStream out) {
out.length = ((BitString) out.content).bytes.length + 1;
}
- //
- //
- // Named Bit List
- //
- //
-
/**
* Default implementation for ASN.1 Named Bitstring type
*
@@ -114,37 +97,20 @@
* that is mapped to array of boolean.
*/
public static class ASN1NamedBitList extends ASN1BitString {
-
- private static final byte[] SET_MASK = { (byte) 128, 64, 32, 16, 8, 4,
- 2, 1 };
-
- private static final BitString emptyString = new BitString(
- new byte[] {}, 0);
-
+ private static final byte[] SET_MASK = { (byte) 128, 64, 32, 16, 8, 4, 2, 1};
+ private static final BitString emptyString = new BitString(EmptyArray.BYTE, 0);
private static final int INDEFINITE_SIZE = -1;
private final int minBits;
-
private final int maxBits;
- public ASN1NamedBitList() {
- this.minBits = INDEFINITE_SIZE;
- this.maxBits = INDEFINITE_SIZE;
- }
-
public ASN1NamedBitList(int minBits) {
this.minBits = minBits;
this.maxBits = INDEFINITE_SIZE;
}
- public ASN1NamedBitList(int minBits, int maxBits) {
- this.minBits = minBits;
- this.maxBits = maxBits;
- }
-
- public Object getDecodedObject(BerInputStream in) throws IOException {
-
- boolean[] value = null;
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
+ boolean[] value;
int unusedBits = in.buffer[in.contentOffset];
int bitsNumber = (in.length - 1) * 8 - unusedBits;
@@ -175,7 +141,6 @@
int j = 0;
byte octet = in.buffer[in.contentOffset + i];
for (int size = in.length - 1; i < size; i++) {
-
for (int k = 0; k < 8; k++, j++) {
value[j] = (SET_MASK[k] & octet) != 0;
}
@@ -191,8 +156,7 @@
return value;
}
- public void setEncodingContent(BerOutputStream out) {
-
+ @Override public void setEncodingContent(BerOutputStream out) {
boolean[] toEncode = (boolean[]) out.content;
int index = toEncode.length - 1;
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Boolean.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Boolean.java
index 49cc35b..99d2a64 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Boolean.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Boolean.java
@@ -30,10 +30,9 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public final class ASN1Boolean extends ASN1Primitive {
-public class ASN1Boolean extends ASN1Primitive {
-
- // default implementation
+ /** default implementation */
private static final ASN1Boolean ASN1 = new ASN1Boolean();
/**
@@ -60,12 +59,6 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readBoolean();
@@ -81,19 +74,13 @@
* @param in - BER input stream
* @return java.lang.Boolean object
*/
- public Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
if (in.buffer[in.contentOffset] == 0) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
- //
- //
- // Encode
- //
- //
-
public void encodeContent(BerOutputStream out) {
out.encodeBoolean();
}
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 ae719a5..90ea48b 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
@@ -207,14 +207,14 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public abstract class ASN1Choice extends ASN1Type {
-
public final ASN1Type[] type;
- // identifiers table: [2][number of distinct identifiers]
- // identifiers[0]: stores identifiers (includes nested choices)
- // identifiers[1]: stores identifiers' indexes in array of types
+ /**
+ * identifiers table: [2][number of distinct identifiers]
+ * identifiers[0]: stores identifiers (includes nested choices)
+ * identifiers[1]: stores identifiers' indexes in array of types
+ */
private final int[][] identifiers;
/**
@@ -233,9 +233,8 @@
}
// create map of all identifiers
- TreeMap map = new TreeMap();
+ TreeMap<BigInteger, BigInteger> map = new TreeMap<BigInteger, BigInteger>();
for (int index = 0; index < type.length; index++) {
-
ASN1Type t = type[index];
if (t instanceof ASN1Any) {
@@ -266,31 +265,26 @@
// fill identifiers array
int size = map.size();
identifiers = new int[2][size];
- Iterator it = map.entrySet().iterator();
+ Iterator<Map.Entry<BigInteger, BigInteger>> it = map.entrySet().iterator();
for (int i = 0; i < size; i++) {
- Map.Entry entry = (Map.Entry) it.next();
- BigInteger identifier = (BigInteger) entry.getKey();
+ Map.Entry<BigInteger, BigInteger> entry = it.next();
+ BigInteger identifier = entry.getKey();
identifiers[0][i] = identifier.intValue();
- identifiers[1][i] = ((BigInteger) entry.getValue()).intValue();
+ identifiers[1][i] = entry.getValue().intValue();
}
this.type = type;
}
- private void addIdentifier(TreeMap map, int identifier, int index){
+ private void addIdentifier(TreeMap<BigInteger, BigInteger> map, int identifier, int index){
if (map.put(BigInteger.valueOf(identifier), BigInteger.valueOf(index)) != null) {
- throw new IllegalArgumentException("ASN.1 choice type MUST have alternatives with distinct tags: " + getClass().getName()); // FIXME name
+ throw new IllegalArgumentException("ASN.1 choice type MUST have alternatives "
+ + "with distinct tags: " + getClass().getName());
}
}
- //
- //
- // DECODE
- //
- //
-
/**
* Tests whether one of choice alternatives has the same identifier or not.
*
@@ -304,7 +298,6 @@
}
public Object decode(BerInputStream in) throws IOException {
-
int index = Arrays.binarySearch(identifiers[0], in.tag);
if (index < 0) {
throw new ASN1Exception("Failed to decode ASN.1 choice type. No alternatives were found for " + getClass().getName());// FIXME message
@@ -323,12 +316,6 @@
return getDecodedObject(in);
}
- //
- //
- // ENCODE
- //
- //
-
public void encodeASN(BerOutputStream out) {
encodeContent(out);
}
@@ -337,12 +324,6 @@
out.encodeChoice(this);
}
- /**
- * TODO Put method description here
- *
- * @param object - an object to be encoded
- * @return
- */
public abstract int getIndex(Object object);
public abstract Object getObjectToEncode(Object object);
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Constructured.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Constructed.java
similarity index 89%
rename from luni/src/main/java/org/apache/harmony/security/asn1/ASN1Constructured.java
rename to luni/src/main/java/org/apache/harmony/security/asn1/ASN1Constructed.java
index 2f17d49..add02b3 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Constructured.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Constructed.java
@@ -28,14 +28,13 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public abstract class ASN1Constructed extends ASN1Type {
-public abstract class ASN1Constructured extends ASN1Type {
-
- public ASN1Constructured(int tagNumber) {
+ protected ASN1Constructed(int tagNumber) {
super(CLASS_UNIVERSAL, tagNumber);
}
- public ASN1Constructured(int tagClass, int tagNumber) {
+ protected ASN1Constructed(int tagClass, int tagNumber) {
super(tagClass, tagNumber);
}
@@ -50,9 +49,6 @@
return this.constrId == identifier;
}
- /**
- *
- */
public void encodeASN(BerOutputStream out) {
out.encodeTag(constrId);
encodeContent(out);
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Enumerated.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Enumerated.java
index bc7b208..cccea94 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Enumerated.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Enumerated.java
@@ -23,6 +23,7 @@
package org.apache.harmony.security.asn1;
import java.io.IOException;
+import java.util.Arrays;
/**
@@ -30,8 +31,7 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
-public class ASN1Enumerated extends ASN1Primitive {
+public final class ASN1Enumerated extends ASN1Primitive {
// default implementation
private static final ASN1Enumerated ASN1 = new ASN1Enumerated();
@@ -60,12 +60,6 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readEnumerated();
@@ -78,22 +72,12 @@
/**
* Extracts array of bytes from BER input stream.
*
- * @param in - BER input stream
* @return array of bytes
*/
public Object getDecodedObject(BerInputStream in) throws IOException {
- byte[] bytesEncoded = new byte[in.length];
- System.arraycopy(in.buffer, in.contentOffset, bytesEncoded, 0,
- in.length);
- return bytesEncoded;
+ return Arrays.copyOfRange(in.buffer, in.contentOffset, in.contentOffset + in.length);
}
- //
- //
- // Encode
- //
- //
-
public void encodeContent(BerOutputStream out) {
out.encodeInteger();
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Exception.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Exception.java
index cfab29d..c17ee8e 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Exception.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Exception.java
@@ -27,25 +27,11 @@
/**
* Thrown by decoder/encoder stream to indicate violation of encoding rules.
*/
+public final class ASN1Exception extends IOException {
-public class ASN1Exception extends IOException {
-
- /**
- * @serial
- */
+ /** @serial */
private static final long serialVersionUID = -3561981263989123987L;
- /**
- * Constructs an ASN1Exception without a message.
- */
- public ASN1Exception(){
- }
-
- /**
- * Constructs an ASN1Exception with a message.
- *
- * @param message - a string that describes encoding violation
- */
public ASN1Exception(String message){
super(message);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Explicit.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Explicit.java
index 15dcc97..45e2167 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Explicit.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Explicit.java
@@ -24,18 +24,14 @@
import java.io.IOException;
-
/**
* This class represents explicitly tagged ASN.1 type.
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public final class ASN1Explicit extends ASN1Constructed {
-public final class ASN1Explicit extends ASN1Constructured {
-
- /**
- * Tagged type
- */
+ /** Tagged type */
public final ASN1Type type;
/**
@@ -60,16 +56,9 @@
*/
public ASN1Explicit(int tagClass, int tagNumber, ASN1Type type) {
super(tagClass, tagNumber);
-
this.type = type;
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
if (constrId != in.tag) {
throw new ASN1Exception("ASN.1 explicitly tagged type is expected at [" +
@@ -86,12 +75,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
-
public void encodeContent(BerOutputStream out) {
out.encodeExplicit(this);
}
@@ -100,8 +83,7 @@
out.getExplicitLength(this);
}
- public String toString() {
- //FIXME fix performance
+ @Override public String toString() {
return super.toString() + " for type " + type;
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1GeneralizedTime.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1GeneralizedTime.java
index 93629ad..e64ebe0 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1GeneralizedTime.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1GeneralizedTime.java
@@ -32,8 +32,7 @@
*
* @see http://asn1.elibel.tm.fr/en/standards/index.htm
*/
-
-public class ASN1GeneralizedTime extends ASN1Time {
+public final class ASN1GeneralizedTime extends ASN1Time {
// default implementation
private static final ASN1GeneralizedTime ASN1 = new ASN1GeneralizedTime();
@@ -62,12 +61,6 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readGeneralizedTime();
@@ -77,12 +70,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
-
public void encodeContent(BerOutputStream out) {
out.encodeGeneralizedTime();
}
@@ -93,10 +80,9 @@
// four digit year, seconds always presented
// and fractional-seconds elements without
// trailing 0's (must be cut later from content)
- private final static String GEN_PATTERN = "yyyyMMddHHmmss.SSS";
+ private static final String GEN_PATTERN = "yyyyMMddHHmmss.SSS";
public void setEncodingContent(BerOutputStream out) {
-
SimpleDateFormat sdf = new SimpleDateFormat(GEN_PATTERN);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String temp = sdf.format(out.content);
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Implicit.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Implicit.java
index d910fd1..21c4ec6 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Implicit.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Implicit.java
@@ -30,24 +30,26 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-public class ASN1Implicit extends ASN1Type {
+public final class ASN1Implicit extends ASN1Type {
- // primitive type of tagging
+ /** primitive type of tagging */
private static final int TAGGING_PRIMITIVE = 0;
- // constructed type of tagging
+ /** constructed type of tagging */
private static final int TAGGING_CONSTRUCTED = 1;
- // string type of tagging
+ /** string type of tagging */
private static final int TAGGING_STRING = 2;
- // tagged ASN.1 type
+ /** tagged ASN.1 type */
private final ASN1Type type;
- // type of tagging. There are three of them
- // 1) primitive: only primitive identifier is valid
- // 2) constructed: only constructed identifier is valid
- // 3) string: both identifiers are valid
+ /**
+ * type of tagging. There are three of them
+ * 1) primitive: only primitive identifier is valid
+ * 2) constructed: only constructed identifier is valid
+ * 3) string: both identifiers are valid
+ */
private final int taggingType;
/**
@@ -59,19 +61,7 @@
* @throws IllegalArgumentException - if tagNumber or type is invalid
*/
public ASN1Implicit(int tagNumber, ASN1Type type) {
- this(CLASS_CONTEXTSPECIFIC, tagNumber, type);
- }
-
- /**
- * Constructs implicitly tagged ASN.1 type
- *
- * @param tagClass - ASN.1 tag class.
- * @param tagNumber - ASN.1 tag number
- * @param type - ASN.1 type to be tagged
- * @throws IllegalArgumentException - if tagNumber, tagClass or type is invalid
- */
- public ASN1Implicit(int tagClass, int tagNumber, ASN1Type type) {
- super(tagClass, tagNumber);
+ super(CLASS_CONTEXTSPECIFIC, tagNumber);
if ((type instanceof ASN1Choice) || (type instanceof ASN1Any)) {
// According to X.680:
@@ -98,15 +88,6 @@
}
}
- //
- //
- // Decode
- //
- //
-
- /**
- * TODO
- */
public final boolean checkTag(int identifier) {
switch (taggingType) {
case TAGGING_PRIMITIVE:
@@ -118,9 +99,6 @@
}
}
- /**
- * TODO
- */
public Object decode(BerInputStream in) throws IOException {
if (!checkTag(in.tag)) {
// FIXME need look for tagging type
@@ -129,7 +107,7 @@
"but got " + Integer.toHexString(in.tag));
}
- // substitute indentifier for further decoding
+ // substitute identifier for further decoding
if (id == in.tag) {
in.tag = type.id;
} else {
@@ -143,12 +121,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
-
public void encodeASN(BerOutputStream out) {
//FIXME need another way for specifying identifier to be encoded
if (taggingType == TAGGING_CONSTRUCTED) {
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Integer.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Integer.java
index 9230bbd..6f33d09 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Integer.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Integer.java
@@ -25,16 +25,14 @@
import java.io.IOException;
import java.math.BigInteger;
-
/**
* This class represents ASN.1 Integer type.
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public final class ASN1Integer extends ASN1Primitive {
-public class ASN1Integer extends ASN1Primitive {
-
- // default implementation
+ /** default implementation */
private static final ASN1Integer ASN1 = new ASN1Integer();
/**
@@ -61,12 +59,6 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readInteger();
@@ -79,7 +71,6 @@
/**
* Extracts array of bytes from BER input stream.
*
- * @param in - BER input stream
* @return array of bytes
*/
public Object getDecodedObject(BerInputStream in) throws IOException {
@@ -89,12 +80,6 @@
return bytesEncoded;
}
- //
- //
- // Encode
- //
- //
-
public void encodeContent(BerOutputStream out) {
out.encodeInteger();
}
@@ -103,7 +88,6 @@
out.length = ((byte[]) out.content).length;
}
-// BEGIN android-changed
/**
* Converts decoded ASN.1 Integer to int value.
* If the object represents an integer value
@@ -113,7 +97,7 @@
* @return decoded int value.
*/
public static int toIntValue(Object decoded) {
- return new BigInteger((byte[]) decoded).intValue();//FIXME optimize
+ return new BigInteger((byte[]) decoded).intValue();
}
/**
@@ -123,9 +107,8 @@
* @return decoded BigInteger value.
*/
public static BigInteger toBigIntegerValue(Object decoded) {
- return new BigInteger((byte[]) decoded);//FIXME optimize
+ return new BigInteger((byte[]) decoded);
}
-// END android-changed
/**
* Converts primitive int value to a form most suitable for encoding.
@@ -134,7 +117,6 @@
* @return object suitable for encoding
*/
public static Object fromIntValue(int value) {
- //FIXME optimize
return BigInteger.valueOf(value).toByteArray();
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OctetString.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OctetString.java
index 5d113a4..7b344f7 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OctetString.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OctetString.java
@@ -23,6 +23,7 @@
package org.apache.harmony.security.asn1;
import java.io.IOException;
+import java.util.Arrays;
/**
@@ -30,10 +31,9 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class ASN1OctetString extends ASN1StringType {
- // default implementation
+ /** default implementation */
private static final ASN1OctetString ASN1 = new ASN1OctetString();
/**
@@ -53,20 +53,12 @@
*
* The default implementation works with encoding
* that is represented as byte array.
- *
- * @return ASN.1 octet string type default implementation
*/
public static ASN1OctetString getInstance() {
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
- public Object decode(BerInputStream in) throws IOException {
+ @Override public Object decode(BerInputStream in) throws IOException {
in.readOctetString();
if (in.isVerify) {
@@ -78,27 +70,17 @@
/**
* Extracts array of bytes from BER input stream.
*
- * @param in - BER input stream
* @return array of bytes
*/
- public Object getDecodedObject(BerInputStream in) throws IOException {
- byte[] bytesEncoded = new byte[in.length];
- System.arraycopy(in.buffer, in.contentOffset, bytesEncoded, 0,
- in.length);
- return bytesEncoded;
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
+ return Arrays.copyOfRange(in.buffer, in.contentOffset, in.contentOffset + in.length);
}
- //
- //
- // Encode
- //
- //
-
- public void encodeContent(BerOutputStream out) {
+ @Override public void encodeContent(BerOutputStream out) {
out.encodeOctetString();
}
- public void setEncodingContent(BerOutputStream out) {
+ @Override public void setEncodingContent(BerOutputStream out) {
out.length = ((byte[]) out.content).length;
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Oid.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Oid.java
index b286284..b926b82 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Oid.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Oid.java
@@ -30,10 +30,9 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class ASN1Oid extends ASN1Primitive {
- // default implementation
+ /** default implementation */
private static final ASN1Oid ASN1 = new ASN1Oid();
/**
@@ -60,12 +59,6 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readOID();
@@ -78,10 +71,9 @@
/**
* Extracts array of integers from BER input stream.
*
- * @param in - BER input stream
* @return array of integers
*/
- public Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
// Allocate and decode
int oidElement = in.oidElement;
int[] oid = new int[oidElement];
@@ -106,12 +98,6 @@
return oid;
}
- //
- //
- // Encode
- //
- //
-
public void encodeContent(BerOutputStream out) {
out.encodeOID();
}
@@ -144,23 +130,13 @@
out.length = length;
}
- //
- //
- // OID encoder/decoder for mapping to string
- //
- //
-
- private final static ASN1Oid STRING_OID = new ASN1Oid() {
-
- public Object getDecodedObject(BerInputStream in) throws IOException {
-
+ private static final ASN1Oid STRING_OID = new ASN1Oid() {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
StringBuilder buf = new StringBuilder();
- int element;
-
//Special handling for the first packed OID element
int octet = in.buffer[in.contentOffset];
- element = octet & 0x7F;
+ int element = octet & 0x7F;
int index = 0;
while ((octet & 0x80) != 0) {
@@ -199,11 +175,9 @@
return buf.toString();
}
- public void setEncodingContent(BerOutputStream out) {
-
+ @Override public void setEncodingContent(BerOutputStream out) {
//FIXME this is a stub for a while
out.content = ObjectIdentifier.toIntArray((String) out.content);
-
super.setEncodingContent(out);
}
};
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OpenType.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OpenType.java
deleted file mode 100644
index 44c68b2..0000000
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1OpenType.java
+++ /dev/null
@@ -1,84 +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.
- */
-
-/**
-* @author Stepan M. Mishura
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.asn1;
-
-import java.io.IOException;
-import org.apache.harmony.security.x501.AttributeType;
-
-
-
-/**
- * Represents ASN.1 open type that is defined by Oid
- *
- * @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
- */
-
-public class ASN1OpenType extends ASN1Any {
-
- private final Id key;
-
- private final InformationObjectSet pool;
-
- public ASN1OpenType(Id key, InformationObjectSet pool) {
- this.key = key;
- this.pool = pool;
- }
-
- public Object decode(BerInputStream in) throws IOException {
-
- int[] oid = (int[]) in.get(key);
- if (oid == null) {
- throw new RuntimeException("");//FIXME message & type
- }
-
- AttributeType attr = (AttributeType) pool.get(oid);
- if (attr == null || (!attr.type.checkTag(in.tag))) {
- in.content = (byte[]) super.getDecodedObject(in);
- } else {
- in.content = attr.type.decode(in);
- }
- return in.content;
- }
-
- public Object getDecodedObject(BerInputStream in) throws IOException {
- return in.content;
- }
-
- public static class Id extends ASN1Oid {
-
- public Object decode(BerInputStream in) throws IOException {
- Object oid = super.decode(in);
-
- if (oid == null) {
- in.put(this, super.getDecodedObject(in));
- } else {
- in.put(this, oid);
- }
- return oid;
- }
-
- public Object getDecodedObject(BerInputStream in) throws IOException {
- return in.get(this);
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Primitive.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Primitive.java
index 1dc17ec..dd25379 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Primitive.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Primitive.java
@@ -28,7 +28,6 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public abstract class ASN1Primitive extends ASN1Type {
public ASN1Primitive(int tagNumber) {
@@ -38,18 +37,14 @@
/**
* Tests provided identifier.
*
- * @param identifier -
- * identifier to be verified
- * @return - true if identifier correspond to primitive identifier of this
- * ASN.1 type, otherwise false
+ * @param identifier identifier to be verified
+ * @return true if identifier correspond to primitive identifier of this
+ * ASN.1 type, otherwise false
*/
public final boolean checkTag(int identifier) {
return this.id == identifier;
}
- /**
- * TODO
- */
public void encodeASN(BerOutputStream out) {
out.encodeTag(id);
encodeContent(out);
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Sequence.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Sequence.java
index bfaf517..129cb57 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Sequence.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Sequence.java
@@ -30,21 +30,12 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class ASN1Sequence extends ASN1TypeCollection {
public ASN1Sequence(ASN1Type[] type) {
super(TAG_SEQUENCE, type);
-
- //FIXME optional components must be checked for distinct identifiers
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readSequence(this);
@@ -54,11 +45,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
public final void encodeContent(BerOutputStream out) {
out.encodeSequence(this);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SequenceOf.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SequenceOf.java
index 94b320e..a549eb5 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SequenceOf.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SequenceOf.java
@@ -23,9 +23,6 @@
package org.apache.harmony.security.asn1;
import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
/**
@@ -33,19 +30,12 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class ASN1SequenceOf extends ASN1ValueCollection {
public ASN1SequenceOf(ASN1Type type) {
super(TAG_SEQUENCE, type);
}
- //
- //
- // Decode
- //
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readSequenceOf(this);
@@ -55,12 +45,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
-
public final void encodeContent(BerOutputStream out) {
out.encodeSequenceOf(this);
}
@@ -68,27 +52,5 @@
public final void setEncodingContent(BerOutputStream out) {
out.getSequenceOfLength(this);
}
-
- /**
- * Creates array wrapper of provided ASN1 type
- *
- * @param type - ASN1 type to be wrapped
- * @return - a wrapper for ASN1 set of type.
- * @throws IOException
- * @see org.apache.harmony.security.asn1.ASN1ValueCollection
- */
- public static ASN1SequenceOf asArrayOf(ASN1Type type) {
-
- return new ASN1SequenceOf(type) {
- public Object getDecodedObject(BerInputStream in)
- throws IOException {
- return ((List) in.content).toArray();
- }
-
- public Collection getValues(Object object) {
- return Arrays.asList((Object[]) object);
- }
- };
- }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Set.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Set.java
index cdf9d64..fff0c64 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Set.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Set.java
@@ -30,24 +30,12 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
-public class ASN1Set extends ASN1TypeCollection {
+public final class ASN1Set extends ASN1TypeCollection {
public ASN1Set(ASN1Type[] type) {
super(TAG_SET, type);
-
- //FIXME implement check for distinct tags
- //if (!hasDistinctTags(type)) {
- // throw new RuntimeException("ASN1 set type: " + getClass().getName()
- // + " MUST have alternatives with distinct tags");
- //}
}
- //
- //
- // Decode
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readSet(this);
@@ -57,11 +45,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
public final void encodeContent(BerOutputStream out) {
out.encodeSet(this);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SetOf.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SetOf.java
index 3358105..8af221a 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SetOf.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1SetOf.java
@@ -23,9 +23,6 @@
package org.apache.harmony.security.asn1;
import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
/**
@@ -33,18 +30,12 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class ASN1SetOf extends ASN1ValueCollection {
public ASN1SetOf(ASN1Type type) {
super(TAG_SETOF, type);
}
- //
- //
- // Decode
- //
-
public Object decode(BerInputStream in) throws IOException {
in.readSetOf(this);
@@ -54,11 +45,6 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
public final void encodeContent(BerOutputStream out) {
out.encodeSetOf(this);
}
@@ -66,27 +52,5 @@
public final void setEncodingContent(BerOutputStream out) {
out.getSetOfLength(this);
}
-
- /**
- * Creates array wrapper of provided ASN1 type
- *
- * @param type - ASN1 type to be wrapped
- * @return - a wrapper for ASN1 set of type.
- * @throws IOException
- * @see org.apache.harmony.security.asn1.ASN1ValueCollection
- */
- public static ASN1SetOf asArrayOf(ASN1Type type) throws IOException {
-
- return new ASN1SetOf(type) {
- public Object getDecodedObject(BerInputStream in)
- throws IOException {
- return ((List) in.content).toArray();
- }
-
- public Collection getValues(Object object) {
- return Arrays.asList((Object[]) object);
- }
- };
- }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1StringType.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1StringType.java
index 689b036..71f5b0e 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1StringType.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1StringType.java
@@ -30,7 +30,6 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public abstract class ASN1StringType extends ASN1Type {
// TODO: what about defining them as separate classes?
@@ -59,14 +58,12 @@
TAG_UNIVERSALSTRING) {
};
- public static final ASN1StringType UTF8STRING = new ASN1StringType(
- TAG_UTF8STRING) {
-
- public Object getDecodedObject(BerInputStream in) throws IOException {
+ public static final ASN1StringType UTF8STRING = new ASN1StringType(TAG_UTF8STRING) {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
return new String(in.buffer, in.contentOffset, in.length, Charsets.UTF_8);
}
- public void setEncodingContent(BerOutputStream out) {
+ @Override public void setEncodingContent(BerOutputStream out) {
byte[] bytes = ((String) out.content).getBytes(Charsets.UTF_8);
out.content = bytes;
out.length = bytes.length;
@@ -77,26 +74,18 @@
super(tagNumber);
}
- //
- //
- // Decode
- //
- //
-
/**
* Tests provided identifier.
*
- * @param identifier -
- * identifier to be verified
- * @return - true if identifier correspond to primitive or constructed
- * identifier of this ASN.1 string type, otherwise false
+ * @param identifier identifier to be verified
+ * @return true if identifier correspond to primitive or constructed
+ * identifier of this ASN.1 string type, otherwise false
*/
public final boolean checkTag(int identifier) {
return this.id == identifier || this.constrId == identifier;
}
public Object decode(BerInputStream in) throws IOException {
-
in.readString(this);
if (in.isVerify) {
@@ -107,9 +96,6 @@
/**
* Extracts String object from BER input stream.
- *
- * @param in - BER input stream
- * @return java.land.String object
*/
public Object getDecodedObject(BerInputStream in) throws IOException {
/* To ensure we get the correct encoding on non-ASCII platforms, specify
@@ -117,12 +103,6 @@
return new String(in.buffer, in.contentOffset, in.length, Charsets.ISO_8859_1);
}
- //
- //
- // Encode
- //
- //
-
public void encodeASN(BerOutputStream out) {
out.encodeTag(id);
encodeContent(out);
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Time.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Time.java
index bed5088..730cac7 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Time.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Time.java
@@ -36,21 +36,12 @@
public abstract class ASN1Time extends ASN1StringType {
- /**
- * TODO Put ctor description here
- *
- * @param tagNumber
- */
public ASN1Time(int tagNumber) {
super(tagNumber);
}
- public Object getDecodedObject(BerInputStream in) throws IOException {
-
- // TODO optimize me:
- // It makes sense use calendar instance instead of times array
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
-
c.set(Calendar.YEAR, in.times[0]);
c.set(Calendar.MONTH, in.times[1]-1);
c.set(Calendar.DAY_OF_MONTH, in.times[2]);
@@ -58,7 +49,6 @@
c.set(Calendar.MINUTE, in.times[4]);
c.set(Calendar.SECOND, in.times[5]);
c.set(Calendar.MILLISECOND, in.times[6]);
-
return c.getTime();
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Type.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Type.java
index 729ef3a..bc50f5d 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Type.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Type.java
@@ -31,17 +31,12 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public abstract class ASN1Type implements ASN1Constants {
- /**
- * Integer representation of primitive identifier.
- */
+ /** Integer representation of primitive identifier. */
public final int id;
- /**
- * Integer representation of constructed identifier.
- */
+ /** Integer representation of constructed identifier. */
public final int constrId;
/**
@@ -59,7 +54,6 @@
*
* @param tagClass - tag class. MUST be
* CLASS_UNIVERSAL, CLASS_APPLICATION, CLASS_CONTEXTSPECIFIC, CLASS_PRIVATE
- * @param isConstructed - is ASN.1 type is a constructed type.
* @param tagNumber - ASN.1 tag number.
* @throws IllegalArgumentException - if tagClass or tagNumber is invalid
*/
@@ -84,12 +78,6 @@
this.constrId = this.id + PC_CONSTRUCTED;
}
- //
- //
- // Stubs for DER
- //
- //
-
public final Object decode(byte[] encoded) throws IOException {
return decode(new DerInputStream(encoded));
}
@@ -116,34 +104,22 @@
}
public final byte[] encode(Object object) {
-
DerOutputStream out = new DerOutputStream(this, object);
return out.encoded;
}
- //
- //
- // Decode
- //
- //
-
/**
* Decodes ASN.1 type.
*
- * @param in -
- * BER input stream
- * @throws IOException -
- * if an I/O error occurs or the end of the stream is reached
+ * @throws IOException if an I/O error occurs or the end of the stream is reached
*/
public abstract Object decode(BerInputStream in) throws IOException;
/**
* Tests provided identifier.
*
- * @param identifier -
- * identifier to be verified
- * @return - true if identifier is associated with this ASN.1 type,
- * otherwise false
+ * @param identifier identifier to be verified
+ * @return true if identifier is associated with this ASN.1 type
*/
public abstract boolean checkTag(int identifier);
@@ -154,26 +130,13 @@
* selected class of objects during decoding.
*
* The default implementation returns an object created by decoding stream.
- *
- * @param -
- * input stream
- * @return - created object
*/
- //FIXME make me public
protected Object getDecodedObject(BerInputStream in) throws IOException {
return in.content;
}
- //
- //
- // Encode
- //
- //
-
/**
* Encodes ASN.1 type.
- *
- * @param out - BER output stream
*/
public abstract void encodeASN(BerOutputStream out);
@@ -182,7 +145,6 @@
public abstract void setEncodingContent(BerOutputStream out);
public int getEncodedLength(BerOutputStream out) { //FIXME name
-
//tag length
int len = 1; //FIXME tag length = 1. what about long form?
//for (; tag > 0; tag = tag >> 8, len++);
@@ -201,10 +163,8 @@
return len;
}
- public String toString() {
+ @Override public String toString() {
// TODO decide whether this method is necessary
- //FIXME fix performance
- return this.getClass().getName() + "(tag: 0x"
- + Integer.toHexString(0xff & this.id) + ")";
+ return getClass().getName() + "(tag: 0x" + Integer.toHexString(0xff & this.id) + ")";
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1TypeCollection.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1TypeCollection.java
index d441a0e..2499fa2 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1TypeCollection.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1TypeCollection.java
@@ -28,31 +28,23 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public abstract class ASN1TypeCollection extends ASN1Constructed {
-public abstract class ASN1TypeCollection extends ASN1Constructured {
+ public final ASN1Type[] type;
- public final ASN1Type[] type; //TODO comment me
+ public final boolean[] OPTIONAL;
- public final boolean[] OPTIONAL; //TODO comment me
-
- public final Object[] DEFAULT; //TODO comment me
+ public final Object[] DEFAULT;
/**
* Constructs ASN.1 collection type.
*
- * @param tagNumber - ASN.1 tag number
- * @param type - a collection of one or more ASN.1 types.
- * @throws IllegalArgumentException - if tagNumber is invalid
+ * @param tagNumber ASN.1 tag number
+ * @param type a collection of one or more ASN.1 types.
+ * @throws IllegalArgumentException if tagNumber is invalid
*/
- public ASN1TypeCollection(int tagNumber, ASN1Type[] type) {
+ protected ASN1TypeCollection(int tagNumber, ASN1Type[] type) {
super(tagNumber);
- // FIXME what about empty sequence?
- // if (type.length == 0) {
- // throw new ASN1Exception("ASN1 collection type: "
- // + getClass().getName()
- // + " MUST have at least one component");
- // }
-
this.type = type;
this.OPTIONAL = new boolean[type.length];
this.DEFAULT = new Object[type.length];
@@ -61,7 +53,7 @@
/**
* Sets a collection component as optional
*
- * @param index - an index of a component
+ * @param index an index of a component
*/
protected final void setOptional(int index) {
OPTIONAL[index] = true;
@@ -71,8 +63,8 @@
* Sets a default value for a collection component.
* The component also became an optional component.
*
- * @param object - a component's default value
- * @param index - an index of a component
+ * @param object a component's default value
+ * @param index an index of a component
*/
protected final void setDefault(Object object, int index) {
OPTIONAL[index] = true;
@@ -87,8 +79,8 @@
*
* The default implementation throws RuntimeException.
*
- * @param object - an object to be encoded
- * @param values - an array to store an object's values to be encoded
+ * @param object an object to be encoded
+ * @param values an array to store an object's values to be encoded
*/
protected void getValues(Object object, Object[] values) {
throw new RuntimeException("ASN.1 type is not designed to be encoded: " + getClass().getName());
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1UTCTime.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1UTCTime.java
index e4c7686..2bc8f4b 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1UTCTime.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1UTCTime.java
@@ -32,29 +32,21 @@
*
* @see http://asn1.elibel.tm.fr/en/standards/index.htm
*/
-public class ASN1UTCTime extends ASN1Time {
+public final class ASN1UTCTime extends ASN1Time {
- /**
- * Length for the pattern: YYMMDDhhmm'Z'
- */
+ /** Length for the pattern: YYMMDDhhmm'Z' */
public static final int UTC_HM = 11;
- /**
- * Length for the pattern: YYMMDDhhmmss'Z'
- */
+ /** Length for the pattern: YYMMDDhhmmss'Z' */
public static final int UTC_HMS = 13;
- /**
- * Length for the pattern: YYMMDDhhmm('+'/'-')hhmm
- */
+ /** Length for the pattern: YYMMDDhhmm('+'/'-')hhmm */
public static final int UTC_LOCAL_HM = 15;
- /**
- * Length for the pattern: YYMMDDhhmmss('+'/'-')hhmm
- */
+ /** Length for the pattern: YYMMDDhhmmss('+'/'-')hhmm */
public static final int UTC_LOCAL_HMS = 17;
- // default implementation
+ /** default implementation */
private static final ASN1UTCTime ASN1 = new ASN1UTCTime();
/**
@@ -81,13 +73,7 @@
return ASN1;
}
- //
- //
- // Decode
- //
- //
-
- public Object decode(BerInputStream in) throws IOException {
+ @Override public Object decode(BerInputStream in) throws IOException {
in.readUTCTime();
if (in.isVerify) {
@@ -96,12 +82,7 @@
return getDecodedObject(in);
}
- //
- //
- // Encode
- //
- //
- public void encodeContent(BerOutputStream out) {
+ @Override public void encodeContent(BerOutputStream out) {
out.encodeUTCTime();
}
@@ -110,9 +91,9 @@
// According to X.680 coordinated universal time format:
// two digit year, seconds always presented,
// no fractional-seconds elements, 'Z' at the end
- private final static String UTC_PATTERN = "yyMMddHHmmss'Z'";
+ private static final String UTC_PATTERN = "yyMMddHHmmss'Z'";
- public void setEncodingContent(BerOutputStream out) {
+ @Override public void setEncodingContent(BerOutputStream out) {
SimpleDateFormat sdf = new SimpleDateFormat(UTC_PATTERN);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
out.content = sdf.format(out.content).getBytes(Charsets.UTF_8);
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1ValueCollection.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1ValueCollection.java
index 43c36c7..751888c 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1ValueCollection.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1ValueCollection.java
@@ -33,23 +33,16 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
+public abstract class ASN1ValueCollection extends ASN1Constructed {
-public abstract class ASN1ValueCollection extends ASN1Constructured {
-
- /**
- * A value collection of this ASN.1 type
- */
+ /** A value collection of this ASN.1 type */
public final ASN1Type type;
/**
* Constructs ASN1 collection type.
- *
- * @param tagNumber - ASN.1 tag number
- * @param type - ASN.1 type
*/
public ASN1ValueCollection(int tagNumber, ASN1Type type) {
super(tagNumber);
-
this.type = type;
}
@@ -62,7 +55,7 @@
* @param - an object to be encoded
* @return - a collection of object's values to be encoded
*/
- public Collection getValues(Object object) {
- return (Collection)object;
+ public Collection<?> getValues(Object object) {
+ return (Collection<?>) object;
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/BerInputStream.java b/luni/src/main/java/org/apache/harmony/security/asn1/BerInputStream.java
index 74aadb5..002f4cf 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/BerInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/BerInputStream.java
@@ -35,38 +35,42 @@
public class BerInputStream {
- /**
- * Associated <code>InputStream</code>
- */
- protected InputStream in;
-
- /**
- * Internal buffer for storing encoded array
- */
+ private final InputStream in;
protected byte[] buffer;
/**
* The position in the buffer.
- *
* Next read must place data into the buffer from this offset
*/
protected int offset = 0;
- // The buffer increment size.
- // Must be reasonable big to reallocate memory not to often.
- // Primary is used for decoding indefinite length encoding
+ /**
+ * The buffer increment size.
+ * Must be reasonable big to reallocate memory not to often.
+ * Primary is used for decoding indefinite length encoding
+ */
private static final int BUF_INCREASE_SIZE = 1024 * 16;
- /**
- * Indicates indefinite length of the current type
- */
+ /** Indicates indefinite length of the current type */
protected static final int INDEFINIT_LENGTH = -1;
+ /** Current decoded tag */
+ public int tag;
+
+ /** Current decoded length */
+ protected int length;
+
+ /** Current decoded content */
+ public Object content;
+
+ /** Current decoded tag offset */
+ protected int tagOffset;
+
+ /** Current decoded content offset */
+ protected int contentOffset;
+
/**
* Creates stream for decoding.
- *
- * @param encoded - bytes array to be decoded
- * @throws IOException - if an error occurs
*/
public BerInputStream(byte[] encoded) throws IOException {
this(encoded, 0, encoded.length);
@@ -75,19 +79,13 @@
/**
* Creates stream for decoding.
*
- * @param encoded -
- * bytes array to be decoded
- * @param offset -
- * the encoding offset
- * @param expectedLength -
- * expected length of full encoding, this includes identifier,
- * length an content octets
- * @throws IOException -
- * if an error occurs
+ * @param encoded bytes array to be decoded
+ * @param offset the encoding offset
+ * @param expectedLength expected length of full encoding, this includes
+ * identifier, length an content octets
*/
- public BerInputStream(byte[] encoded, int offset, int expectedLength)
- throws IOException {
-
+ public BerInputStream(byte[] encoded, int offset, int expectedLength) throws IOException {
+ this.in = null;
this.buffer = encoded;
this.offset = offset;
@@ -104,8 +102,6 @@
* Creates stream for decoding.
*
* Allocates initial buffer of default size
- *
- * @param is associated <code>InputStream</code>
*/
public BerInputStream(InputStream in) throws IOException {
this(in, BUF_INCREASE_SIZE);
@@ -114,13 +110,9 @@
/**
* Creates stream for decoding.
*
- * Allocates initial buffer of <code>initialSize</code> size
- *
* @param initialSize the internal buffer initial size
- * @param is associated <code>InputStream</code>
*/
public BerInputStream(InputStream in, int initialSize) throws IOException {
-
this.in = in;
buffer = new byte[initialSize];
@@ -143,49 +135,22 @@
/**
* Resets this stream to initial state.
*
- * @param encoded - a new bytes array to be decoded
- * @throws IOException - if an error occurs
+ * @param encoded a new bytes array to be decoded
+ * @throws IOException if an error occurs
*/
public final void reset(byte[] encoded) throws IOException {
buffer = encoded;
-
next();
}
/**
- * Current decoded tag
- */
- public int tag;
-
- /**
- * Current decoded length
- */
- protected int length;
-
- /**
- * Current decoded content
- */
- public Object content;
-
- /**
- * Current decoded tag offset
- */
- protected int tagOffset;
-
- /**
- * Current decoded content offset
- */
- protected int contentOffset;
-
- /**
* Decodes next encoded type.
* Initializes tag, length, tagOffset and contentOffset variables
*
* @return next decoded tag
- * @throws IOException - if error occured
+ * @throws IOException if error occured
*/
public int next() throws IOException {
-
tagOffset = offset;
// read tag
@@ -242,11 +207,8 @@
/**
* Decodes ASN.1 bitstring type
- *
- * @throws IOException - if error occured
*/
public void readBitString() throws IOException {
-
if (tag == ASN1Constants.TAG_BITSTRING) {
if (length == 0) {
@@ -257,11 +219,13 @@
// content: check unused bits
if (buffer[contentOffset] > 7) {
- throw new ASN1Exception("ASN.1 Bitstring: wrong content at [" + contentOffset + "]. A number of unused bits MUST be in range 0 to 7");
+ throw new ASN1Exception("ASN.1 Bitstring: wrong content at [" + contentOffset
+ + "]. A number of unused bits MUST be in range 0 to 7");
}
if (length == 1 && buffer[contentOffset] != 0) {
- throw new ASN1Exception("ASN.1 Bitstring: wrong content at [" + contentOffset + "]. For empty string unused bits MUST be 0");
+ throw new ASN1Exception("ASN.1 Bitstring: wrong content at [" + contentOffset
+ + "]. For empty string unused bits MUST be 0");
}
} else if (tag == ASN1Constants.TAG_C_BITSTRING) {
@@ -273,47 +237,38 @@
/**
* Decodes ASN.1 Enumerated type
- *
- * @throws IOException - if error occured
*/
public void readEnumerated() throws IOException {
-
if (tag != ASN1Constants.TAG_ENUM) {
throw expected("enumerated");
}
- //
- // all checks are the same as for ASN.1 integer type
- //
-
// check encoded length
if (length == 0) {
- throw new ASN1Exception("ASN.1 enumerated: wrong length for identifier at [" + tagOffset + "]");
+ throw new ASN1Exception("ASN.1 enumerated: wrong length for identifier at ["
+ + tagOffset + "]");
}
readContent();
// check encoded content
if (length > 1) {
-
int bits = buffer[contentOffset] & 0xFF;
if (buffer[contentOffset + 1] < 0) {
bits += 0x100;
}
if (bits == 0 || bits == 0x1FF) {
- throw new ASN1Exception("ASN.1 enumerated: wrong content at [" + contentOffset + "]. An integer MUST be encoded in minimum number of octets");
+ throw new ASN1Exception("ASN.1 enumerated: wrong content at [" + contentOffset
+ + "]. An integer MUST be encoded in minimum number of octets");
}
}
}
/**
* Decodes ASN.1 boolean type
- *
- * @throws IOException - if error occured
*/
public void readBoolean() throws IOException {
-
if (tag != ASN1Constants.TAG_BOOLEAN) {
throw expected("boolean");
}
@@ -326,25 +281,19 @@
readContent();
}
- /**
- * The last choice index
- */
+ /** The last choice index */
public int choiceIndex;
- /**
- * Keeps last decoded: year, month, day, hour, minute, second, millisecond
- */
+ /** Keeps last decoded: year, month, day, hour, minute, second, millisecond */
public int[] times;
/**
* Decodes ASN.1 GeneralizedTime type
*
- * @throws IOException - if error occured
+ * @throws IOException if error occured
*/
public void readGeneralizedTime() throws IOException {
-
if (tag == ASN1Constants.TAG_GENERALIZEDTIME) {
-
// FIXME: any other optimizations?
readContent();
// FIXME store string somewhere to allow a custom time type perform
@@ -357,17 +306,17 @@
}
// check syntax: MUST be YYYYMMDDHHMMSS[(./,)DDD]'Z'
- if (length != 15 && (length < 17 || length > 19)) // invalid
- // length
- {
- throw new ASN1Exception("ASN.1 GeneralizedTime wrongly encoded at [" + contentOffset + "]");
+ if (length != 15 && (length < 17 || length > 19)) {
+ throw new ASN1Exception("ASN.1 GeneralizedTime wrongly encoded at ["
+ + contentOffset + "]");
}
// check content: milliseconds
if (length > 16) {
byte char14 = buffer[contentOffset + 14];
if (char14 != '.' && char14 != ',') {
- throw new ASN1Exception("ASN.1 GeneralizedTime wrongly encoded at [" + contentOffset + "]");
+ throw new ASN1Exception("ASN.1 GeneralizedTime wrongly encoded at ["
+ + contentOffset + "]");
}
}
@@ -403,12 +352,10 @@
/**
* Decodes ASN.1 UTCTime type
*
- * @throws IOException - if an I/O error occurs or the end of the stream is reached
+ * @throws IOException if an I/O error occurs or the end of the stream is reached
*/
public void readUTCTime() throws IOException {
-
if (tag == ASN1Constants.TAG_UTCTIME) {
-
switch (length) {
case ASN1UTCTime.UTC_HM:
case ASN1UTCTime.UTC_HMS:
@@ -461,15 +408,10 @@
}
}
- //TODO comment me
private int strToInt(int off, int count) throws ASN1Exception {
-
- //FIXME works only with buffer
-
- int c;
int result = 0;
for (int i = off, end = off + count; i < end; i++) {
- c = buffer[i] - 48;
+ int c = buffer[i] - 48;
if (c < 0 || c > 9) {
throw new ASN1Exception("Time encoding has invalid char");
}
@@ -480,11 +422,8 @@
/**
* Decodes ASN.1 Integer type
- *
- * @throws IOException - if error occured
*/
public void readInteger() throws IOException {
-
if (tag != ASN1Constants.TAG_INTEGER) {
throw expected("integer");
}
@@ -498,7 +437,6 @@
// check encoded content
if (length > 1) {
-
byte firstByte = buffer[offset - length];
byte secondByte = (byte) (buffer[offset - length + 1] & 0x80);
@@ -511,11 +449,8 @@
/**
* Decodes ASN.1 Octetstring type
- *
- * @throws IOException - if error occured
*/
public void readOctetString() throws IOException {
-
if (tag == ASN1Constants.TAG_OCTETSTRING) {
readContent();
} else if (tag == ASN1Constants.TAG_C_OCTETSTRING) {
@@ -529,16 +464,12 @@
throw new ASN1Exception("ASN.1 " + what + " identifier expected at [" + tagOffset + "], got " + Integer.toHexString(tag));
}
- //FIXME comment me
public int oidElement;
/**
* Decodes ASN.1 ObjectIdentifier type
- *
- * @throws IOException - if error occured
*/
public void readOID() throws IOException {
-
if (tag != ASN1Constants.TAG_OID) {
throw expected("OID");
}
@@ -557,18 +488,6 @@
oidElement = 1;
for (int i = 0; i < length; i++, ++oidElement) {
-
- // According to ASN.1 BER spec:
- // leading octet of subidentifier MUST not be 0x80
- // This assertion is not verified
- //
- //if (buffer[contentOffset + i] == (byte)0x80) {
- // throw new ASN1Exception(
- // "Wrong content for ASN.1 object identifier at ["
- // + contentOffset
- // + "]. Subidentifier MUST be encoded in minimum number of octets");
- //}
-
while ((buffer[contentOffset + i] & 0x80) == 0x80) {
i++;
}
@@ -577,12 +496,8 @@
/**
* Decodes ASN.1 Sequence type
- *
- * @param sequence - ASN.1 sequence to be decoded
- * @throws IOException - if error occured
*/
public void readSequence(ASN1Sequence sequence) throws IOException {
-
if (tag != ASN1Constants.TAG_C_SEQUENCE) {
throw expected("sequence");
}
@@ -618,7 +533,6 @@
}
} else {
-
int seqTagOffset = tagOffset; //store tag offset
Object[] values = new Object[type.length];
@@ -661,12 +575,8 @@
/**
* Decodes ASN.1 SequenceOf type
- *
- * @param sequenceOf - ASN.1 sequence to be decoded
- * @throws IOException - if error occured
*/
public void readSequenceOf(ASN1SequenceOf sequenceOf) throws IOException {
-
if (tag != ASN1Constants.TAG_C_SEQUENCEOF) {
throw expected("sequenceOf");
}
@@ -676,12 +586,8 @@
/**
* Decodes ASN.1 Set type
- *
- * @param set - ASN.1 set to be decoded
- * @throws IOException - if error occured
*/
public void readSet(ASN1Set set) throws IOException {
-
if (tag != ASN1Constants.TAG_C_SET) {
throw expected("set");
}
@@ -691,12 +597,8 @@
/**
* Decodes ASN.1 SetOf type
- *
- * @param set - ASN.1 set to be decoded
- * @throws IOException - if error occured
*/
public void readSetOf(ASN1SetOf setOf) throws IOException {
-
if (tag != ASN1Constants.TAG_C_SETOF) {
throw expected("setOf");
}
@@ -704,9 +606,7 @@
decodeValueCollection(setOf);
}
- private final void decodeValueCollection(ASN1ValueCollection collection)
- throws IOException {
-
+ private void decodeValueCollection(ASN1ValueCollection collection) throws IOException {
int begOffset = offset;
int endOffset = begOffset + length;
@@ -718,10 +618,9 @@
type.decode(this);
}
} else {
-
int seqTagOffset = tagOffset; //store tag offset
- ArrayList values = new ArrayList();
+ ArrayList<Object> values = new ArrayList<Object>();
while (endOffset > offset) {
next();
values.add(type.decode(this));
@@ -740,11 +639,9 @@
/**
* Decodes ASN.1 String type
*
- * @throws IOException - if an I/O error occurs or the end of the stream is reached
+ * @throws IOException if an I/O error occurs or the end of the stream is reached
*/
public void readString(ASN1StringType type) throws IOException {
-
- //FIXME check string content
if (tag == type.id) {
readContent();
} else if (tag == type.constrId) {
@@ -767,8 +664,6 @@
/**
* Returns internal buffer used for decoding
- *
- * @return - buffer
*/
public final byte[] getBuffer() {
return buffer;
@@ -776,8 +671,6 @@
/**
* Returns length of the current content for decoding
- *
- * @return - length of content
*/
public final int getLength() {
return length;
@@ -785,8 +678,6 @@
/**
* Returns the current offset
- *
- * @return - offset
*/
public final int getOffset() {
return offset;
@@ -794,8 +685,6 @@
/**
* Returns end offset for the current encoded type
- *
- * @return - offset
*/
public final int getEndOffset() {
return offset + length;
@@ -803,17 +692,11 @@
/**
* Returns start offset for the current encoded type
- *
- * @return - offset
*/
public final int getTagOffset() {
return tagOffset;
}
- public final int getContentOffset() {
- return contentOffset;
- }
-
/**
* Indicates verify or store mode.
*
@@ -845,12 +728,8 @@
/**
* Reads the next encoded byte from the encoded input stream.
- *
- * @return the next encoded byte
- * @throws IOException - if error occured
*/
protected int read() throws IOException {
-
if (offset == buffer.length) {
throw new ASN1Exception("Unexpected end of encoding");
}
@@ -872,8 +751,6 @@
/**
* Reads the next encoded content from the encoded input stream.
* The method MUST be used for reading a primitive encoded content.
- *
- * @throws IOException - if error occured
*/
public void readContent() throws IOException {
if (offset + length > buffer.length) {
@@ -902,16 +779,6 @@
}
}
- // // reallocates internal buffer for indefined reading mode
- // private void reallocateBuffer(int n) {
- // int newSize;
- // for (newSize = buffer.length * 2; newSize < buffer.length + n; newSize = newSize * 2)
- // ;
- // byte[] newBuffer = new byte[newSize];
- // System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
- // buffer = newBuffer;
- // }
-
/**
* Reallocates the buffer in order to make it
* exactly the size of data it contains
@@ -925,17 +792,9 @@
buffer = newBuffer;
}
}
-
- //
- //
- //
- //
- //
-
private Object[][] pool;
public void put(Object key, Object entry) {
-
if (pool == null) {
pool = new Object[2][10];
}
@@ -960,7 +819,6 @@
}
public Object get(Object key) {
-
if (pool == null) {
return null;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/BerOutputStream.java b/luni/src/main/java/org/apache/harmony/security/asn1/BerOutputStream.java
index f646e69..36b26bb 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/BerOutputStream.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/BerOutputStream.java
@@ -28,34 +28,21 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public class BerOutputStream {
- /**
- * Encoded byte array
- */
+ /** Encoded byte array */
public byte[] encoded;
- /**
- * current offset
- */
+ /** current offset */
protected int offset;
- /**
- * Current encoded length
- */
+ /** Current encoded length */
public int length;
- /**
- * Current encoded content
- */
+ /** Current encoded content */
public Object content;
- public BerOutputStream() {
- }
-
public final void encodeTag(int tag) {
-
encoded[offset++] = (byte) tag; //FIXME long form?
if (length > 127) { //long form
@@ -93,7 +80,7 @@
}
public void encodeBoolean() {
- if (((Boolean) content).booleanValue()) {
+ if ((Boolean) content) {
encoded[offset] = (byte) 0xFF;
} else {
encoded[offset] = 0x00;
@@ -190,10 +177,6 @@
offset += length;
}
- /*
- * LENGTH
- */
-
public void getChoiceLength(ASN1Choice choice) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
@@ -217,8 +200,4 @@
public void getSetOfLength(ASN1SetOf setOf) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
-
- public int getStringLength(Object object) {
- throw new RuntimeException("Is not implemented yet"); //FIXME
- }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/BitString.java b/luni/src/main/java/org/apache/harmony/security/asn1/BitString.java
index 64f85a4..b0579ef 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/BitString.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/BitString.java
@@ -27,7 +27,6 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public final class BitString {
private static final byte[] SET_MASK = { (byte) 128, 64, 32, 16, 8, 4, 2, 1 };
@@ -35,27 +34,19 @@
private static final byte[] RESET_MASK = { 0x7f, (byte) 0xbf, (byte) 0xdf,
(byte) 0xef, (byte) 0xf7, (byte) 0xfb, (byte) 0xfd, (byte) 0xfe, };
- /**
- * Sequence of bits padded with unused bits.
- * @see #unusedBits
- */
+ /** Sequence of bits padded with unused bits. */
public final byte[] bytes;
- /**
- * Number of unused bits in the last byte.
- */
+ /** Number of unused bits in the last byte. */
public final int unusedBits;
/**
- * Constructs bit string
- *
- * @param bytes - array of bytes that represents bit string,
+ * @param bytes array of bytes that represents bit string,
* including unused bits
- * @param unusedBits - number of unused bits
+ * @param unusedBits number of unused bits
* @throws IllegalArgumentException - if parameters are invalid
*/
public BitString(byte[] bytes, int unusedBits) {
-
// constraints are set according X.690
if (unusedBits < 0 || unusedBits > 7) {
throw new IllegalArgumentException("Number of unused bits MUST be in range 0-7");
@@ -69,11 +60,6 @@
this.unusedBits = unusedBits;
}
- /**
- * Constructs bit string from array of booleans
- *
- * @param values - array of booleans
- */
public BitString(boolean[] values) {
unusedBits = values.length % 8;
int size = values.length / 8;
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/DerInputStream.java b/luni/src/main/java/org/apache/harmony/security/asn1/DerInputStream.java
index 0000952..1fddb82 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/DerInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/DerInputStream.java
@@ -30,15 +30,17 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public final class DerInputStream extends BerInputStream {
+ /** mask for verifying unused bits for ASN.1 bitstring */
+ private static final byte[] UNUSED_BITS_MASK = new byte[] { 0x01, 0x03,
+ 0x07, 0x0F, 0x1F, 0x3F, 0x7F };
+
public DerInputStream(byte[] encoded) throws IOException {
super(encoded, 0, encoded.length);
}
- public DerInputStream(byte[] encoded, int offset, int encodingLen)
- throws IOException {
+ public DerInputStream(byte[] encoded, int offset, int encodingLen) throws IOException {
super(encoded, offset, encodingLen);
}
@@ -46,11 +48,7 @@
super(in);
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#next()
- */
- public final int next() throws IOException {
-
+ public int next() throws IOException {
int tag = super.next();
if (length == INDEFINIT_LENGTH) {
@@ -62,18 +60,10 @@
return tag;
}
- // mask for verifying unused bits for ASN.1 bitstring
- private static final byte[] UNUSED_BITS_MASK = new byte[] { 0x01, 0x03,
- 0x07, 0x0F, 0x1F, 0x3F, 0x7F };
-
-
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readBitString()
- */
public void readBitString() throws IOException {
-
if (tag == ASN1Constants.TAG_C_BITSTRING) {
- throw new ASN1Exception("ASN.1 bitstring: constructed identifier at [" + tagOffset + "]. Not valid for DER.");
+ throw new ASN1Exception("ASN.1 bitstring: constructed identifier at [" + tagOffset
+ + "]. Not valid for DER.");
}
super.readBitString();
@@ -82,37 +72,29 @@
if (length > 1
&& buffer[contentOffset] != 0
&& (buffer[offset - 1] & UNUSED_BITS_MASK[buffer[contentOffset] - 1]) != 0) {
- throw new ASN1Exception("ASN.1 bitstring: wrong content at [" + contentOffset + "]. DER requires zero unused bits in final octet.");
+ throw new ASN1Exception("ASN.1 bitstring: wrong content at [" + contentOffset
+ + "]. DER requires zero unused bits in final octet.");
}
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readBoolean()
- */
public void readBoolean() throws IOException {
-
super.readBoolean();
// check encoded content
if (buffer[contentOffset] != 0 && buffer[contentOffset] != (byte) 0xFF) {
- throw new ASN1Exception("ASN.1 boolean: wrong content at [" + contentOffset + "]. DER allows only 0x00 or 0xFF values");
+ throw new ASN1Exception("ASN.1 boolean: wrong content at [" + contentOffset
+ + "]. DER allows only 0x00 or 0xFF values");
}
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readOctetString()
- */
public void readOctetString() throws IOException {
-
if (tag == ASN1Constants.TAG_C_OCTETSTRING) {
- throw new ASN1Exception("ASN.1 octetstring: constructed identifier at [" + tagOffset + "]. Not valid for DER.");
+ throw new ASN1Exception("ASN.1 octetstring: constructed identifier at [" + tagOffset
+ + "]. Not valid for DER.");
}
super.readOctetString();
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readSequence(org.apache.harmony.security.asn1.ASN1Sequence)
- */
public void readSequence(ASN1Sequence sequence) throws IOException {
//
// According to ASN.1 DER spec. sequence MUST not include
@@ -123,9 +105,6 @@
super.readSequence(sequence);
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readSetOf(org.apache.harmony.security.asn1.ASN1SetOf)
- */
public void readSetOf(ASN1SetOf setOf) throws IOException {
//
// According to ASN.1 DER spec. set of MUST appear in
@@ -136,63 +115,37 @@
super.readSetOf(setOf);
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readString(ASN1StringType)
- */
public void readString(ASN1StringType type) throws IOException {
-
if (tag == type.constrId) {
- throw new ASN1Exception("ASN.1 string: constructed identifier at [" + tagOffset + "]. Not valid for DER.");
+ throw new ASN1Exception("ASN.1 string: constructed identifier at [" + tagOffset
+ + "]. Not valid for DER.");
}
super.readString(type);
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readUTCTime()
- */
public void readUTCTime() throws IOException {
-
if (tag == ASN1Constants.TAG_C_UTCTIME) {
// It is a string type and it can be encoded as primitive or constructed.
- throw new ASN1Exception("ASN.1 UTCTime: constructed identifier at [" + tagOffset + "]. Not valid for DER.");
+ throw new ASN1Exception("ASN.1 UTCTime: constructed identifier at [" + tagOffset
+ + "]. Not valid for DER.");
}
// check format: DER uses YYMMDDHHMMSS'Z' only
if (length != ASN1UTCTime.UTC_HMS) {
- throw new ASN1Exception("ASN.1 UTCTime: wrong format for DER, identifier at [" + tagOffset + "]");
+ throw new ASN1Exception("ASN.1 UTCTime: wrong format for DER, identifier at ["
+ + tagOffset + "]");
}
super.readUTCTime();
}
- /**
- * @see org.apache.harmony.security.asn1.BerInputStream#readGeneralizedTime()
- */
public void readGeneralizedTime() throws IOException {
-
if (tag == ASN1Constants.TAG_C_GENERALIZEDTIME) {
// It is a string type and it can be encoded as primitive or constructed.
- throw new ASN1Exception("ASN.1 GeneralizedTime: constructed identifier at [" + tagOffset + "]. Not valid for DER.");
+ throw new ASN1Exception("ASN.1 GeneralizedTime: constructed identifier at ["
+ + tagOffset + "]. Not valid for DER.");
}
super.readGeneralizedTime();
-
- // FIXME makes sense only if we support all GeneralizedTime formats
- // late check syntax: the last char MUST be Z
- //if (buffer[offset - 1] != 'Z') {
- // throw new ASN1Exception(
- // "ASN.1 GeneralizedTime wrongly encoded at ["
- // + contentOffset + ']');
- //}
-
- // the fractional-seconds elements, if present MUST
- // omit all trailing zeros
- // FIXME implement me
- // if () {
- // throw new IOException(
- // "DER ASN.1 GeneralizedTime wrongly encoded at ["
- // + contentOffset
- // + "]. Trailing zeros MUST be omitted");
- // }
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/DerOutputStream.java b/luni/src/main/java/org/apache/harmony/security/asn1/DerOutputStream.java
index 84030e7..e9c4ab7 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/DerOutputStream.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/DerOutputStream.java
@@ -30,46 +30,36 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public final class DerOutputStream extends BerOutputStream {
+ private static final int initSize = 32;
+ private int index;
+ private int[][] len = new int[initSize][];
+ private Object[][] val = new Object[initSize][];
public DerOutputStream(ASN1Type asn1, Object object) {
- super();
-
content = object;
-
index = -1;
asn1.setEncodingContent(this);
-
encoded = new byte[asn1.getEncodedLength(this)];
-
index = 0;
asn1.encodeASN(this);
}
- public void encodeChoice(ASN1Choice choice) {
-
+ @Override public void encodeChoice(ASN1Choice choice) {
ASN1Type type = (ASN1Type) val[index][0];
-
content = val[index][1];
-
index++;
-
type.encodeASN(this);
}
- public void encodeExplicit(ASN1Explicit explicit) {
-
+ @Override public void encodeExplicit(ASN1Explicit explicit) {
content = val[index][0];
length = len[index][0];
-
index++;
-
explicit.type.encodeASN(this);
}
- public void encodeSequence(ASN1Sequence sequence) {
-
+ @Override public void encodeSequence(ASN1Sequence sequence) {
ASN1Type[] type = sequence.type;
Object[] values = val[index];
@@ -77,7 +67,6 @@
index++;
for (int i = 0; i < type.length; i++) {
-
if (values[i] == null) {
continue;
}
@@ -89,43 +78,27 @@
}
}
- public void encodeSequenceOf(ASN1SequenceOf sequenceOf) {
+ @Override public void encodeSequenceOf(ASN1SequenceOf sequenceOf) {
encodeValueCollection(sequenceOf);
}
- public void encodeSetOf(ASN1SetOf setOf) {
+ @Override public void encodeSetOf(ASN1SetOf setOf) {
encodeValueCollection(setOf);
}
- private final void encodeValueCollection(ASN1ValueCollection collection) {
-
+ private void encodeValueCollection(ASN1ValueCollection collection) {
Object[] values = val[index];
int[] compLens = len[index];
index++;
for (int i = 0; i < values.length; i++) {
-
content = values[i];
length = compLens[i];
-
collection.type.encodeASN(this);
}
}
- /*
- * DATA
- */
-
- private final static int initSize = 32;
-
- private int index;
-
- private int[][] len = new int[initSize][];
-
- private Object[][] val = new Object[initSize][];
-
private void push(int[] lengths, Object[] values) {
-
index++;
if (index == val.length) {
@@ -141,12 +114,7 @@
val[index] = values;
}
- /*
- * LENGTH
- */
-
- public void getChoiceLength(ASN1Choice choice) {
-
+ @Override public void getChoiceLength(ASN1Choice choice) {
int i = choice.getIndex(content);
content = choice.getObjectToEncode(content);
@@ -161,8 +129,7 @@
values[1] = content;
}
- public void getExplicitLength(ASN1Explicit explicit) {
-
+ @Override public void getExplicitLength(ASN1Explicit explicit) {
Object[] values = new Object[1];
int[] compLens = new int[1];
@@ -180,8 +147,7 @@
length = explicit.type.getEncodedLength(this);
}
- public void getSequenceLength(ASN1Sequence sequence) {
-
+ @Override public void getSequenceLength(ASN1Sequence sequence) {
ASN1Type[] type = sequence.type;
Object[] values = new Object[type.length];
@@ -222,16 +188,15 @@
length = seqLen;
}
- public void getSequenceOfLength(ASN1SequenceOf sequence) {
+ @Override public void getSequenceOfLength(ASN1SequenceOf sequence) {
getValueOfLength(sequence);
}
- public void getSetOfLength(ASN1SetOf setOf) {
+ @Override public void getSetOfLength(ASN1SetOf setOf) {
getValueOfLength(setOf);
}
private void getValueOfLength(ASN1ValueCollection collection) {
-
//FIXME what about another way?
Object[] cv = collection.getValues(content).toArray();
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/InformationObjectSet.java b/luni/src/main/java/org/apache/harmony/security/asn1/InformationObjectSet.java
deleted file mode 100644
index c652543..0000000
--- a/luni/src/main/java/org/apache/harmony/security/asn1/InformationObjectSet.java
+++ /dev/null
@@ -1,107 +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.
- */
-
-/**
-* @author Stepan M. Mishura
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.asn1;
-
-import java.util.Arrays;
-import org.apache.harmony.security.x501.AttributeType;
-
-
-/**
- * Represents Information Object Set.
- *
- * @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
- */
-
-public class InformationObjectSet {
-
- private final int capacity;
-
- private final Entry[][] pool;
-
- public InformationObjectSet() {
- this(64, 10);
- }
-
- public InformationObjectSet(int capacity, int size) {
- this.capacity = capacity;
- pool = new Entry[capacity][size];
- }
-
- public void put(AttributeType at) {
- put(at.oid.getOid(), at);
- }
-
- public void put(int[] oid, Object object) {
-
- int index = hashIntArray(oid) % capacity;
- // look for OID in the pool
- Entry[] list = pool[index];
- int i = 0;
- for (; list[i] != null; i++) {
-
- // check wrong static initialization: no duplicate OIDs
- if (Arrays.equals(oid, list[i].oid)) {
- throw new Error(); //FIXME message
- }
- }
-
- // check : to avoid NPE
- if (i == (capacity - 1)) {
- throw new Error(); //FIXME message
- }
- list[i] = new Entry(oid, object);
- }
-
- public Object get(int[] oid) {
- int index = hashIntArray(oid) % capacity;
-
- // look for OID in the pool
- Entry[] list = pool[index];
- for (int i = 0; list[i] != null; i++) {
- if (Arrays.equals(oid, list[i].oid)) {
- return list[i].object;
- }
- }
- return null;
- }
-
- // FIXME change me to Arrays.hashCode(int[])
- private int hashIntArray(int[] array) {
- int intHash = 0;
- for (int i = 0; i < array.length && i < 4; i++) {
- intHash += array[i] << (8 * i); //TODO what about to find better one?
- }
- return intHash & 0x7FFFFFFF; // only positive
- }
-
- private static class Entry {
- public int[] oid;
-
- public Object object;
-
- public Entry(int[] oid, Object object) {
- this.oid = oid;
- this.object = object;
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ObjectIdentifier.java b/luni/src/main/java/org/apache/harmony/security/asn1/ObjectIdentifier.java
index 199f30c..24140e5 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ObjectIdentifier.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ObjectIdentifier.java
@@ -38,20 +38,19 @@
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
-
public final class ObjectIdentifier {
- // OID as array of integers
+ /** OID as array of integers */
private final int[] oid;
- // OID as string
+ /** OID as string */
private String soid;
/**
* Creates ObjectIdentifier(OID) from array of integers.
*
- * @param oid - array of integers
- * @throws IllegalArgumentException - if oid is invalid or null
+ * @param oid array of integers
+ * @throws IllegalArgumentException if oid is invalid or null
*/
public ObjectIdentifier(int[] oid) {
validate(oid);
@@ -61,30 +60,15 @@
/**
* Creates ObjectIdentifier(OID) from string representation.
*
- * @param strOid - oid string
- * @throws IllegalArgumentException - if oid string is invalid or null
+ * @param strOid oid string
+ * @throws IllegalArgumentException if oid string is invalid or null
*/
public ObjectIdentifier(String strOid) {
this.oid = toIntArray(strOid);
this.soid = strOid;
}
- /**
- * Returns array of integers.
- *
- * @return array of integers
- */
- public int[] getOid() {
- return oid;
- }
-
- /**
- * Compares object with OID for equality.
- *
- * @return true if object is ObjectIdentifier and it has the same
- * representation as array of integers, otherwise false
- */
- public boolean equals(Object o) {
+ @Override public boolean equals(Object o) {
if (this == o) {
return true;
}
@@ -94,20 +78,14 @@
return Arrays.equals(oid, ((ObjectIdentifier) o).oid);
}
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
+ @Override public String toString() {
if (soid == null) {
soid = toString(oid);
}
return soid;
}
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
+ @Override public int hashCode() {
// FIXME change me to Arrays.hashCode(int[])
int intHash = 0;
for (int i = 0; i < oid.length && i < 4; i++) {
@@ -119,11 +97,10 @@
/**
* Validates ObjectIdentifier (OID).
*
- * @param oid - oid as array of integers
- * @throws IllegalArgumentException - if oid is invalid or null
+ * @param oid oid as array of integers
+ * @throws IllegalArgumentException if oid is invalid or null
*/
public static void validate(int[] oid) {
-
if (oid == null) {
throw new IllegalArgumentException("oid == null");
}
@@ -133,107 +110,27 @@
}
if (oid[0] > 2) {
- throw new IllegalArgumentException("Valid values for first subidentifier are 0, 1 and 2");
+ throw new IllegalArgumentException(
+ "Valid values for first subidentifier are 0, 1 and 2");
} else if (oid[0] != 2 && oid[1] > 39) {
- throw new IllegalArgumentException("If the first subidentifier has 0 or 1 value the second subidentifier value MUST be less than 40");
+ throw new IllegalArgumentException("If the first subidentifier has 0 or 1 value the "
+ + "second subidentifier value MUST be less than 40");
}
- for (int i = 0; i < oid.length; i++) {
- if (oid[i] < 0) {
+ for (int anOid : oid) {
+ if (anOid < 0) {
throw new IllegalArgumentException("Subidentifier MUST have positive value");
}
}
}
- // FIXME: implement me
- // /**
- // * Validates ObjectIdentifier (OID).
- // *
- // * @param oid - oid as string
- // * @throws IllegalArgumentException - if oid string is invalid or null
- // */
- // public static void validate(String oid) {
- //
- // if (oid == null) {
- // throw new NullPointerException();
- // }
- //
- // int length = oid.length();
- // if (length < 3 || oid.charAt(1) != '.') {
- // throw new IllegalArgumentException("Invalid oid string");
- // }
- //
- // int pos = 2;
- // int subidentifier = 0;
- // switch (oid.charAt(0)) {
- // case '0':
- // case '1':
- // for (char c = oid.charAt(pos);;) {
- // if (c < '0' || c > '9') {
- // throw new IllegalArgumentException("Invalid oid string");
- // } else {
- // subidentifier = subidentifier * 10 + c - '0';
- // }
- //
- // pos++;
- // if (pos == length) {
- // break;
- // }
- //
- // c = oid.charAt(pos);
- // if (c == '.') {
- // pos++;
- // if (pos == length) {
- // throw new IllegalArgumentException("Invalid oid string");
- // }
- // break;
- // }
- // }
- //
- // if (subidentifier > 39) {
- // throw new IllegalArgumentException(
- // "If the first subidentifier has 0 or 1 value the second "
- // + "subidentifier value MUST be less then 40.");
- // }
- // break;
- // case '2':
- // break;
- // default:
- // throw new IllegalArgumentException(
- // "Valid values for first subidentifier are 0, 1 and 2");
- // }
- //
- // if (pos == length) {
- // return;
- // }
- //
- // for (char c = oid.charAt(pos);;) {
- // if (c < '0' || c > '9') {
- // throw new IllegalArgumentException("Invalid oid string");
- // }
- //
- // pos++;
- // if (pos == length) {
- // return;
- // }
- //
- // c = oid.charAt(pos);
- // if (c == '.') {
- // pos++;
- // if (pos == length) {
- // throw new IllegalArgumentException("Invalid oid string");
- // }
- // }
- // }
- // }
-
/**
* Returns string representation of OID.
*
* Note: it is supposed that passed array of integers
* contains valid OID value, so no checks are performed.
*
- * @param oid - oid as array of integers
+ * @param oid oid as array of integers
* @return oid string representation
*/
public static String toString(int[] oid) {
@@ -247,7 +144,6 @@
return sb.toString();
}
- // BEGIN android-changed
/**
* Gets ObjectIdentifier (OID) from string representation.
*
@@ -255,9 +151,9 @@
* OID = subidentifier 1*("." subidentifier)
* subidentifier = 1*(digit)
*
- * @param oidString - string representation of OID
- * @return - oid as array of integers
- * @throws IllegalArgumentException - if oid string is invalid or null
+ * @param str string representation of OID
+ * @return oid as array of integers
+ * @throws IllegalArgumentException if oid string is invalid or null
*/
public static int[] toIntArray(String str) {
return toIntArray(str, true);
@@ -269,7 +165,7 @@
*
* String representation is defined as for {@link #toIntArray}.
*
- * @param oidString - string representation of OID
+ * @param str string representation of OID
* @return true if oidString has valid syntax or false if not
*/
public static boolean isOID(String str) {
@@ -283,10 +179,10 @@
* OID = subidentifier 1*("." subidentifier)
* subidentifier = 1*(digit)
*
- * @param oidString - string representation of OID
- * @return - oid as array of integers or null if the oid string is
+ * @param str string representation of OID
+ * @return oid as array of integers or null if the oid string is
* invalid or null and shouldThrow is false
- * @throws IllegalArgumentException - if oid string is invalid or null and
+ * @throws IllegalArgumentException if oid string is invalid or null and
* shouldThrow is true
*/
private static int[] toIntArray(String str, boolean shouldThrow) {
@@ -368,5 +264,4 @@
return oid;
}
- // END android-changed
}
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java b/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java
index ebdce53..8d07013 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicy.java
@@ -24,7 +24,6 @@
import java.io.File;
import java.net.URL;
-import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
@@ -270,8 +269,7 @@
*/
public synchronized void refresh() {
Set<PolicyEntry> fresh = new HashSet<PolicyEntry>();
- Properties system = new Properties(AccessController
- .doPrivileged(new PolicyUtils.SystemKit()));
+ Properties system = System.getProperties();
system.setProperty("/", File.separator);
URL[] policyLocations = PolicyUtils.getPolicyURLs(system,
JAVA_SECURITY_POLICY,
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java b/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java
index 9857680..7f55e6f 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/DefaultPolicyParser.java
@@ -27,7 +27,6 @@
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
-import java.security.AccessController;
import java.security.CodeSource;
import java.security.KeyStore;
import java.security.KeyStoreException;
@@ -44,7 +43,6 @@
import java.util.List;
import java.util.Properties;
import java.util.Set;
-import java.util.StringTokenizer;
import org.apache.harmony.security.DefaultPolicyScanner;
import org.apache.harmony.security.DefaultPolicyScanner.GrantEntry;
import org.apache.harmony.security.DefaultPolicyScanner.KeystoreEntry;
@@ -108,15 +106,9 @@
* @return a collection of PolicyEntry objects, may be empty
* @throws Exception IO error while reading location or file syntax error
*/
- public Collection<PolicyEntry>parse(URL location, Properties system)
- throws Exception {
-
+ public Collection<PolicyEntry>parse(URL location, Properties system) throws Exception {
boolean resolve = PolicyUtils.canExpandProperties();
- Reader r =
- new BufferedReader(
- new InputStreamReader(
- AccessController.doPrivileged(
- new PolicyUtils.URLLoader(location))));
+ Reader r = new BufferedReader(new InputStreamReader(location.openStream()));
Collection<GrantEntry> grantEntries = new HashSet<GrantEntry>();
List<KeystoreEntry> keystores = new ArrayList<KeystoreEntry>();
@@ -381,17 +373,15 @@
* @throws Exception if KeyStore is <code>null</code>
* or if it failed to provide a certificate
*/
- protected Certificate[] resolveSigners(KeyStore ks, String signers)
- throws Exception {
+ protected Certificate[] resolveSigners(KeyStore ks, String signers) throws Exception {
if (ks == null) {
throw new KeyStoreException("No KeyStore to resolve signers: " + signers);
}
Collection<Certificate> certs = new HashSet<Certificate>();
- StringTokenizer snt = new StringTokenizer(signers, ",");
- while (snt.hasMoreTokens()) {
+ for (String signer : signers.split(",")) {
//XXX cache found certs ??
- certs.add(ks.getCertificate(snt.nextToken().trim()));
+ certs.add(ks.getCertificate(signer.trim()));
}
return certs.toArray(new Certificate[certs.size()]);
}
@@ -456,8 +446,7 @@
}
KeyStore ks = KeyStore.getInstance(ke.type);
URL location = new URL(base, ke.url);
- InputStream is = AccessController
- .doPrivileged(new PolicyUtils.URLLoader(location));
+ InputStream is = location.openStream();
try {
ks.load(is, null);
}
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 7dbc476..d5e925e 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
@@ -24,7 +24,7 @@
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
-import org.apache.harmony.security.Util;
+import java.util.Locale;
/**
@@ -138,18 +138,14 @@
Provider.Service service;
ServiceCacheEntry cacheEntry = this.serviceCache;
if (cacheEntry != null
- && Util.equalsIgnoreCase(algorithm, cacheEntry.algorithm)
+ && cacheEntry.algorithm.equalsIgnoreCase(algorithm)
&& Services.refreshNumber != cacheEntry.refreshNumber) {
service = cacheEntry.service;
} else {
if (Services.isEmpty()) {
throw notFound(serviceName, algorithm);
}
- String name = new StringBuilder(128)
- .append(this.serviceName)
- .append(".")
- .append(Util.toUpperCase(algorithm))
- .toString();
+ String name = this.serviceName + "." + algorithm.toUpperCase(Locale.US);
service = Services.getService(name);
if (service == null) {
throw notFound(serviceName, algorithm);
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java b/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java
index 43bc44a..c22314b 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/PolicyUtils.java
@@ -28,19 +28,15 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
-import java.security.AccessController;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
-import java.security.PrivilegedAction;
-import java.security.PrivilegedExceptionAction;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
-import org.apache.harmony.security.Util;
/**
* This class consist of a number of static methods, which provide a common functionality
@@ -53,166 +49,6 @@
private PolicyUtils() {}
/**
- * Auxiliary action for opening InputStream from specified location.
- */
- public static class URLLoader implements PrivilegedExceptionAction<InputStream> {
-
- /**
- * URL of target location.
- */
- public URL location;
-
- /**
- * Constructor with target URL parameter.
- */
- public URLLoader(URL location) {
- this.location = location;
- }
-
- /**
- * Returns InputStream from the target URL.
- */
- public InputStream run() throws Exception {
- return location.openStream();
- }
- }
-
- /**
- * Auxiliary action for accessing system properties in a bundle.
- */
- public static class SystemKit implements PrivilegedAction<Properties> {
-
- /**
- * Returns system properties.
- */
- public Properties run() {
- return System.getProperties();
- }
- }
-
- /**
- * Auxiliary action for accessing specific system property.
- */
- public static class SystemPropertyAccessor implements PrivilegedAction<String> {
-
- /**
- * A key of a required system property.
- */
- public String key;
-
- /**
- * Constructor with a property key parameter.
- */
- public SystemPropertyAccessor(String key) {
- this.key = key;
- }
-
- /**
- * Handy one-line replacement of
- * "provide key and supply action" code block,
- * for reusing existing action instance.
- */
- public PrivilegedAction<String> key(String key) {
- this.key = key;
- return this;
- }
-
- /**
- * Returns specified system property.
- */
- public String run() {
- return System.getProperty(key);
- }
- }
-
- /**
- * Auxiliary action for accessing specific security property.
- */
- public static class SecurityPropertyAccessor implements PrivilegedAction<String> {
-
- private String key;
-
- /**
- * Constructor with a property key parameter.
- */
- public SecurityPropertyAccessor(String key) {
- super();
- this.key = key;
- }
-
- public PrivilegedAction<String> key(String key) {
- this.key = key;
- return this;
- }
-
- /**
- * Returns specified security property.
- */
- public String run() {
- return Security.getProperty(key);
- }
- }
-
- /**
- * Auxiliary action for loading a provider by specific security property.
- */
- public static class ProviderLoader<T> implements PrivilegedAction<T> {
-
- private String key;
-
- /**
- * Acceptable provider superclass.
- */
- private Class<T> expectedType;
-
- /**
- * Constructor taking property key and acceptable provider
- * superclass parameters.
- */
- public ProviderLoader(String key, Class<T> expected) {
- super();
- this.key = key;
- this.expectedType = expected;
- }
-
- /**
- * Returns provider instance by specified security property.
- * The <code>key</code> should map to a fully qualified classname.
- *
- * @throws SecurityException if no value specified for the key
- * in security properties or if an Exception has occurred
- * during classloading and instantiating.
- */
- public T run() {
- String klassName = Security.getProperty(key);
- if (klassName == null || klassName.length() == 0) {
- throw new SecurityException("Provider implementation should be specified via '" +
- key + "' security property");
- }
- // TODO accurate classloading
- try {
- Class<?> klass = Class.forName(klassName, true,
- Thread.currentThread().getContextClassLoader());
- if (expectedType != null && klass.isAssignableFrom(expectedType)){
- throw new SecurityException("Provided class " + klassName +
- " does not implement " + expectedType.getName());
- }
- //FIXME expectedType.cast(klass.newInstance());
- return (T)klass.newInstance();
- }
- catch (SecurityException se){
- throw se;
- }
- catch (Exception e) {
- // TODO log error ??
- SecurityException se = new SecurityException("Unable to instantiate provider: " + klassName);
- se.initCause(e);
- throw se;
- }
- }
- }
-
- /**
* Specific exception to signal that property expansion failed
* due to unknown key.
*/
@@ -421,8 +257,7 @@
* @see #expand(String, Properties)
*/
public static boolean canExpandProperties() {
- return !Util.equalsIgnoreCase(FALSE,AccessController
- .doPrivileged(new SecurityPropertyAccessor(POLICY_EXPAND)));
+ return !Security.getProperty(POLICY_EXPAND).equalsIgnoreCase(FALSE);
}
/**
@@ -460,15 +295,12 @@
public static URL[] getPolicyURLs(final Properties system,
final String systemUrlKey, final String securityUrlPrefix) {
- final SecurityPropertyAccessor security = new SecurityPropertyAccessor(
- null);
final List<URL> urls = new ArrayList<URL>();
boolean dynamicOnly = false;
URL dynamicURL = null;
//first check if policy is set via system properties
- if (!Util.equalsIgnoreCase(FALSE, AccessController
- .doPrivileged(security.key(POLICY_ALLOW_DYNAMIC)))) {
+ if (!Security.getProperty(POLICY_ALLOW_DYNAMIC).equalsIgnoreCase(FALSE)) {
String location = system.getProperty(systemUrlKey);
if (location != null) {
if (location.startsWith("=")) {
@@ -480,17 +312,10 @@
location = expandURL(location, system);
// location can be a file, but we need an url...
final File f = new File(location);
- dynamicURL = AccessController
- .doPrivileged(new PrivilegedExceptionAction<URL>() {
-
- public URL run() throws Exception {
- if (f.exists()) {
- return f.toURI().toURL();
- } else {
- return null;
- }
- }
- });
+ dynamicURL = null;
+ if (f.exists()) {
+ dynamicURL = f.toURI().toURL();
+ }
if (dynamicURL == null) {
dynamicURL = new URL(location);
}
@@ -505,9 +330,7 @@
if (!dynamicOnly) {
int i = 1;
while (true) {
- String location = AccessController
- .doPrivileged(security.key(new StringBuilder(
- securityUrlPrefix).append(i++).toString()));
+ String location = Security.getProperty(securityUrlPrefix + (i++));
if (location == null) {
break;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java b/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java
index 933bf83..c63a57db 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/SecurityUtils.java
@@ -25,18 +25,10 @@
import java.security.AccessControlContext;
import java.util.WeakHashMap;
-//FIXME: move this class under umbrella of protected packages -
-// see lib/java.security: property 'package.access',
-// so only trusted classes like Thread and AccessController will
-// have an access to this class.
-// This is to remove dependency on VMStack, to reduce number
-// of VM2API-dependent classes.
-
/**
* The class is used to perform an exchange of information between
* java.lang.Thread and java.security.AccessController.<br>
- * The data to exchange is inherited contexts for the Thread-s.
- *
+ * The data to exchange is inherited contexts for the Threads.
*/
public final class SecurityUtils {
@@ -94,17 +86,7 @@
* It may also return null if no Thread found in the map - that seems
* possible during VM startup process.
*/
- public static AccessControlContext getContext(Thread thread)
- throws SecurityException {
-
- // ~fixme: see 'fixme' at the top of the file
- /*
- Class cl = VMStack.getCallerClass(0);
- if (cl != AccessController.class) {
- throw new SecurityException("You ["+cl+"] do not have access to this resource.");
- }
- */
-
+ public static AccessControlContext getContext(Thread thread) throws SecurityException {
synchronized (ACC_CACHE) {
return ACC_CACHE.get(thread);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/fortress/Services.java b/luni/src/main/java/org/apache/harmony/security/fortress/Services.java
index 7c2cff2..d97e0f4 100644
--- a/luni/src/main/java/org/apache/harmony/security/fortress/Services.java
+++ b/luni/src/main/java/org/apache/harmony/security/fortress/Services.java
@@ -22,15 +22,13 @@
package org.apache.harmony.security.fortress;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
-import org.apache.harmony.security.Util;
/**
@@ -42,16 +40,14 @@
public class Services {
// The HashMap that contains information about preferred implementations for
- // all serviceName.algName in the registered providers
- // BEGIN android-changed
- // set the initial size to 600 so we don't grow to 1024 by default because
+ // all serviceName.algName in the registered providers.
+ // Set the initial size to 600 so we don't grow to 1024 by default because
// initialization adds a few entries more than the growth threshold.
private static final Map<String, Provider.Service> services
= new HashMap<String, Provider.Service>(600);
- // save default SecureRandom service as well.
- // avoids similar provider/services iteration in SecureRandom constructor
+ // Save default SecureRandom service as well.
+ // Avoids similar provider/services iteration in SecureRandom constructor
private static Provider.Service secureRandom;
- // END android-changed
// Need refresh flag
private static boolean needRefresh; // = false;
@@ -66,14 +62,8 @@
// Hash for quick provider access by name
private static final Map<String, Provider> providersNames = new HashMap<String, Provider>(20);
-
static {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- loadProviders();
- return null;
- }
- });
+ loadProviders();
}
// Load statically registered providers and init Services Info
@@ -167,23 +157,17 @@
* @param p
*/
public static void initServiceInfo(Provider p) {
- StringBuilder sb = new StringBuilder(128);
-
for (Provider.Service serv : p.getServices()) {
String type = serv.getType();
if (secureRandom == null && type.equals("SecureRandom")) {
secureRandom = serv;
}
- sb.delete(0, sb.length());
- String key = sb.append(type).append(".").append(
- Util.toUpperCase(serv.getAlgorithm())).toString();
+ String key = type + "." + serv.getAlgorithm().toUpperCase(Locale.US);
if (!services.containsKey(key)) {
services.put(key, serv);
}
for (String alias : Engine.door.getAliases(serv)) {
- sb.delete(0, sb.length());
- key = sb.append(type).append(".").append(Util.toUpperCase(alias))
- .toString();
+ key = type + "." + alias.toUpperCase(Locale.US);
if (!services.containsKey(key)) {
services.put(key, serv);
}
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequest.java b/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequest.java
index 7af53e6..3d36d37 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequest.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequest.java
@@ -38,52 +38,37 @@
*
* Signature ::= BIT STRING
*/
-public class CertificationRequest {
+public final class CertificationRequest {
- // the value of certificationRequestInfo field of the structure
+ /** the value of certificationRequestInfo field of the structure */
private CertificationRequestInfo info;
- // the value of signatureAlgorithm field of the structure
+ /** the value of signatureAlgorithm field of the structure */
private AlgorithmIdentifier algId;
- // the value of signature field of the structure
+ /** the value of signature field of the structure */
private byte[] signature;
- // the ASN.1 encoded form of CertificationRequest
+ /** the ASN.1 encoded form of CertificationRequest */
private byte[] encoding;
public CertificationRequest(CertificationRequestInfo info,
AlgorithmIdentifier algId, byte[] signature) {
this.info = info;
this.algId = algId;
- this.signature = new byte[signature.length];
- System.arraycopy(signature, 0, this.signature, 0, signature.length);
+ this.signature = signature.clone();
}
- // private constructor with encoding given
private CertificationRequest(CertificationRequestInfo info,
AlgorithmIdentifier algId, byte[] signature, byte[] encoding) {
this(info, algId, signature);
this.encoding = encoding;
}
- /**
- * @return Returns the algId.
- */
- public AlgorithmIdentifier getAlgId() {
- return algId;
- }
-
- /**
- * @return Returns the info.
- */
public CertificationRequestInfo getInfo() {
return info;
}
- /**
- * @return Returns the signature.
- */
public byte[] getSignature() {
byte[] result = new byte[signature.length];
System.arraycopy(signature, 0, result, 0, signature.length);
@@ -109,7 +94,6 @@
public Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
-
return new CertificationRequest(
(CertificationRequestInfo) values[0],
(AlgorithmIdentifier) values[1],
@@ -119,7 +103,6 @@
protected void getValues(Object object, Object[] values) {
CertificationRequest certReq = (CertificationRequest) object;
-
values[0] = certReq.info;
values[1] = certReq.algId;
values[2] = new BitString(certReq.signature, 0);
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequestInfo.java b/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequestInfo.java
index d90b446..d13f952 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequestInfo.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs10/CertificationRequestInfo.java
@@ -30,72 +30,44 @@
import org.apache.harmony.security.x509.SubjectPublicKeyInfo;
/**
- CertificationRequestInfo ::= SEQUENCE {
- version Version,
- subject Name,
- subjectPublicKeyInfo SubjectPublicKeyInfo,
- attributes [0] IMPLICIT Attributes }
+ * CertificationRequestInfo ::= SEQUENCE {
+ * version Version,
+ * subject Name,
+ * subjectPublicKeyInfo SubjectPublicKeyInfo,
+ * attributes [0] IMPLICIT Attributes }
+ *
+ * Version ::= INTEGER
+ *
+ * Attributes ::= SET OF Attribute
+ */
+public final class CertificationRequestInfo {
+ private final int version;
- Version ::= INTEGER
+ /** the value of subject field of the structure */
+ private final Name subject;
- Attributes ::= SET OF Attribute
-*/
+ /** the value of subjectPublicKeyInfo field of the structure */
+ private final SubjectPublicKeyInfo subjectPublicKeyInfo;
-public class CertificationRequestInfo {
- // version
- private int version;
+ /** the value of attributes field of the structure */
+ private final List<?> attributes;
- // the value of subject field of the structure
- private Name subject;
+ /** the ASN.1 encoded form of CertificationRequestInfo */
+ private byte[] encoding;
- // the value of subjectPublicKeyInfo field of the structure
- private SubjectPublicKeyInfo subjectPublicKeyInfo;
-
- // the value of attributes field of the structure
- private List attributes;
-
- // the ASN.1 encoded form of CertificationRequestInfo
- private byte [] encoding;
-
- public CertificationRequestInfo(int version, Name subject,
- SubjectPublicKeyInfo subjectPublicKeyInfo, List attributes) {
+ private CertificationRequestInfo(int version, Name subject,
+ SubjectPublicKeyInfo subjectPublicKeyInfo, List<?> attributes, byte [] encoding) {
this.version = version;
this.subject = subject;
this.subjectPublicKeyInfo = subjectPublicKeyInfo;
this.attributes = attributes;
- }
-
- // private constructor with encoding given
- private CertificationRequestInfo(int version, Name subject,
- SubjectPublicKeyInfo subjectPublicKeyInfo, List attributes, byte [] encoding) {
- this(version, subject, subjectPublicKeyInfo, attributes);
this.encoding = encoding;
}
- /**
- * @return Returns the attributes.
- */
- public List getAttributes() {
- return attributes;
- }
-
- /**
- * @return Returns the subject.
- */
public Name getSubject() {
return subject;
}
- /**
- * @return Returns the subjectPublicKeyInfo.
- */
- public SubjectPublicKeyInfo getSubjectPublicKeyInfo() {
- return subjectPublicKeyInfo;
- }
-
- /**
- * @return Returns the version.
- */
public int getVersion() {
return version;
}
@@ -111,8 +83,7 @@
return encoding;
}
-
- public String toString() {
+ @Override public String toString() {
StringBuilder res = new StringBuilder();
res.append("-- CertificationRequestInfo:");
res.append("\n version: ");
@@ -120,9 +91,9 @@
res.append("\n subject: ");
res.append(subject.getName(X500Principal.CANONICAL));
res.append("\n subjectPublicKeyInfo: ");
- res.append("\n\t algorithm: "
- + subjectPublicKeyInfo.getAlgorithmIdentifier().getAlgorithm());
- res.append("\n\t public key: " + subjectPublicKeyInfo.getPublicKey());
+ res.append("\n\t algorithm: ");
+ res.append(subjectPublicKeyInfo.getAlgorithmIdentifier().getAlgorithm());
+ res.append("\n\t public key: ").append(subjectPublicKeyInfo.getPublicKey());
res.append("\n attributes: ");
if (attributes != null) {
res.append(attributes.toString());
@@ -141,25 +112,23 @@
AttributeTypeAndValue.ASN1)) // attributes
}) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new CertificationRequestInfo(
ASN1Integer.toIntValue(values[0]),
(Name) values[1],
(SubjectPublicKeyInfo) values[2],
- (List) values[3],
+ (List<?>) values[3],
in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
CertificationRequestInfo certReqInfo = (CertificationRequestInfo) object;
-
values[0] = ASN1Integer.fromIntValue(certReqInfo.version);
values[1] = certReqInfo.subject;
values[2] = certReqInfo.subjectPublicKeyInfo;
values[3] = certReqInfo.attributes;
}
};
-
}
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs7/AuthenticatedAttributes.java b/luni/src/main/java/org/apache/harmony/security/pkcs7/AuthenticatedAttributes.java
index 5483aec..5a08a16 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs7/AuthenticatedAttributes.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs7/AuthenticatedAttributes.java
@@ -27,26 +27,26 @@
import org.apache.harmony.security.x501.AttributeTypeAndValue;
/**
- *
* As defined in PKCS #7: Cryptographic Message Syntax Standard
* (http://www.ietf.org/rfc/rfc2315.txt):
* authenticatedAttributes is a set of attributes that are signed (i.e., authenticated) by the signer
*/
-class AuthenticatedAttributes {
+final class AuthenticatedAttributes {
private byte[] encoding;
- private List authenticatedAttributes;
+ private final List<AttributeTypeAndValue> authenticatedAttributes;
- public AuthenticatedAttributes(byte[] encoding, List authenticatedAttributes) {
+ private AuthenticatedAttributes(byte[] encoding,
+ List<AttributeTypeAndValue> authenticatedAttributes) {
this.encoding = encoding;
this.authenticatedAttributes = authenticatedAttributes;
}
- public List getAttributes() {
+
+ public List<AttributeTypeAndValue> getAttributes() {
return authenticatedAttributes;
}
/**
* Returns ASN.1 encoded form of this authenticatedAttributes.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -57,9 +57,9 @@
public static final ASN1SetOf ASN1 =
new ASN1SetOf(AttributeTypeAndValue.ASN1) {
- public Object getDecodedObject(BerInputStream in) {
+ @Override public Object getDecodedObject(BerInputStream in) {
return new AuthenticatedAttributes(in.getEncoded(),
- (List) in.content);
+ (List<AttributeTypeAndValue>) in.content);
}
};
}
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs7/ContentInfo.java b/luni/src/main/java/org/apache/harmony/security/pkcs7/ContentInfo.java
index fbe06a65..c8d3076 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs7/ContentInfo.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs7/ContentInfo.java
@@ -40,8 +40,7 @@
* content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
* }
*/
-
-public class ContentInfo {
+public final class ContentInfo {
// OIDs
public static final int[] DATA = new int[] {1, 2, 840, 113549, 1, 7, 1};
@@ -51,15 +50,10 @@
public static final int[] DIGESTED_DATA = new int[] {1, 2, 840, 113549, 1, 7, 5};
public static final int[] ENCRYPTED_DATA = new int[] {1, 2, 840, 113549, 1, 7, 6};
- private int[] oid;
- private Object content;
+ private final int[] oid;
+ private final Object content;
private byte[] encoding;
- public ContentInfo(int[] oid, Object content) {
- this.oid = oid;
- this.content = content;
- }
-
private ContentInfo(int[] oid, Object content, byte[] encoding) {
this.oid = oid;
this.content = content;
@@ -91,12 +85,12 @@
return encoding;
}
- public String toString() {
+ @Override public String toString() {
StringBuilder res = new StringBuilder();
res.append("==== ContentInfo:");
res.append("\n== ContentType (OID): ");
- for (int i = 0; i< oid.length; i++) {
- res.append(oid[i]);
+ for (int i : oid) {
+ res.append(i);
res.append(' ');
}
res.append("\n== Content: ");
@@ -118,7 +112,7 @@
setOptional(1); // content is optional
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
ContentInfo ci = (ContentInfo) object;
values[0] = ci.oid;
if (ci.content != null) {
@@ -135,7 +129,7 @@
}
}
- protected Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
Object[] values = (Object[]) in.content;
int[] oid = (int[]) values[0];
if (Arrays.equals(oid, DATA)) {
@@ -153,8 +147,7 @@
SignedData.ASN1.decode((byte[])values[1]),
in.getEncoded());
}
- return new ContentInfo((int[])values[0], (byte[])values[1],
- in.getEncoded());
+ return new ContentInfo((int[]) values[0], values[1], in.getEncoded());
}
};
}
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs7/SignedData.java b/luni/src/main/java/org/apache/harmony/security/pkcs7/SignedData.java
index 69156fe..eaf245c 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs7/SignedData.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs7/SignedData.java
@@ -46,21 +46,18 @@
* crls
* [1] IMPLICIT CertificateRevocationLists OPTIONAL,
* signerInfos SignerInfos }
- *
*/
+public final class SignedData {
+ private final int version;
+ private final List<?> digestAlgorithms;
+ private final ContentInfo contentInfo;
+ private final List<Certificate> certificates;
+ private final List<CertificateList> crls;
+ private final List<SignerInfo> signerInfos;
-public class SignedData {
-
- private int version;
-
- private List digestAlgorithms;
- private ContentInfo contentInfo;
- private List certificates;
- private List crls;
- private List signerInfos;
-
- public SignedData(int version, List digestAlgorithms, ContentInfo contentInfo,
- List certificates, List crls, List signerInfos) {
+ private SignedData(int version, List<?> digestAlgorithms, ContentInfo contentInfo,
+ List<Certificate> certificates, List<CertificateList> crls,
+ List<SignerInfo> signerInfos) {
this.version = version;
this.digestAlgorithms = digestAlgorithms;
this.contentInfo = contentInfo;
@@ -69,40 +66,23 @@
this.signerInfos = signerInfos;
}
- public List getCertificates() {
+ public List<Certificate> getCertificates() {
return certificates;
}
- public List getCRLs() {
+ public List<CertificateList> getCRLs() {
return crls;
}
- public List getSignerInfos() {
+ public List<SignerInfo> getSignerInfos() {
return signerInfos;
}
- /**
- * @return Returns the contentInfo.
- */
- public ContentInfo getContentInfo() {
- return contentInfo;
- }
-
- /**
- * @return Returns the digestAlgorithms.
- */
- public List getDigestAlgorithms() {
- return digestAlgorithms;
- }
-
- /**
- * @return Returns the version.
- */
public int getVersion() {
return version;
}
- public String toString() {
+ @Override public String toString() {
StringBuilder res = new StringBuilder();
res.append("---- SignedData:");
res.append("\nversion: ");
@@ -138,7 +118,7 @@
setOptional(4); // crls is optional
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
SignedData sd = (SignedData) object;
values[0] = new byte[] {(byte)sd.version};
values[1] = sd.digestAlgorithms;
@@ -148,15 +128,15 @@
values[5] = sd.signerInfos;
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new SignedData(
ASN1Integer.toIntValue(values[0]),
- (List) values[1],
+ (List<?>) values[1],
(ContentInfo) values[2],
- (List) values[3],
- (List) values[4],
- (List) values[5]
+ (List<Certificate>) values[3],
+ (List<CertificateList>) values[4],
+ (List<SignerInfo>) values[5]
);
}
};
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs7/SignerInfo.java b/luni/src/main/java/org/apache/harmony/security/pkcs7/SignerInfo.java
index aa40fdd..baaa090 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs7/SignerInfo.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs7/SignerInfo.java
@@ -53,33 +53,27 @@
* unauthenticatedAttributes
* [1] IMPLICIT Attributes OPTIONAL
* }
- *
*/
-public class SignerInfo {
+public final class SignerInfo {
+ private final int version;
+ private final X500Principal issuer;
+ private final BigInteger serialNumber;
+ private final AlgorithmIdentifier digestAlgorithm;
+ private final AuthenticatedAttributes authenticatedAttributes;
+ private final AlgorithmIdentifier digestEncryptionAlgorithm;
+ private final byte[] encryptedDigest;
+ private final List<?> unauthenticatedAttributes;
- private int version;
- private X500Principal issuer;
- private BigInteger serialNumber;
-
- private AlgorithmIdentifier digestAlgorithm;
- private AuthenticatedAttributes authenticatedAttributes;
- private AlgorithmIdentifier digestEncryptionAlgorithm;
- private byte[] encryptedDigest;
- private List unauthenticatedAttributes;
-
- public SignerInfo(int version,
+ private SignerInfo(int version,
Object[] issuerAndSerialNumber,
AlgorithmIdentifier digestAlgorithm,
AuthenticatedAttributes authenticatedAttributes,
AlgorithmIdentifier digestEncryptionAlgorithm,
byte[] encryptedDigest,
- List unauthenticatedAttributes
- ) {
+ List<?> unauthenticatedAttributes) {
this.version = version;
this.issuer = ((Name)issuerAndSerialNumber[0]).getX500Principal();
- // BEGIN android-changed
this.serialNumber = ASN1Integer.toBigIntegerValue(issuerAndSerialNumber[1]);
- // END android-changed
this.digestAlgorithm = digestAlgorithm;
this.authenticatedAttributes = authenticatedAttributes;
this.digestEncryptionAlgorithm = digestEncryptionAlgorithm;
@@ -99,15 +93,11 @@
return digestAlgorithm.getAlgorithm();
}
- public String getdigestAlgorithm() {
- return digestAlgorithm.getAlgorithm();
- }
-
public String getDigestEncryptionAlgorithm() {
return digestEncryptionAlgorithm.getAlgorithm();
}
- public List getAuthenticatedAttributes() {
+ public List<AttributeTypeAndValue> getAuthenticatedAttributes() {
if (authenticatedAttributes == null) {
return null;
}
@@ -159,7 +149,7 @@
})
{
// method to encode
- public void getValues(Object object, Object[] values) {
+ @Override public void getValues(Object object, Object[] values) {
Object [] issAndSerial = (Object[])object;
values[0] = issAndSerial[0];
values[1] = issAndSerial[1];
@@ -182,7 +172,7 @@
setOptional(6); // unauthenticatedAttributes is optional
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
SignerInfo si = (SignerInfo) object;
values[0] = new byte[] {(byte)si.version};
try {
@@ -201,7 +191,7 @@
values[6] = si.unauthenticatedAttributes;
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new SignerInfo(
ASN1Integer.toIntValue(values[0]),
diff --git a/luni/src/main/java/org/apache/harmony/security/pkcs8/PrivateKeyInfo.java b/luni/src/main/java/org/apache/harmony/security/pkcs8/PrivateKeyInfo.java
index be7e3b3..400bf86 100644
--- a/luni/src/main/java/org/apache/harmony/security/pkcs8/PrivateKeyInfo.java
+++ b/luni/src/main/java/org/apache/harmony/security/pkcs8/PrivateKeyInfo.java
@@ -47,22 +47,15 @@
*
* Attributes ::= SET OF Attribute
*/
-
-public class PrivateKeyInfo {
-
- private int version;
-
- private AlgorithmIdentifier privateKeyAlgorithm;
-
- private byte[] privateKey;
-
- private List attributes;
-
+public final class PrivateKeyInfo {
+ private final int version;
+ private final AlgorithmIdentifier privateKeyAlgorithm;
+ private final byte[] privateKey;
+ private final List<?> attributes;
private byte[] encoding;
public PrivateKeyInfo(int version, AlgorithmIdentifier privateKeyAlgorithm,
byte[] privateKey, List attributes) {
-
this.version = version;
this.privateKeyAlgorithm = privateKeyAlgorithm;
this.privateKey = privateKey;
@@ -76,29 +69,20 @@
this.encoding = encoding;
}
- /**
- * @return Returns version.
- */
public int getVersion() {
return version;
}
- /**
- * @return Returns AlgorithmIdentifier.
- */
public AlgorithmIdentifier getAlgorithmIdentifier() {
return privateKeyAlgorithm;
}
- /**
- * @return Returns List of attributes.
- */
public List getAttributes() {
return attributes;
}
/**
- * @return Returns the OCTET STRING.
+ * Returns the OCTET STRING.
*/
public byte[] getPrivateKey() {
return privateKey;
@@ -106,7 +90,6 @@
/**
* Returns ASN.1 encoded form of this PrivateKeyInfo.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -129,23 +112,18 @@
}
protected Object getDecodedObject(BerInputStream in) {
-
Object[] values = (Object[]) in.content;
-
return new PrivateKeyInfo(ASN1Integer.toIntValue(values[0]),
(AlgorithmIdentifier) values[1], (byte[]) values[2],
(List) values[3], in.getEncoded());
}
protected void getValues(Object object, Object[] values) {
-
PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) object;
-
values[0] = ASN1Integer.fromIntValue(privateKeyInfo.version);
values[1] = privateKeyInfo.privateKeyAlgorithm;
values[2] = privateKeyInfo.privateKey;
values[3] = privateKeyInfo.attributes;
}
};
-
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java
index f3dd402..a2c5b4c 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/cert/Cache.java
@@ -138,25 +138,6 @@
cache = new Object[cache_size];
}
- // BEGIN android-removed
- // /**
- // * Creates the Cache object of size of 900.
- // * @param pref_size specifies how many leading/trailing bytes of object's
- // * encoded form will be used for hash computation
- // */
- // public Cache(int pref_size) {
- // this(pref_size, 900);
- // }
- //
- // /**
- // * Creates the Cache object of size of 900.
- // */
- // public Cache() {
- // this(28, 900);
- // }
- // END android-removed
-
- // BEGIN android-added
/**
* Creates the Cache object of size of 9.
* @param pref_size specifies how many leading/trailing bytes of object's
@@ -172,7 +153,6 @@
public Cache() {
this(28, 9);
}
- // END android-added
/**
* Returns the hash code for the array. This code is used to
@@ -342,4 +322,3 @@
}
}
-
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
index a4537e8..790be67 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/cert/DRLCertFactory.java
@@ -22,16 +22,9 @@
package org.apache.harmony.security.provider.cert;
-import java.security.AccessController;
import java.security.Provider;
-
-/**
- * Master class (provider) for X509 Certificate Factory
- * Implementation.
- */
public final class DRLCertFactory extends Provider {
-
/**
* @serial
*/
@@ -42,22 +35,10 @@
*/
public DRLCertFactory() {
// specification of the provider name, version, and description.
-
- // BEGIN android-changed
- // Avoid using a message resource string here, since it forces loading
- // all the messages in a non-error context.
super("DRLCertFactory", 1.0, "ASN.1, DER, PkiPath, PKCS7");
- // END android-changed
-
- AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
- public Void run() {
- // register the service
- put("CertificateFactory.X509",
- "org.apache.harmony.security.provider.cert.X509CertFactoryImpl");
- // mapping the alias
- put("Alg.Alias.CertificateFactory.X.509", "X509");
- return null;
- }
- });
+ // register the service
+ put("CertificateFactory.X509", "org.apache.harmony.security.provider.cert.X509CertFactoryImpl");
+ // mapping the alias
+ put("Alg.Alias.CertificateFactory.X.509", "X509");
}
}
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 0b1f797..da53201 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
@@ -124,7 +124,7 @@
if (inStream == null) {
throw new CertificateException("inStream == null");
}
- ArrayList result = new ArrayList();
+ ArrayList<Certificate> result = new ArrayList<Certificate>();
try {
if (!inStream.markSupported()) {
// create the mark supporting wrapper
@@ -210,12 +210,10 @@
if (data == null) {
throw new CertificateException("Invalid PKCS7 data provided");
}
- List certs = data.getCertificates();
+ List<org.apache.harmony.security.x509.Certificate> certs = data.getCertificates();
if (certs != null) {
- for (int i = 0; i < certs.size(); i++) {
- result.add(new X509CertImpl(
- (org.apache.harmony.security.x509.Certificate)
- certs.get(i)));
+ for (org.apache.harmony.security.x509.Certificate cert : certs) {
+ result.add(new X509CertImpl(cert));
}
}
return result;
@@ -267,7 +265,7 @@
if (inStream == null) {
throw new CRLException("inStream == null");
}
- ArrayList result = new ArrayList();
+ ArrayList<CRL> result = new ArrayList<CRL>();
try {
if (!inStream.markSupported()) {
inStream = new RestoringInputStream(inStream);
@@ -351,11 +349,10 @@
if (data == null) {
throw new CRLException("Invalid PKCS7 data provided");
}
- List crls = data.getCRLs();
+ List<CertificateList> crls = data.getCRLs();
if (crls != null) {
- for (int i = 0; i < crls.size(); i++) {
- result.add(new X509CRLImpl(
- (CertificateList) crls.get(i)));
+ for (CertificateList crl : crls) {
+ result.add(new X509CRLImpl(crl));
}
}
return result;
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 d8f79bc..776677e 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
@@ -60,14 +60,12 @@
* @see org.apache.harmony.security.x509.Certificate
* @see java.security.cert.X509Certificate
*/
-public class X509CertImpl extends X509Certificate {
+public final class X509CertImpl extends X509Certificate {
- /**
- * @serial
- */
+ /** @serial */
private static final long serialVersionUID = 2972248729446736154L;
- // the core object to be wrapped in X509Certificate
+ /** the core object to be wrapped in X509Certificate */
private final Certificate certificate;
// to speed up access to the info, the following fields
@@ -139,19 +137,11 @@
// ----------------- Public methods implementations ------------------
//
- /**
- * @see java.security.cert.X509Certificate#checkValidity()
- * method documentation for more information.
- */
public void checkValidity()
throws CertificateExpiredException, CertificateNotYetValidException {
checkValidity(System.currentTimeMillis());
}
- /**
- * @see java.security.cert.X509Certificate#checkValidity(Date)
- * method documentation for more information.
- */
public void checkValidity(Date date)
throws CertificateExpiredException, CertificateNotYetValidException {
checkValidity(date.getTime());
@@ -169,18 +159,10 @@
}
}
- /**
- * @see java.security.cert.X509Certificate#getVersion()
- * method documentation for more information.
- */
public int getVersion() {
return tbsCert.getVersion() + 1;
}
- /**
- * @see java.security.cert.X509Certificate#getSerialNumber()
- * method documentation for more information.
- */
public BigInteger getSerialNumber() {
BigInteger result = serialNumber;
if (result == null) {
@@ -189,18 +171,10 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getIssuerDN()
- * method documentation for more information.
- */
public Principal getIssuerDN() {
return getIssuerX500Principal();
}
- /**
- * @see java.security.cert.X509Certificate#getIssuerX500Principal()
- * method documentation for more information.
- */
public X500Principal getIssuerX500Principal() {
X500Principal result = issuer;
if (result == null) {
@@ -210,18 +184,10 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getSubjectDN()
- * method documentation for more information.
- */
public Principal getSubjectDN() {
return getSubjectX500Principal();
}
- /**
- * @see java.security.cert.X509Certificate#getSubjectX500Principal()
- * method documentation for more information.
- */
public X500Principal getSubjectX500Principal() {
X500Principal result = subject;
if (result == null) {
@@ -231,13 +197,10 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getNotBefore()
- * method documentation for more information.
- */
public Date getNotBefore() {
return new Date(getNotBeforeInternal());
}
+
private long getNotBeforeInternal() {
long result = notBefore;
if (result == -1) {
@@ -246,13 +209,10 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getNotAfter()
- * method documentation for more information.
- */
public Date getNotAfter() {
return new Date(getNotAfterInternal());
}
+
private long getNotAfterInternal() {
long result = notAfter;
if (result == -1) {
@@ -261,13 +221,10 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getTBSCertificate()
- * method documentation for more information.
- */
public byte[] getTBSCertificate() throws CertificateEncodingException {
return getTbsCertificateInternal().clone();
}
+
private byte[] getTbsCertificateInternal() {
byte[] result = tbsCertificate;
if (result == null) {
@@ -276,13 +233,10 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getSignature()
- * method documentation for more information.
- */
public byte[] getSignature() {
return getSignatureInternal().clone();
}
+
private byte[] getSignatureInternal() {
byte[] result = signature;
if (result == null) {
@@ -291,10 +245,6 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getSigAlgName()
- * method documentation for more information.
- */
public String getSigAlgName() {
String result = sigAlgName;
if (result == null) {
@@ -310,10 +260,6 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getSigAlgOID()
- * method documentation for more information.
- */
public String getSigAlgOID() {
String result = sigAlgOID;
if (result == null) {
@@ -323,10 +269,6 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getSigAlgParams()
- * method documentation for more information.
- */
public byte[] getSigAlgParams() {
if (nullSigAlgParams) {
return null;
@@ -343,26 +285,14 @@
return result;
}
- /**
- * @see java.security.cert.X509Certificate#getIssuerUniqueID()
- * method documentation for more information.
- */
public boolean[] getIssuerUniqueID() {
return tbsCert.getIssuerUniqueID();
}
- /**
- * @see java.security.cert.X509Certificate#getSubjectUniqueID()
- * method documentation for more information.
- */
public boolean[] getSubjectUniqueID() {
return tbsCert.getSubjectUniqueID();
}
- /**
- * @see java.security.cert.X509Certificate#getKeyUsage()
- * method documentation for more information.
- */
public boolean[] getKeyUsage() {
if (extensions == null) {
return null;
@@ -370,11 +300,7 @@
return extensions.valueOfKeyUsage();
}
- /**
- * @see java.security.cert.X509Certificate#getExtendedKeyUsage()
- * method documentation for more information.
- */
- public List/*<String>*/ getExtendedKeyUsage()
+ public List<String> getExtendedKeyUsage()
throws CertificateParsingException {
if (extensions == null) {
return null;
@@ -386,10 +312,6 @@
}
}
- /**
- * @see java.security.cert.X509Certificate#getBasicConstraints()
- * method documentation for more information.
- */
public int getBasicConstraints() {
if (extensions == null) {
return Integer.MAX_VALUE;
@@ -397,12 +319,7 @@
return extensions.valueOfBasicConstrains();
}
- /**
- * @see java.security.cert.X509Certificate#getSubjectAlternativeNames()
- * method documentation for more information.
- */
- public Collection/*<List<?>>*/ getSubjectAlternativeNames()
- throws CertificateParsingException {
+ public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException {
if (extensions == null) {
return null;
}
@@ -420,8 +337,7 @@
* @see java.security.cert.X509Certificate#getIssuerAlternativeNames()
* method documentation for more information.
*/
- public Collection/*FIXME <List<?>>*/ getIssuerAlternativeNames()
- throws CertificateParsingException {
+ public Collection<List<?>> getIssuerAlternativeNames() throws CertificateParsingException {
if (extensions == null) {
return null;
}
@@ -439,10 +355,6 @@
// ----- java.security.cert.Certificate methods implementations ------
//
- /**
- * @see java.security.cert.Certificate#getEncoded()
- * method documentation for more information.
- */
public byte[] getEncoded() throws CertificateEncodingException {
return getEncodedInternal().clone();
}
@@ -454,10 +366,6 @@
return result;
}
- /**
- * @see java.security.cert.Certificate#getPublicKey()
- * method documentation for more information.
- */
public PublicKey getPublicKey() {
PublicKey result = publicKey;
if (result == null) {
@@ -466,19 +374,10 @@
return result;
}
- /**
- * @see java.security.cert.Certificate#toString()
- * method documentation for more information.
- */
public String toString() {
return certificate.toString();
}
- /**
- * Verifies the signature of the certificate.
- * @see java.security.cert.Certificate#verify(PublicKey)
- * method documentation for more information.
- */
public void verify(PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
@@ -499,11 +398,6 @@
}
}
- /**
- * Verifies the signature of the certificate.
- * @see java.security.cert.Certificate#verify(PublicKey,String)
- * method documentation for more information.
- */
public void verify(PublicKey key, String sigProvider)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException,
@@ -528,7 +422,7 @@
/**
* Implements a faster RSA verification method that delegates to OpenSSL
* native code. In all other aspects it behaves just like the ordinary
- * {@link verify} method.
+ * {@link #verify} method.
*
* @param key The RSA public key to use
*
@@ -567,11 +461,7 @@
// ----- java.security.cert.X509Extension methods implementations ----
//
- /**
- * @see java.security.cert.X509Extension#getNonCriticalExtensionOIDs()
- * method documentation for more information.
- */
- public Set getNonCriticalExtensionOIDs() {
+ public Set<String> getNonCriticalExtensionOIDs() {
if (extensions == null) {
return null;
}
@@ -579,11 +469,7 @@
return extensions.getNonCriticalExtensions();
}
- /**
- * @see java.security.cert.X509Extension#getCriticalExtensionOIDs()
- * method documentation for more information.
- */
- public Set getCriticalExtensionOIDs() {
+ public Set<String> getCriticalExtensionOIDs() {
if (extensions == null) {
return null;
}
@@ -591,10 +477,6 @@
return extensions.getCriticalExtensions();
}
- /**
- * @see java.security.cert.X509Extension#getExtensionValue(String)
- * method documentation for more information.
- */
public byte[] getExtensionValue(String oid) {
if (extensions == null) {
return null;
@@ -604,10 +486,6 @@
return (ext == null) ? null : ext.getRawExtnValue();
}
- /**
- * @see java.security.cert.X509Extension#hasUnsupportedCriticalExtension()
- * method documentation for more information.
- */
public boolean hasUnsupportedCriticalExtension() {
if (extensions == null) {
return false;
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 e961d1f..b65d345 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
@@ -171,14 +171,14 @@
throw new CertificateException(
"Incorrect PKCS7 encoded form: missing signed data");
}
- List certs = sd.getCertificates();
+ List<Certificate> certs = sd.getCertificates();
if (certs == null) {
// empty chain of certificates
- certs = new ArrayList();
+ certs = new ArrayList<Certificate>();
}
- List result = new ArrayList();
- for (int i=0; i<certs.size(); i++) {
- result.add(new X509CertImpl((Certificate) certs.get(i)));
+ List<X509CertImpl> result = new ArrayList<X509CertImpl>();
+ for (Certificate cert : certs) {
+ result.add(new X509CertImpl(cert));
}
return new X509CertPathImpl(result, PKCS7, ci.getEncoded());
}
@@ -224,13 +224,13 @@
if (sd == null) {
throw new CertificateException("Incorrect PKCS7 encoded form: missing signed data");
}
- List certs = sd.getCertificates();
+ List<Certificate> certs = sd.getCertificates();
if (certs == null) {
- certs = new ArrayList();
+ certs = new ArrayList<Certificate>();
}
- List result = new ArrayList();
- for (int i=0; i<certs.size(); i++) {
- result.add(new X509CertImpl((Certificate) certs.get(i)));
+ List<X509CertImpl> result = new ArrayList<X509CertImpl>();
+ for (Certificate cert : certs) {
+ result.add(new X509CertImpl(cert));
}
return new X509CertPathImpl(result, PKCS7, ci.getEncoded());
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
index 8e3774b..70a2449 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/CryptoProvider.java
@@ -17,7 +17,6 @@
package org.apache.harmony.security.provider.crypto;
-import java.security.AccessController;
import java.security.Provider;
/**
@@ -38,8 +37,7 @@
*/
public CryptoProvider() {
- super("Crypto", 1.0,
- "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
+ super("Crypto", 1.0, "HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)");
// names of classes implementing services
final String MD_NAME = "org.apache.harmony.security.provider.crypto.SHA1_MessageDigestImpl";
@@ -50,45 +48,36 @@
final String SIGN_ALIAS = "SHA1withDSA";
- final String KEYF_NAME =
- "org.apache.harmony.security.provider.crypto.DSAKeyFactoryImpl";
+ final String KEYF_NAME = "org.apache.harmony.security.provider.crypto.DSAKeyFactoryImpl";
- AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
+ put("MessageDigest.SHA-1", MD_NAME);
+ put("MessageDigest.SHA-1 ImplementedIn", "Software");
+ put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
+ put("Alg.Alias.MessageDigest.SHA", "SHA-1");
- public Void run() {
+ if (RandomBitsSupplier.isServiceAvailable()) {
+ put("SecureRandom.SHA1PRNG", SR_NAME);
+ put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
+ }
- put("MessageDigest.SHA-1", MD_NAME);
- put("MessageDigest.SHA-1 ImplementedIn", "Software");
- put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
- put("Alg.Alias.MessageDigest.SHA", "SHA-1");
+ put("Signature.SHA1withDSA", SIGN_NAME);
+ put("Signature.SHA1withDSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.SHAwithDSA", SIGN_ALIAS);
+ put("Alg.Alias.Signature.DSAwithSHA1", SIGN_ALIAS);
+ put("Alg.Alias.Signature.SHA1/DSA", SIGN_ALIAS);
+ put("Alg.Alias.Signature.SHA/DSA", SIGN_ALIAS);
+ put("Alg.Alias.Signature.SHA-1/DSA", SIGN_ALIAS);
+ put("Alg.Alias.Signature.DSA", SIGN_ALIAS);
+ put("Alg.Alias.Signature.DSS", SIGN_ALIAS);
- if (RandomBitsSupplier.isServiceAvailable()) {
- put("SecureRandom.SHA1PRNG", SR_NAME);
- put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
- }
+ put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", SIGN_ALIAS);
+ put("Alg.Alias.Signature.1.2.840.10040.4.3", SIGN_ALIAS);
+ put("Alg.Alias.Signature.1.3.14.3.2.13", SIGN_ALIAS);
+ put("Alg.Alias.Signature.1.3.14.3.2.27", SIGN_ALIAS);
- put("Signature.SHA1withDSA", SIGN_NAME);
- put("Signature.SHA1withDSA ImplementedIn", "Software");
- put("Alg.Alias.Signature.SHAwithDSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSAwithSHA1", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA1/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.SHA-1/DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSA", SIGN_ALIAS);
- put("Alg.Alias.Signature.DSS", SIGN_ALIAS);
-
- put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.2.840.10040.4.3", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.3.14.3.2.13", SIGN_ALIAS);
- put("Alg.Alias.Signature.1.3.14.3.2.27", SIGN_ALIAS);
-
- put("KeyFactory.DSA", KEYF_NAME);
- put("KeyFactory.DSA ImplementedIn", "Software");
- put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA");
- put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA");
-
- return null;
- }
- });
+ put("KeyFactory.DSA", KEYF_NAME);
+ put("KeyFactory.DSA ImplementedIn", "Software");
+ put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA");
+ put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA");
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
index 993914a..3862132 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
@@ -23,10 +23,8 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
-import java.security.AccessController;
import java.security.ProviderException;
-
/**
* The static class providing access on Linux platform
* to system means for generating true random bits. <BR>
@@ -37,25 +35,24 @@
* If no device available the service is not available,
* that is, provider shouldn't register the algorithm. <BR>
*/
-
-
public class RandomBitsSupplier implements SHA1_Data {
/**
- * BufferedInputStream to read from device
+ * InputStream to read from device
+ *
+ * Using a BufferedInputStream leads to problems
+ * on Android in rare cases, since the
+ * BufferedInputStream's available() issues an
+ * ioctl(), and the pseudo device doesn't seem
+ * to like that. Since we're reading bigger
+ * chunks and not single bytes, the FileInputStream
+ * shouldn't be slower, so we use that. Same might
+ * apply to other Linux platforms.
+ *
+ * TODO: the above doesn't sound true.
*/
- // BEGIN android-changed
- // Using a BufferedInputStream leads to problems
- // on Android in rare cases, since the
- // BufferedInputStream's available() issues an
- // iotcl(), and the pseudo device doesn't seem
- // to like that. Since we're reading bigger
- // chunks and not single bytes, the FileInputStream
- // shouldn't be slower, so we use that. Same might
- // apply to other Linux platforms.
- private static FileInputStream bis = null;
- // END android-changed
+ private static FileInputStream fis = null;
/**
* File to connect to device
@@ -67,41 +64,23 @@
*/
private static boolean serviceAvailable = false;
+ /**
+ * names of random devices on Linux platform
+ */
+ private static final String DEVICE_NAMES[] = { "/dev/urandom" /*, "/dev/random" */ };
static {
- AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
-
- for ( int i = 0 ; i < DEVICE_NAMES.length ; i++ ) {
- File file = new File(DEVICE_NAMES[i]);
-
- try {
- if ( file.canRead() ) {
- // BEGIN android-modified
- bis = new FileInputStream(file);
- // END android-modified
- randomFile = file;
- serviceAvailable = true;
- return null;
- }
- } catch (FileNotFoundException e) {
- }
- }
-
- // BEGIN android-removed
-// // If we have come out of the above loop, then we have been unable to
-// // access /dev/*random, so try to fall back to using the system random() API
-// try {
-// System.loadLibrary(LIBRARY_NAME);
-// serviceAvailable = true;
-// } catch (UnsatisfiedLinkError e) {
-// serviceAvailable = false;
-// }
- return null;
+ for (String deviceName : DEVICE_NAMES) {
+ try {
+ File file = new File(deviceName);
+ if (file.canRead()) {
+ fis = new FileInputStream(file);
+ randomFile = file;
+ serviceAvailable = true;
}
+ } catch (FileNotFoundException e) {
}
- );
+ }
}
@@ -129,7 +108,7 @@
try {
for ( ; ; ) {
- bytesRead = bis.read(bytes, offset, numBytes-total);
+ bytesRead = fis.read(bytes, offset, numBytes-total);
// the below case should not occur because /dev/random or /dev/urandom is a special file
@@ -155,18 +134,6 @@
return bytes;
}
-
- // BEGIN android-removed
-// /**
-// * On platforms with no "random" devices available, this native
-// * method uses system API calls to generate random numbers<BR>
-// *
-// * In case of any runtime failure ProviderException gets thrown.
-// */
-// private static native synchronized boolean getUnixSystemRandom(byte[] randomBits, int numBytes);
- // END android-removed
-
-
/**
* The method returns byte array of requested length provided service is available.
* ProviderException gets thrown otherwise.
@@ -179,7 +146,6 @@
* InvalidArgumentException - if numBytes <= 0
*/
public static byte[] getRandomBits(int numBytes) {
-
if (numBytes <= 0) {
throw new IllegalArgumentException(Integer.toString(numBytes));
}
@@ -190,8 +156,6 @@
throw new ProviderException("ATTENTION: service is not available : no random devices");
}
- // BEGIN android-changed
return getUnixDeviceRandom(numBytes);
- // END android-changed
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java
index 0e30e03..b559576 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java
@@ -80,20 +80,4 @@
* in this implementation # is set to 20 (in general # varies from 1 to 20)
*/
static final int DIGEST_LENGTH = 20;
-
-
- // BEGIN android-removed
-// /**
-// * name of native library to use on Windows platform
-// */
-// static final String LIBRARY_NAME = "hysecurity";
- // END android-removed
-
-
- /**
- * names of random devices on Linux platform
- */
- // BEGIN android-changed: /dev/random seems to be empty on Android
- static final String DEVICE_NAMES[] = { "/dev/urandom" /*, "/dev/random" */ };
- // END android-changed
}
diff --git a/luni/src/main/java/org/apache/harmony/security/utils/AlgNameMapper.java b/luni/src/main/java/org/apache/harmony/security/utils/AlgNameMapper.java
index 8305c70..9ad5373 100644
--- a/luni/src/main/java/org/apache/harmony/security/utils/AlgNameMapper.java
+++ b/luni/src/main/java/org/apache/harmony/security/utils/AlgNameMapper.java
@@ -25,10 +25,10 @@
import java.security.Provider;
import java.security.Security;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import org.apache.harmony.security.Util;
import org.apache.harmony.security.asn1.ObjectIdentifier;
/**
@@ -83,7 +83,7 @@
static {
for (String[] element : knownAlgMappings) {
- String algUC = Util.toUpperCase(element[1]);
+ String algUC = element[1].toUpperCase(Locale.US);
alg2OidMap.put(algUC, element[0]);
oid2AlgMap.put(element[0], algUC);
// map upper case alg name to its original name
@@ -113,7 +113,7 @@
*/
public static String map2OID(String algName) {
// alg2OidMap map contains upper case keys
- return alg2OidMap.get(Util.toUpperCase(algName));
+ return alg2OidMap.get(algName.toUpperCase(Locale.US));
}
/**
@@ -136,7 +136,7 @@
* @return algorithm name
*/
public static String getStandardName(String algName) {
- return algAliasesMap.get(Util.toUpperCase(algName));
+ return algAliasesMap.get(algName.toUpperCase(Locale.US));
}
// Searches given provider for mappings like
@@ -153,7 +153,7 @@
if (key.startsWith(keyPrfix2find)) {
String alias = key.substring(keyPrfix2find.length());
String alg = (String)me.getValue();
- String algUC = Util.toUpperCase(alg);
+ String algUC = alg.toUpperCase(Locale.US);
if (isOID(alias)) {
if (alias.startsWith("OID.")) {
alias = alias.substring(4);
@@ -172,8 +172,8 @@
algAliasesMap.put(algUC, alg);
}
// Do not override known standard names
- } else if (!algAliasesMap.containsKey(Util.toUpperCase(alias))) {
- algAliasesMap.put(Util.toUpperCase(alias), alg);
+ } else if (!algAliasesMap.containsKey(alias.toUpperCase(Locale.US))) {
+ algAliasesMap.put(alias.toUpperCase(Locale.US), alg);
}
}
}
@@ -187,9 +187,7 @@
* @return 'true' if parameter represents OID
*/
public static boolean isOID(String alias) {
- // BEGIN android-changed
return ObjectIdentifier.isOID(normalize(alias));
- // END android-changed
}
/**
@@ -203,18 +201,4 @@
? oid.substring(4)
: oid;
}
-
- /**
- * Present all internal maps as formatted string
- * @return Internal maps String representation
- */
- public static String dump() {
- StringBuilder sb = new StringBuilder("alg2OidMap: ");
- sb.append(alg2OidMap);
- sb.append("\noid2AlgMap: ");
- sb.append(oid2AlgMap);
- sb.append("\nalgAliasesMap: ");
- sb.append(algAliasesMap);
- return sb.toString();
- }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/utils/Array.java b/luni/src/main/java/org/apache/harmony/security/utils/Array.java
index afcb19d..582ca7d 100644
--- a/luni/src/main/java/org/apache/harmony/security/utils/Array.java
+++ b/luni/src/main/java/org/apache/harmony/security/utils/Array.java
@@ -33,6 +33,15 @@
private Array() {
}
+ public static String getBytesAsString(byte[] data) {
+ StringBuilder result = new StringBuilder(data.length * 3);
+ for (int i = 0; i < data.length; ++i) {
+ result.append(Byte.toHexString(data[i], false));
+ result.append(' ');
+ }
+ return result.toString();
+ }
+
/**
* Represents <code>array</code> as <code>String</code>
* for printing. Array length can be up to 32767
@@ -67,13 +76,9 @@
// put delimiter
sb.append(' ');
// put current byte
- int currentByte = (0xff & array[i]);
- String hexTail = Integer.toHexString(currentByte);
- if (hexTail.length() == 1) {
- sb.append('0');
- }
- sb.append(hexTail);
+ sb.append(Byte.toHexString(array[i], false));
// form character representation part
+ int currentByte = (0xff & array[i]);
char currentChar = (char)(currentByte & 0xffff);
// FIXME if needed (how to distinguish PRINTABLE chars?)
charForm.append(
diff --git a/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java b/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
index 9013eba..70a13f7 100644
--- a/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
+++ b/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
@@ -72,20 +72,21 @@
if (signedData == null) {
throw new IOException("No SignedData found");
}
- Collection encCerts = signedData.getCertificates();
+ Collection<org.apache.harmony.security.x509.Certificate> encCerts
+ = signedData.getCertificates();
if (encCerts.isEmpty()) {
return null;
}
X509Certificate[] certs = new X509Certificate[encCerts.size()];
int i = 0;
- for (Iterator it = encCerts.iterator(); it.hasNext();) {
- certs[i++]= new X509CertImpl((org.apache.harmony.security.x509.Certificate)it.next());
+ for (org.apache.harmony.security.x509.Certificate encCert : encCerts) {
+ certs[i++] = new X509CertImpl(encCert);
}
- List sigInfos = signedData.getSignerInfos();
+ List<SignerInfo> sigInfos = signedData.getSignerInfos();
SignerInfo sigInfo;
if (!sigInfos.isEmpty()) {
- sigInfo = (SignerInfo)sigInfos.get(0);
+ sigInfo = sigInfos.get(0);
} else {
return null;
}
@@ -115,18 +116,13 @@
// Get Signature instance
Signature sig = null;
- String da = sigInfo.getdigestAlgorithm();
+ String da = sigInfo.getDigestAlgorithm();
String dea = sigInfo.getDigestEncryptionAlgorithm();
String alg = null;
if (da != null && dea != null) {
alg = da + "with" + dea;
- try{
- // BEGIN android-removed
- // sig = OpenSSLSignature.getInstance(alg);
- // END android-removed
- // BEGIN android-added
+ try {
sig = OpenSSLSignature.getInstance(alg);
- // END android-removed
} catch (NoSuchAlgorithmException e) {}
}
if (sig == null) {
@@ -134,13 +130,8 @@
if (alg == null) {
return null;
}
- try{
- // BEGIN android-removed
- // sig = OpenSSLSignature.getInstance(alg);
- // END android-removed
- // BEGIN android-added
+ try {
sig = OpenSSLSignature.getInstance(alg);
- // END android-removed
} catch (NoSuchAlgorithmException e) {
return null;
}
@@ -150,7 +141,7 @@
// If the authenticatedAttributes field of SignerInfo contains more than zero attributes,
// compute the message digest on the ASN.1 DER encoding of the Attributes value.
// Otherwise, compute the message digest on the data.
- List atr = sigInfo.getAuthenticatedAttributes();
+ List<AttributeTypeAndValue> atr = sigInfo.getAuthenticatedAttributes();
byte[] sfBytes = new byte[signature.available()];
signature.read(sfBytes);
@@ -163,9 +154,8 @@
// If the authenticatedAttributes field contains the message-digest attribute,
// verify that it equals the computed digest of the signature file
byte[] existingDigest = null;
- for (Iterator it = atr.iterator(); it.hasNext();) {
- AttributeTypeAndValue a = (AttributeTypeAndValue)it.next();
- if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID) ){
+ for (AttributeTypeAndValue a : atr) {
+ if (Arrays.equals(a.getType().getOid(), MESSAGE_DIGEST_OID)) {
//TODO value existingDigest = a.AttributeValue;
}
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/AttributeType.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeType.java
deleted file mode 100644
index 6e11358..0000000
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeType.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.
- */
-/**
-* @author Stepan M. Mishura
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.x501;
-
-import org.apache.harmony.security.asn1.ASN1Type;
-import org.apache.harmony.security.asn1.ObjectIdentifier;
-
-
-/**
- * X.501 Attribute Type
- *
- * This is a draft class for Module InformationFramework (X.501).
- *
- * @see <a href="http://www.itu.int/ITU-T/asn1/database/itu-t/x/x501/2001/InformationFramework.html">X.501</a>
- */
-
-public class AttributeType {
-
- public final ObjectIdentifier oid;
-
- public final ASN1Type type;
-
- public AttributeType(ObjectIdentifier oid, ASN1Type type) {
- this.oid = oid;
- this.type = type;
- }
-}
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 6dbf416..96e3df5 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
@@ -26,9 +26,8 @@
import java.nio.charset.Charsets;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.Iterator;
+import java.util.Locale;
import javax.security.auth.x500.X500Principal;
-import org.apache.harmony.security.Util;
import org.apache.harmony.security.asn1.ASN1Constants;
import org.apache.harmony.security.asn1.ASN1Oid;
import org.apache.harmony.security.asn1.ASN1Sequence;
@@ -42,146 +41,105 @@
/**
* X.501 AttributeTypeAndValue
*/
-public class AttributeTypeAndValue {
+public final class AttributeTypeAndValue {
- // Country code attribute (name from RFC 1779)
- private static final ObjectIdentifier C;
+ /** known attribute types for RFC1779 (see Table 1) */
+ private static final HashMap<String, ObjectIdentifier> RFC1779_NAMES
+ = new HashMap<String, ObjectIdentifier>(10);
- // Common name attribute (name from RFC 1779)
- private static final ObjectIdentifier CN;
+ /** known keywords attribute */
+ private static final HashMap<String, ObjectIdentifier> KNOWN_NAMES
+ = new HashMap<String, ObjectIdentifier>(30);
- // Domain component attribute (name from RFC 2253)
- private static final ObjectIdentifier DC;
+ /** known attribute types for RFC2253 (see 2.3. Converting AttributeTypeAndValue) */
+ private static final HashMap<String, ObjectIdentifier> RFC2253_NAMES
+ = new HashMap<String, ObjectIdentifier>(10);
- // DN qualifier attribute (name from API spec)
- private static final ObjectIdentifier DNQ;
+ /** known attribute types for RFC2459 (see API spec.) */
+ private static final HashMap<String, ObjectIdentifier> RFC2459_NAMES
+ = new HashMap<String, ObjectIdentifier>(10);
- private static final ObjectIdentifier DNQUALIFIER;
+ /** Country code attribute (name from RFC 1779) */
+ private static final ObjectIdentifier C
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 6 }, "C", RFC1779_NAMES);
- // Email Address attribute (name from API spec)
- private static final ObjectIdentifier EMAILADDRESS;
+ /** Common name attribute (name from RFC 1779) */
+ private static final ObjectIdentifier CN
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 3 }, "CN", RFC1779_NAMES);
- // Generation attribute (qualifies an individual's name)
- // (name from API spec)
- private static final ObjectIdentifier GENERATION;
+ /** Domain component attribute (name from RFC 2253) */
+ private static final ObjectIdentifier DC = new ObjectIdentifier(
+ new int[] { 0, 9, 2342, 19200300, 100, 1, 25 }, "DC", RFC2253_NAMES);
- // Given name attribute (name from API spec)
- private static final ObjectIdentifier GIVENNAME;
+ /** DN qualifier attribute (name from API spec) */
+ private static final ObjectIdentifier DNQ
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 46 }, "DNQ", RFC2459_NAMES);
- // Initials attribute (initials of an individual's name)
- // (name from API spec)
- private static final ObjectIdentifier INITIALS;
+ private static final ObjectIdentifier DNQUALIFIER
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 46 }, "DNQUALIFIER", RFC2459_NAMES);
- // Name of a locality attribute (name from RFC 1779)
- private static final ObjectIdentifier L;
+ /** Email Address attribute (name from API spec) */
+ private static final ObjectIdentifier EMAILADDRESS = new ObjectIdentifier(
+ new int[] { 1, 2, 840, 113549, 1, 9, 1}, "EMAILADDRESS", RFC2459_NAMES);
- // Organization name attribute (name from RFC 1779)
- private static final ObjectIdentifier O;
+ /** Generation attribute (qualifies an individual's name) (name from API spec) */
+ private static final ObjectIdentifier GENERATION
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 44 }, "GENERATION", RFC2459_NAMES);
- // Organizational unit name attribute (name from RFC 1779)
- private static final ObjectIdentifier OU;
+ /** Given name attribute (name from API spec) */
+ private static final ObjectIdentifier GIVENNAME
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 42 }, "GIVENNAME", RFC2459_NAMES);
- // Serial number attribute (serial number of a device)
- // (name from API spec)
- private static final ObjectIdentifier SERIALNUMBER;
+ /** Initials attribute (initials of an individual's name) (name from API spec) */
+ private static final ObjectIdentifier INITIALS
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 43 }, "INITIALS", RFC2459_NAMES);
- // Attribute for the full name of a state or province
- // (name from RFC 1779)
- private static final ObjectIdentifier ST;
+ /** Name of a locality attribute (name from RFC 1779) */
+ private static final ObjectIdentifier L
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 7 }, "L", RFC1779_NAMES);
- // Street attribute (name from RFC 1779)
- private static final ObjectIdentifier STREET;
+ /** Organization name attribute (name from RFC 1779) */
+ private static final ObjectIdentifier O
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 10 }, "O", RFC1779_NAMES);
- // Surname attribute (comes from an individual's parent name)
- // (name from API spec)
- private static final ObjectIdentifier SURNAME;
+ /** Organizational unit name attribute (name from RFC 1779) */
+ private static final ObjectIdentifier OU
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 11 }, "OU", RFC1779_NAMES);
- // Title attribute (object in an organization)(name from API spec)
- private static final ObjectIdentifier T;
+ /** Serial number attribute (serial number of a device) (name from API spec) */
+ private static final ObjectIdentifier SERIALNUMBER
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 5 }, "SERIALNUMBER", RFC2459_NAMES);
- // User identifier attribute (name from RFC 2253)
- private static final ObjectIdentifier UID;
+ /** Attribute for the full name of a state or province (name from RFC 1779) */
+ private static final ObjectIdentifier ST
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 8 }, "ST", RFC1779_NAMES);
- //
- // OID's pool
- //
+ /** Street attribute (name from RFC 1779) */
+ private static final ObjectIdentifier STREET
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 9 }, "STREET", RFC1779_NAMES);
- // pool's capacity
- private static final int CAPACITY;
+ /** Surname attribute (comes from an individual's parent name) (name from API spec) */
+ private static final ObjectIdentifier SURNAME
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 4 }, "SURNAME", RFC2459_NAMES);
- // pool's size
- private static final int SIZE;
+ /** Title attribute (object in an organization)(name from API spec) */
+ private static final ObjectIdentifier T
+ = new ObjectIdentifier(new int[] { 2, 5, 4, 12 }, "T", RFC2459_NAMES);
- // pool: contains all recognizable attribute type keywords
- private static final ObjectIdentifier[][] KNOWN_OIDS;
+ /** User identifier attribute (name from RFC 2253) */
+ private static final ObjectIdentifier UID = new ObjectIdentifier(
+ new int[]{ 0, 9, 2342, 19200300, 100, 1, 1 }, "UID", RFC2253_NAMES);
- // known keywords attribute
- private static final HashMap KNOWN_NAMES = new HashMap(30);
+ /** pool's capacity */
+ private static final int CAPACITY = 10;
- // known attribute types for RFC1779 (see Table 1)
- private static final HashMap RFC1779_NAMES = new HashMap(10);
+ /** pool's size */
+ private static final int SIZE = 10;
- // known attribute types for RFC2253
- // (see 2.3. Converting AttributeTypeAndValue)
- private static final HashMap RFC2253_NAMES = new HashMap(10);
-
- // known attribute types for RFC2459 (see API spec.)
- private static final HashMap RFC2459_NAMES = new HashMap(10);
+ /** pool: contains all recognizable attribute type keywords */
+ private static final ObjectIdentifier[][] KNOWN_OIDS = new ObjectIdentifier[SIZE][CAPACITY];
static {
-
- // pool initialization
- CAPACITY = 10;
- SIZE = 10;
- KNOWN_OIDS = new ObjectIdentifier[SIZE][CAPACITY];
-
- // init known attribute type keywords
- C = new ObjectIdentifier(new int[] { 2, 5, 4, 6 }, "C", RFC1779_NAMES);
- CN = new ObjectIdentifier(new int[] { 2, 5, 4, 3 }, "CN", RFC1779_NAMES);
-
- DC = new ObjectIdentifier(
- new int[] { 0, 9, 2342, 19200300, 100, 1, 25 }, "DC",
- RFC2253_NAMES);
- // DN qualifier aliases
- DNQ = new ObjectIdentifier(new int[] { 2, 5, 4, 46 }, "DNQ",
- RFC2459_NAMES);
- DNQUALIFIER = new ObjectIdentifier(new int[] { 2, 5, 4, 46 },
- "DNQUALIFIER", RFC2459_NAMES);
-
- EMAILADDRESS = new ObjectIdentifier(new int[] { 1, 2, 840, 113549, 1,
- 9, 1 }, "EMAILADDRESS", RFC2459_NAMES);
-
- GENERATION = new ObjectIdentifier(new int[] { 2, 5, 4, 44 },
- "GENERATION", RFC2459_NAMES);
- GIVENNAME = new ObjectIdentifier(new int[] { 2, 5, 4, 42 },
- "GIVENNAME", RFC2459_NAMES);
-
- INITIALS = new ObjectIdentifier(new int[] { 2, 5, 4, 43 }, "INITIALS",
- RFC2459_NAMES);
-
- L = new ObjectIdentifier(new int[] { 2, 5, 4, 7 }, "L", RFC1779_NAMES);
-
- O = new ObjectIdentifier(new int[] { 2, 5, 4, 10 }, "O", RFC1779_NAMES);
- OU = new ObjectIdentifier(new int[] { 2, 5, 4, 11 }, "OU",
- RFC1779_NAMES);
-
- SERIALNUMBER = new ObjectIdentifier(new int[] { 2, 5, 4, 5 },
- "SERIALNUMBER", RFC2459_NAMES);
- ST = new ObjectIdentifier(new int[] { 2, 5, 4, 8 }, "ST", RFC1779_NAMES);
- STREET = new ObjectIdentifier(new int[] { 2, 5, 4, 9 }, "STREET",
- RFC1779_NAMES);
- SURNAME = new ObjectIdentifier(new int[] { 2, 5, 4, 4 }, "SURNAME",
- RFC2459_NAMES);
-
- T = new ObjectIdentifier(new int[] { 2, 5, 4, 12 }, "T", RFC2459_NAMES);
-
- UID = new ObjectIdentifier(
- new int[] { 0, 9, 2342, 19200300, 100, 1, 1 }, "UID",
- RFC2253_NAMES);
-
- //
- // RFC1779
- //
RFC1779_NAMES.put(CN.getName(), CN);
RFC1779_NAMES.put(L.getName(), L);
RFC1779_NAMES.put(ST.getName(), ST);
@@ -190,17 +148,10 @@
RFC1779_NAMES.put(C.getName(), C);
RFC1779_NAMES.put(STREET.getName(), STREET);
- //
- // RFC2253: includes all from RFC1779
- //
RFC2253_NAMES.putAll(RFC1779_NAMES);
-
RFC2253_NAMES.put(DC.getName(), DC);
RFC2253_NAMES.put(UID.getName(), UID);
- //
- // RFC2459
- //
RFC2459_NAMES.put(DNQ.getName(), DNQ);
RFC2459_NAMES.put(DNQUALIFIER.getName(), DNQUALIFIER);
RFC2459_NAMES.put(EMAILADDRESS.getName(), EMAILADDRESS);
@@ -211,45 +162,31 @@
RFC2459_NAMES.put(SURNAME.getName(), SURNAME);
RFC2459_NAMES.put(T.getName(), T);
- //
- // Init KNOWN_OIDS pool
- //
-
// add from RFC2253 (includes RFC1779)
- Iterator it = RFC2253_NAMES.values().iterator();
- while (it.hasNext()) {
- addOID((ObjectIdentifier) it.next());
+ for (ObjectIdentifier objectIdentifier : RFC2253_NAMES.values()) {
+ addOID(objectIdentifier);
}
// add attributes from RFC2459
- it = RFC2459_NAMES.values().iterator();
- while (it.hasNext()) {
- Object o = it.next();
-
+ for (ObjectIdentifier o : RFC2459_NAMES.values()) {
//don't add DNQUALIFIER because it has the same oid as DNQ
if (!(o == DNQUALIFIER)) {
- addOID((ObjectIdentifier) o);
+ addOID(o);
}
}
- //
- // Init KNOWN_NAMES pool
- //
-
KNOWN_NAMES.putAll(RFC2253_NAMES); // RFC2253 includes RFC1779
KNOWN_NAMES.putAll(RFC2459_NAMES);
}
- //Attribute type
+ /** Attribute type */
private final ObjectIdentifier oid;
- //Attribute value
+ /** Attribute value */
private final AttributeValue value;
// for decoder only
- private AttributeTypeAndValue(int[] oid, AttributeValue value)
- throws IOException {
-
+ private AttributeTypeAndValue(int[] oid, AttributeValue value) throws IOException {
ObjectIdentifier thisOid = getOID(oid);
if (thisOid == null) {
thisOid = new ObjectIdentifier(oid);
@@ -269,13 +206,9 @@
* @throws IOException
* if OID can not be created from its string representation
*/
- public AttributeTypeAndValue(String sOid, AttributeValue value)
- throws IOException {
+ public AttributeTypeAndValue(String sOid, AttributeValue value) throws IOException {
if (sOid.charAt(0) >= '0' && sOid.charAt(0) <= '9') {
-
- int[] array = org.apache.harmony.security.asn1.ObjectIdentifier
- .toIntArray(sOid);
-
+ int[] array = org.apache.harmony.security.asn1.ObjectIdentifier.toIntArray(sOid);
ObjectIdentifier thisOid = getOID(array);
if (thisOid == null) {
thisOid = new ObjectIdentifier(array);
@@ -283,7 +216,7 @@
this.oid = thisOid;
} else {
- this.oid = (ObjectIdentifier) KNOWN_NAMES.get(Util.toUpperCase(sOid));
+ this.oid = KNOWN_NAMES.get(sOid.toUpperCase(Locale.US));
if (this.oid == null) {
throw new IOException("Unrecognizable attribute name: " + sOid);
}
@@ -298,7 +231,6 @@
* @param buf - string buffer to be used
*/
public void appendName(String attrFormat, StringBuffer buf) {
-
boolean hexFormat = false;
if (X500Principal.RFC1779.equals(attrFormat)) {
if (RFC1779_NAMES == oid.getGroup()) {
@@ -309,8 +241,7 @@
buf.append('=');
if (value.escapedString == value.getHexString()) {
- //FIXME all chars in upper case
- buf.append(Util.toUpperCase(value.getHexString()));
+ buf.append(value.getHexString().toUpperCase(Locale.US));
} else if (value.escapedString.length() != value.rawString.length()) {
// was escaped
value.appendQEString(buf);
@@ -326,15 +257,13 @@
if (X500Principal.CANONICAL.equals(attrFormat)) {
// only PrintableString and UTF8String in string format
// all others are output in hex format
- // BEGIN android-changed
- // no hex for teletex; see bug 2102191
+ // no hex for teletex; see http://b/2102191
int tag = value.getTag();
if (!ASN1StringType.UTF8STRING.checkTag(tag)
&& !ASN1StringType.PRINTABLESTRING.checkTag(tag)
&& !ASN1StringType.TELETEXSTRING.checkTag(tag)) {
hexFormat = true;
}
- // END android-changed
}
} else {
@@ -358,8 +287,6 @@
/**
* Gets type of the AttributeTypeAndValue
- *
- * @return ObjectIdentifier
*/
public ObjectIdentifier getType() {
return oid;
@@ -385,16 +312,13 @@
* bmpString BMPString (SIZE (1..MAX)) }
*
*/
-
- public static final ASN1Type attributeValue = new ASN1Type(
- ASN1Constants.TAG_PRINTABLESTRING) {
+ public static final ASN1Type attributeValue = new ASN1Type(ASN1Constants.TAG_PRINTABLESTRING) {
public boolean checkTag(int tag) {
return true;
}
public Object decode(BerInputStream in) throws IOException {
-
// FIXME what about constr???
String str = null;
if (DirectoryString.ASN1.checkTag(in.tag)) {
@@ -412,7 +336,7 @@
return new AttributeValue(str, bytesEncoded, in.tag);
}
- public Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
// stub to avoid wrong decoder usage
throw new RuntimeException("AttributeValue getDecodedObject MUST NOT be invoked");
}
@@ -421,7 +345,6 @@
// Encode
//
public void encodeASN(BerOutputStream out) {
-
AttributeValue av = (AttributeValue) out.content;
if (av.encoded != null) {
@@ -435,19 +358,14 @@
}
public void setEncodingContent(BerOutputStream out) {
-
AttributeValue av = (AttributeValue) out.content;
if (av.encoded != null) {
out.length = av.encoded.length;
} else {
-
if (av.getTag() == ASN1Constants.TAG_UTF8STRING) {
-
out.content = av.rawString;
-
ASN1StringType.UTF8STRING.setEncodingContent(out);
-
av.bytes = (byte[]) out.content;
out.content = av;
} else {
@@ -462,10 +380,8 @@
throw new RuntimeException("AttributeValue encodeContent MUST NOT be invoked");
}
- public int getEncodedLength(BerOutputStream out) { //FIXME name
-
+ @Override public int getEncodedLength(BerOutputStream out) { //FIXME name
AttributeValue av = (AttributeValue) out.content;
-
if (av.encoded != null) {
return out.length;
} else {
@@ -477,23 +393,22 @@
public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
ASN1Oid.getInstance(), attributeValue }) {
- protected Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
Object[] values = (Object[]) in.content;
- return new AttributeTypeAndValue((int[]) values[0],
- (AttributeValue) values[1]);
+ return new AttributeTypeAndValue((int[]) values[0], (AttributeValue) values[1]);
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
AttributeTypeAndValue atav = (AttributeTypeAndValue) object;
-
values[0] = atav.oid.getOid();
values[1] = atav.value;
}
};
- // returns known OID or null
+ /**
+ * Returns known OID or null.
+ */
private static ObjectIdentifier getOID(int[] oid) {
-
int index = hashIntArray(oid) % CAPACITY;
// look for OID in the pool
@@ -506,10 +421,11 @@
return null;
}
- // adds known OID to pool
- // for static AttributeTypeAndValue initialization only
+ /**
+ * Adds known OID to pool.
+ * for static AttributeTypeAndValue initialization only
+ */
private static void addOID(ObjectIdentifier oid) {
-
int[] newOid = oid.getOid();
int index = hashIntArray(newOid) % CAPACITY;
@@ -517,7 +433,6 @@
ObjectIdentifier[] list = KNOWN_OIDS[index];
int i = 0;
for (; list[i] != null; i++) {
-
// check wrong static initialization: no duplicate OIDs
if (Arrays.equals(newOid, list[i].getOid())) {
throw new Error("ObjectIdentifier: invalid static initialization; " +
@@ -533,7 +448,9 @@
list[i] = oid;
}
- // returns hash for array of integers
+ /**
+ * Returns hash for array of integers.
+ */
private static int hashIntArray(int[] oid) {
int intHash = 0;
for (int i = 0; i < oid.length && i < 4; i++) {
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
index ecce1e0..3b9226c 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/AttributeValue.java
@@ -31,7 +31,7 @@
/**
* X.501 Attribute Value
*/
-public class AttributeValue {
+public final class AttributeValue {
public final boolean wasEncoded;
@@ -47,8 +47,9 @@
public boolean hasQE; // raw string contains '"' or '\'
- public AttributeValue(String parsedString, boolean hasQorE) {
+ public String rawString;
+ public AttributeValue(String parsedString, boolean hasQorE) {
wasEncoded = false;
this.hasQE = hasQorE;
@@ -58,7 +59,6 @@
}
public AttributeValue(String hexString, byte[] encoded) {
-
wasEncoded = true;
this.hexString = hexString;
@@ -84,10 +84,7 @@
}
}
- public String rawString;
-
public AttributeValue(String rawString, byte[] encoded, int tag) {
-
wasEncoded = true;
this.encoded = encoded;
@@ -115,7 +112,6 @@
public String getHexString() {
if (hexString == null) {
-
if (!wasEncoded) {
//FIXME optimize me: what about reusable OutputStream???
if (Utils.isPrintableString(rawString)) {
@@ -165,16 +161,15 @@
buf.append('"');
}
- //
- // Escapes:
- // 1) chars ",", "+", """, "\", "<", ">", ";" (RFC 2253)
- // 2) chars "#", "=" (required by RFC 1779)
- // 3) a space char at the beginning or end
- // 4) according to the requirement to be RFC 1779 compatible:
- // '#' char is escaped in any position
- //
+ /**
+ * Escapes:
+ * 1) chars ",", "+", """, "\", "<", ">", ";" (RFC 2253)
+ * 2) chars "#", "=" (required by RFC 1779)
+ * 3) a space char at the beginning or end
+ * 4) according to the requirement to be RFC 1779 compatible:
+ * '#' char is escaped in any position
+ */
private String makeEscaped(String name) {
-
int length = name.length();
if (length == 0) {
return name;
@@ -220,7 +215,6 @@
}
public String makeCanonical() {
-
int length = rawString.length();
if (length == 0) {
return rawString;
@@ -236,11 +230,9 @@
int bufLength;
for (; index < length; index++) {
-
char ch = rawString.charAt(index);
switch (ch) {
-
case ' ':
bufLength = buf.length();
if (bufLength == 0 || buf.charAt(bufLength - 1) == ' ') {
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/Attributes.java b/luni/src/main/java/org/apache/harmony/security/x501/Attributes.java
deleted file mode 100644
index 294fc8f..0000000
--- a/luni/src/main/java/org/apache/harmony/security/x501/Attributes.java
+++ /dev/null
@@ -1,60 +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.
- */
-/**
-* @author Stepan M. Mishura
-* @version $Revision$
-*/
-
-package org.apache.harmony.security.x501;
-
-import org.apache.harmony.security.asn1.ASN1OpenType;
-import org.apache.harmony.security.asn1.ASN1Sequence;
-import org.apache.harmony.security.asn1.ASN1SetOf;
-import org.apache.harmony.security.asn1.ASN1Type;
-import org.apache.harmony.security.asn1.InformationObjectSet;
-
-
-/**
- * X.501 Attributes
- *
- * This is a draft class for Module InformationFramework (X.501).
- *
- * @see <a href="http://www.itu.int/ITU-T/asn1/database/itu-t/x/x501/2001/InformationFramework.html">X.501</a>
- */
-
-public class Attributes {
-
-
- /**
- * The class corresponds to following ASN.1 type:
- *
- * Attribute ::= SEQUENCE {
- * type AttributeType,
- * values SET SIZE (0..MAX) OF AttributeValue }
- *
- * AttributeType ::= OBJECT IDENTIFIER
- *
- * AttributeValue ::= ANY DEFINED BY AttributeType
- *
- */
- public static ASN1Sequence getASN1(InformationObjectSet set) {
- ASN1OpenType.Id id = new ASN1OpenType.Id();
- ASN1OpenType any = new ASN1OpenType(id, set);
-
- return new ASN1Sequence(new ASN1Type[] { id, new ASN1SetOf(any) });
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/DirectoryString.java b/luni/src/main/java/org/apache/harmony/security/x501/DirectoryString.java
index 9c1eba6..902442f 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/DirectoryString.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/DirectoryString.java
@@ -45,7 +45,7 @@
* }
* </pre>
*/
-public class DirectoryString {
+public final class DirectoryString {
public static final ASN1Choice ASN1 = new ASN1Choice(new ASN1Type[] {
ASN1StringType.TELETEXSTRING,
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/Name.java b/luni/src/main/java/org/apache/harmony/security/x501/Name.java
index c3c4ffd..40ef852 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/Name.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/Name.java
@@ -23,10 +23,10 @@
package org.apache.harmony.security.x501;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
-import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.security.auth.x500.X500Principal;
@@ -40,22 +40,22 @@
/**
* X.501 Name
*/
-public class Name {
+public final class Name {
- //ASN.1 DER encoding of Name
+ /** ASN.1 DER encoding of Name */
private volatile byte[] encoded;
- // RFC1779 string
+ /** RFC1779 string */
private String rfc1779String;
- // RFC2253 string
+ /** RFC2253 string */
private String rfc2253String;
- //CANONICAL string
+ /** CANONICAL string */
private String canonicalString;
- //Collection of RDNs
- private List rdn;
+ /** Collection of RDNs */
+ private List<List<AttributeTypeAndValue>> rdn;
/**
* Creates new <code>Name</code> instance from its DER encoding
@@ -64,7 +64,6 @@
* @throws IOException - if encoding is wrong
*/
public Name(byte[] encoding) throws IOException {
-
DerInputStream in = new DerInputStream(encoding);
if (in.getEndOffset() != encoding.length) {
@@ -73,7 +72,7 @@
ASN1.decode(in);
- this.rdn = (List) in.content;
+ this.rdn = (List<List<AttributeTypeAndValue>>) in.content;
}
/**
@@ -86,8 +85,7 @@
rdn = new DNParser(name).parse();
}
- // Creates Name instance
- private Name(List rdn) {
+ private Name(List<List<AttributeTypeAndValue>> rdn) {
this.rdn = rdn;
}
@@ -105,13 +103,10 @@
* Returns Relative Distinguished Name as <code>String</code> according
* the format requested
*
- * @param format
- * Name format requested
- * @return Relative Distinguished Name as <code>String</code> according
- * the format requested
+ * @param format one of X500Principal.CANONICAL, X500Principal.RFC1779, or
+ * X500Principal.RFC2253, case insensitive
*/
public String getName(String format) {
-
//
// check X500Principal constants first
//
@@ -169,31 +164,24 @@
/**
* Returns Relative Distinguished Name as <code>String</code> according
* the format requested, format is int value
- *
- * @param format
- * Name format requested
- * @return Relative Distinguished Name as <code>String</code> according
- * the format requested
*/
private String getName0(String format) {
-
StringBuffer name = new StringBuffer();
// starting with the last element and moving to the first.
for (int i = rdn.size() - 1; i >= 0; i--) {
- List atavList = (List) rdn.get(i);
+ List<AttributeTypeAndValue> atavList = rdn.get(i);
if (X500Principal.CANONICAL == format) {
- List sortedList = new LinkedList(atavList);
- Collections.sort(sortedList, new AttributeTypeAndValueComparator());
- atavList = sortedList;
+ atavList = new ArrayList<AttributeTypeAndValue>(atavList);
+ Collections.sort(atavList, new AttributeTypeAndValueComparator());
}
// Relative Distinguished Name to string
- Iterator it = atavList.iterator();
+ Iterator<AttributeTypeAndValue> it = atavList.iterator();
while (it.hasNext()) {
- AttributeTypeAndValue _ava = (AttributeTypeAndValue) it.next();
- _ava.appendName(format, name);
+ AttributeTypeAndValue attributeTypeAndValue = it.next();
+ attributeTypeAndValue.appendName(format, name);
if (it.hasNext()) {
// multi-valued RDN
if (X500Principal.RFC1779 == format) {
@@ -244,18 +232,17 @@
* SET OF AttributeTypeAndValue
*
*/
-
public static final ASN1SetOf ASN1_RDN = new ASN1SetOf(
AttributeTypeAndValue.ASN1);
public static final ASN1SequenceOf ASN1 = new ASN1SequenceOf(ASN1_RDN) {
public Object getDecodedObject(BerInputStream in) {
- return new Name((List) in.content);
+ return new Name((List<List<AttributeTypeAndValue>>) in.content);
}
public Collection getValues(Object object) {
- return ((Name) object).rdn; //FIXME what about get method?
+ return ((Name) object).rdn;
}
};
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/AccessDescription.java b/luni/src/main/java/org/apache/harmony/security/x509/AccessDescription.java
index c539f37..0f2fe6d 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/AccessDescription.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/AccessDescription.java
@@ -34,25 +34,18 @@
* AccessDescription ::= SEQUENCE {
* accessMethod OBJECT IDENTIFIER,
* accessLocation GeneralName }
- *
*/
-public class AccessDescription {
+public final class AccessDescription {
- // the value of access method
+ /** the value of access method */
private final String accessMethod;
- // the value of accessLocation
+ /** the value of accessLocation */
private final GeneralName accessLocation;
- private byte [] encoding;
+ private byte[] encoding;
- public AccessDescription(String accessMethod, GeneralName accessLocation) {
- this.accessMethod = accessMethod;
- this.accessLocation = accessLocation;
- }
-
- private AccessDescription(String accessMethod, GeneralName accessLocation,
- byte[] encoding) {
+ private AccessDescription(String accessMethod, GeneralName accessLocation, byte[] encoding) {
this.accessMethod = accessMethod;
this.accessLocation = accessLocation;
this.encoding = encoding;
@@ -60,7 +53,6 @@
/**
* Returns ASN.1 encoded form of this X.509 AccessDescription.
- * @return a byte array containing ASN.1 encoded form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -69,7 +61,7 @@
return encoding;
}
- public String toString() {
+ @Override public String toString() {
StringBuilder res = new StringBuilder();
res.append("\n-- AccessDescription:");
res.append("\naccessMethod: ");
@@ -81,41 +73,24 @@
}
/**
- * @return Returns the accessLocation.
- */
- public GeneralName getAccessLocation() {
- return accessLocation;
- }
-
- /**
- * @return Returns the accessMethod.
- */
- public String getAccessMethod() {
- return accessMethod;
- }
-
- /**
* Custom AccessDescription DER encoder/decoder
*/
public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
ASN1Oid.getInstance(),
GeneralName.ASN1 }) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new AccessDescription(
ObjectIdentifier.toString((int[]) values[0]),
(GeneralName) values[1], in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
AccessDescription ad = (AccessDescription) object;
-
values[0] = ObjectIdentifier.toIntArray(ad.accessMethod);
values[1] = ad.accessLocation;
}
};
-
}
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 9298ba5..f0fa49f 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
@@ -47,42 +47,25 @@
* }
* </pre>
*/
-public class AlgorithmIdentifier {
-
- // the value of algorithm field
+public final class AlgorithmIdentifier {
+ /** the value of algorithm field */
private String algorithm;
- // the name of the algorithm
+ /** the name of the algorithm */
private String algorithmName;
- // the value of parameters field
+ /** the value of parameters field */
private byte[] parameters;
- // the encoding of AlgorithmIdentifier value
+ /** the encoding of AlgorithmIdentifier value */
private byte[] encoding;
- /**
- * TODO
- * @param algorithm: String
- */
public AlgorithmIdentifier(String algorithm) {
this(algorithm, null, null);
}
- /**
- * TODO
- * @param algorithm: String
- * @param parameters: byte[]
- */
public AlgorithmIdentifier(String algorithm, byte[] parameters) {
this(algorithm, parameters, null);
}
- //
- // TODO
- // @param algorithm: String
- // @param parameters: byte[]
- // @param encoding: byte[]
- //
- private AlgorithmIdentifier(String algorithm, byte[] parameters,
- byte[] encoding) {
+ private AlgorithmIdentifier(String algorithm, byte[] parameters, byte[] encoding) {
this.algorithm = algorithm;
this.parameters = parameters;
this.encoding = encoding;
@@ -90,7 +73,6 @@
/**
* Returns the value of algorithm field of the structure.
- * @return algorithm
*/
public String getAlgorithm() {
return algorithm;
@@ -100,7 +82,6 @@
* Returns the name of the algorithm corresponding to
* its OID. If there is no the such correspondence,
* algorithm OID is returned.
- * @return algorithm
*/
public String getAlgorithmName() {
if (algorithmName == null) {
@@ -114,7 +95,6 @@
/**
* Returns the value of parameters field of the structure.
- * @return parameters
*/
public byte[] getParameters() {
return parameters;
@@ -122,7 +102,6 @@
/**
* Returns ASN.1 encoded form of this X.509 AlgorithmIdentifier value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -131,7 +110,7 @@
return encoding;
}
- public boolean equals(Object ai) {
+ @Override public boolean equals(Object ai) {
if (!(ai instanceof AlgorithmIdentifier)) {
return false;
}
@@ -142,7 +121,7 @@
: Arrays.equals(parameters, algid.parameters));
}
- public int hashCode() {
+ @Override public int hashCode() {
return algorithm.hashCode() * 37 + (parameters != null ? parameters.hashCode() : 0);
}
@@ -169,13 +148,13 @@
setOptional(1); // parameters are optional
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new AlgorithmIdentifier(ObjectIdentifier
.toString((int[]) values[0]), (byte[]) values[1]);
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
AlgorithmIdentifier aID = (AlgorithmIdentifier) object;
@@ -183,5 +162,4 @@
values[1] = aID.getParameters();
}
};
-
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/AlternativeName.java b/luni/src/main/java/org/apache/harmony/security/x509/AlternativeName.java
index 0e84512..48e4376 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/AlternativeName.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/AlternativeName.java
@@ -18,7 +18,6 @@
package org.apache.harmony.security.x509;
import java.io.IOException;
-import java.util.List;
/**
* This class implements the values of Subject Alternative Name
@@ -27,29 +26,19 @@
* For more information about these extensions see RFC 3280
* at http://www.ietf.org/rfc/rfc3280.txt
*/
-public class AlternativeName extends ExtensionValue {
+public final class AlternativeName extends ExtensionValue {
// constants indicating which alternative name is presented
// by this object
public static final boolean ISSUER = false;
public static final boolean SUBJECT = true;
- // indicating which alternative name is presented by this object
+ /** indicating which alternative name is presented by this object */
private boolean which;
- // the alternative names
+ /** the alternative names */
private GeneralNames alternativeNames;
/**
- * Creates the extension object for given alternative names.
- * @param which specifies which alternative names are given
- * (Subject's or Issuer's)
- */
- public AlternativeName(boolean which, GeneralNames alternativeNames) {
- this.which = which;
- this.alternativeNames = alternativeNames;
- }
-
- /**
* Creates the extension object on the base of its encoded form.
* @param which specifies which alternative names are given
* (Subject's or Issuer's)
@@ -57,24 +46,13 @@
public AlternativeName(boolean which, byte[] encoding) throws IOException {
super(encoding);
this.which = which;
- this.alternativeNames =
- (GeneralNames) GeneralNames.ASN1.decode(encoding);
- }
-
- /**
- * Returns the list of alternative names.
- * The list is in the collection of pairs:<br>
- * [Integer (tag of GeneralName), Object (name value)]
- */
- public List getAlternativeNames() {
- return alternativeNames.getPairsList();
+ this.alternativeNames = (GeneralNames) GeneralNames.ASN1.decode(encoding);
}
/**
* Returns ASN.1 encoded form of this X.509 AlternativeName value.
- * @return a byte array containing ASN.1 encode form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = GeneralNames.ASN1.encode(alternativeNames);
}
@@ -85,7 +63,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append((which) ? "Subject" : "Issuer")
.append(" Alternative Names [\n");
alternativeNames.dumpValue(buffer, prefix + " ");
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/AuthorityKeyIdentifier.java b/luni/src/main/java/org/apache/harmony/security/x509/AuthorityKeyIdentifier.java
index ad07476..381c2b2 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/AuthorityKeyIdentifier.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/AuthorityKeyIdentifier.java
@@ -51,8 +51,7 @@
* KeyIdentifier ::= OCTET STRING
* </pre>
*/
-public class AuthorityKeyIdentifier extends ExtensionValue {
-
+public final class AuthorityKeyIdentifier extends ExtensionValue {
private final byte[] keyIdentifier;
private final GeneralNames authorityCertIssuer;
private final BigInteger authorityCertSerialNumber;
@@ -65,15 +64,13 @@
this.authorityCertSerialNumber = authorityCertSerialNumber;
}
- public static AuthorityKeyIdentifier decode(byte[] encoding)
- throws IOException {
- AuthorityKeyIdentifier aki =
- (AuthorityKeyIdentifier) ASN1.decode(encoding);
+ public static AuthorityKeyIdentifier decode(byte[] encoding) throws IOException {
+ AuthorityKeyIdentifier aki = (AuthorityKeyIdentifier) ASN1.decode(encoding);
aki.encoding = encoding;
return aki;
}
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
@@ -84,7 +81,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("AuthorityKeyIdentifier [\n");
if (keyIdentifier != null) {
buffer.append(prefix).append(" keyIdentifier:\n");
@@ -114,7 +111,7 @@
setOptional(2);
}
- protected Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
Object[] values = (Object[]) in.content;
byte[] enc = (byte[]) values[2];
@@ -127,10 +124,8 @@
(GeneralNames) values[1], authorityCertSerialNumber);
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
AuthorityKeyIdentifier akid = (AuthorityKeyIdentifier) object;
-
values[0] = akid.keyIdentifier;
values[1] = akid.authorityCertIssuer;
if (akid.authorityCertSerialNumber != null) {
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/BasicConstraints.java b/luni/src/main/java/org/apache/harmony/security/x509/BasicConstraints.java
index 214b3a8..ccb8d10 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/BasicConstraints.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/BasicConstraints.java
@@ -34,46 +34,30 @@
* id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
*
* BasicConstraints ::= SEQUENCE {
- * cA BOOLEAN DEFAULT FALSE,
+ * ca BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL
* }
* </pre>
* (as specified in RFC 3280)
*/
-public class BasicConstraints extends ExtensionValue {
-
- // is CA
- private boolean cA = false;
- // path len constraint
+public final class BasicConstraints extends ExtensionValue {
+ /** is CA */
+ private boolean ca = false;
+ /** path len constraint */
private int pathLenConstraint = Integer.MAX_VALUE;
- // Constructor for creating the extension without
- // encoding provided
- /**
- * Creates the extension object on the base of the values of
- * fields of the structure..
- */
- public BasicConstraints(boolean cA, int pathLenConstraint) {
- this.cA = cA;
- this.pathLenConstraint = pathLenConstraint;
- }
-
/**
* Creates the extension object on the base of its encoded form.
*/
public BasicConstraints(byte[] encoding) throws IOException {
super(encoding);
Object[] values = (Object[]) ASN1.decode(encoding);
- cA = ((Boolean) values[0]).booleanValue();
+ ca = (Boolean) values[0];
if (values[1] != null) {
pathLenConstraint = new BigInteger((byte[]) values[1]).intValue();
}
}
- public boolean getCA() {
- return cA;
- }
-
public int getPathLenConstraint() {
return pathLenConstraint;
}
@@ -83,9 +67,7 @@
*/
public byte[] getEncoded() {
if (encoding == null) {
- encoding = ASN1.encode(
- new Object[] {Boolean.valueOf(cA),
- BigInteger.valueOf(pathLenConstraint)});
+ encoding = ASN1.encode(new Object[]{ca, BigInteger.valueOf(pathLenConstraint) });
}
return encoding;
}
@@ -96,7 +78,7 @@
*/
public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("BasicConstraints [\n").append(prefix)
- .append(" CA: ").append(cA)
+ .append(" CA: ").append(ca)
.append("\n ").append(prefix).append("pathLenConstraint: ")
.append(pathLenConstraint).append('\n').append(prefix)
.append("]\n");
@@ -112,16 +94,14 @@
setOptional(1);
}
- public Object getDecodedObject(BerInputStream in)
- throws IOException {
+ public Object getDecodedObject(BerInputStream in) throws IOException {
return in.content;
}
protected void getValues(Object object, Object[] values) {
- Object[] vals = (Object[]) object;
- values[0] = (Boolean) vals[0];
- values[1] = ((BigInteger) vals[1]).toByteArray();
+ Object[] array = (Object[]) object;
+ values[0] = array[0];
+ values[1] = ((BigInteger) array[1]).toByteArray();
}
-
};
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/CRLDistributionPoints.java b/luni/src/main/java/org/apache/harmony/security/x509/CRLDistributionPoints.java
index 781de29..b3db0c5 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/CRLDistributionPoints.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/CRLDistributionPoints.java
@@ -24,7 +24,6 @@
import java.io.IOException;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import org.apache.harmony.security.asn1.ASN1SequenceOf;
import org.apache.harmony.security.asn1.ASN1Type;
@@ -65,19 +64,11 @@
* }
* </pre>
*/
-public class CRLDistributionPoints extends ExtensionValue {
-
- private List distributionPoints;
+public final class CRLDistributionPoints extends ExtensionValue {
+ private List<DistributionPoint> distributionPoints;
private byte[] encoding;
- public CRLDistributionPoints(List distributionPoints) {
- if ((distributionPoints == null) || (distributionPoints.size() == 0)) {
- throw new IllegalArgumentException("distributionPoints are empty");
- }
- this.distributionPoints = distributionPoints;
- }
-
- public CRLDistributionPoints(List distributionPoints, byte[] encoding) {
+ private CRLDistributionPoints(List<DistributionPoint> distributionPoints, byte[] encoding) {
if ((distributionPoints == null) || (distributionPoints.size() == 0)) {
throw new IllegalArgumentException("distributionPoints are empty");
}
@@ -85,30 +76,27 @@
this.encoding = encoding;
}
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
return encoding;
}
- public static CRLDistributionPoints decode(byte[] encoding)
- throws IOException {
- CRLDistributionPoints cdp = (CRLDistributionPoints) ASN1.decode(encoding);
- return cdp;
+ public static CRLDistributionPoints decode(byte[] encoding) throws IOException {
+ return (CRLDistributionPoints) ASN1.decode(encoding);
}
/**
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("CRL Distribution Points: [\n");
int number = 0;
- for (Iterator it=distributionPoints.iterator();
- it.hasNext();) {
+ for (DistributionPoint distributionPoint : distributionPoints) {
buffer.append(prefix).append(" [").append(++number).append("]\n");
- ((DistributionPoint) it.next()).dumpValue(buffer, prefix + " ");
+ distributionPoint.dumpValue(buffer, prefix + " ");
}
buffer.append(prefix).append("]\n");
}
@@ -116,15 +104,12 @@
/**
* Custom X.509 decoder.
*/
- public static final ASN1Type ASN1 =
- new ASN1SequenceOf(DistributionPoint.ASN1) {
-
- public Object getDecodedObject(BerInputStream in) {
- return new CRLDistributionPoints((List)in.content,
- in.getEncoded());
+ public static final ASN1Type ASN1 = new ASN1SequenceOf(DistributionPoint.ASN1) {
+ @Override public Object getDecodedObject(BerInputStream in) {
+ return new CRLDistributionPoints((List<DistributionPoint>) in.content, in.getEncoded());
}
- public Collection getValues(Object object) {
+ @Override public Collection<?> getValues(Object object) {
CRLDistributionPoints dps = (CRLDistributionPoints) object;
return dps.distributionPoints;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/CRLNumber.java b/luni/src/main/java/org/apache/harmony/security/x509/CRLNumber.java
index 72a20ec..5396bea 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/CRLNumber.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/CRLNumber.java
@@ -33,19 +33,11 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt)
*/
-public class CRLNumber extends ExtensionValue {
-
- // crl number value
+public final class CRLNumber extends ExtensionValue {
+ /** crl number value */
private final BigInteger number;
/**
- * Constructs the object on the base of the invalidity date value.
- */
- public CRLNumber(BigInteger number) {
- this.number = number;
- }
-
- /**
* Constructs the object on the base of its encoded form.
*/
public CRLNumber(byte[] encoding) throws IOException {
@@ -62,9 +54,8 @@
/**
* Returns ASN.1 encoded form of this X.509 CRLNumber value.
- * @return a byte array containing ASN.1 encoded form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(number.toByteArray());
}
@@ -75,9 +66,8 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
- buffer.append(prefix).append("CRL Number: [ ").append(number).append(
- " ]\n");
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
+ buffer.append(prefix).append("CRL Number: [ ").append(number).append(" ]\n");
}
/**
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Certificate.java b/luni/src/main/java/org/apache/harmony/security/x509/Certificate.java
index ca1abb0..5edf8d5 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Certificate.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Certificate.java
@@ -45,23 +45,16 @@
* }
* </pre>
*/
-public class Certificate {
-
- // the value of tbsCertificate field of the structure
+public final class Certificate {
+ /** the value of tbsCertificate field of the structure */
private final TBSCertificate tbsCertificate;
- // the value of signatureAlgorithm field of the structure
+ /** the value of signatureAlgorithm field of the structure */
private final AlgorithmIdentifier signatureAlgorithm;
- // the value of signatureValue field of the structure
+ /** the value of signatureValue field of the structure */
private final byte[] signatureValue;
- // the ASN.1 encoded form of Certificate
+ /** the ASN.1 encoded form of Certificate */
private byte[] encoding;
- /**
- * TODO
- * @param tbsCertificate: TBSCertificate
- * @param signatureAlgorithm: AlgorithmIdentifier
- * @param signatureValue: byte[]
- */
public Certificate(TBSCertificate tbsCertificate,
AlgorithmIdentifier signatureAlgorithm,
byte[] signatureValue) {
@@ -72,13 +65,6 @@
signatureValue.length);
}
- //
- // TODO
- // @param tbsCertificate: TBSCertificate
- // @param signatureAlgorithm: AlgorithmIdentifier
- // @param signatureValue: byte[]
- // @param encoding: byte[]
- //
private Certificate(TBSCertificate tbsCertificate,
AlgorithmIdentifier signatureAlgorithm,
byte[] signatureValue, byte[] encoding) {
@@ -88,31 +74,19 @@
/**
* Returns the value of tbsCertificate field of the structure.
- * @return tbsCertificate
*/
public TBSCertificate getTbsCertificate() {
return tbsCertificate;
}
/**
- * Returns the value of signatureAlgorithm field of the structure.
- * @return signatureAlgorithm
- */
- public AlgorithmIdentifier getSignatureAlgorithm() {
- return signatureAlgorithm;
- }
-
- /**
* Returns the value of signatureValue field of the structure.
- * @return signatureValue
*/
public byte[] getSignatureValue() {
- byte[] result = new byte[signatureValue.length];
- System.arraycopy(signatureValue, 0, result, 0, signatureValue.length);
- return result;
+ return signatureValue.clone();
}
- public String toString() {
+ @Override public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("X.509 Certificate:\n[\n");
tbsCertificate.dumpValue(buffer);
@@ -127,7 +101,6 @@
/**
* Returns ASN.1 encoded form of this X.509 TBSCertificate value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -143,20 +116,17 @@
new ASN1Sequence(new ASN1Type[]
{TBSCertificate.ASN1, AlgorithmIdentifier.ASN1, ASN1BitString.getInstance()}) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new Certificate(
(TBSCertificate) values[0],
(AlgorithmIdentifier) values[1],
((BitString) values[2]).bytes, // FIXME keep as BitString object
- in.getEncoded()
- );
+ in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
Certificate cert = (Certificate) object;
-
values[0] = cert.tbsCertificate;
values[1] = cert.signatureAlgorithm;
values[2] = new BitString(cert.signatureValue, 0);
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/CertificateIssuer.java b/luni/src/main/java/org/apache/harmony/security/x509/CertificateIssuer.java
index 4627a9b..3f37114 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/CertificateIssuer.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/CertificateIssuer.java
@@ -37,28 +37,17 @@
* In java implementation it is presumed that GeneralNames consist of
* one element and its type is directoryName.
*/
-public class CertificateIssuer extends ExtensionValue {
-
- // certificate issuer value
+public final class CertificateIssuer extends ExtensionValue {
+ /** certificate issuer value */
private X500Principal issuer;
/**
- * Creates an object on the base of GeneralName structure.
- */
- public CertificateIssuer(GeneralName issuer) {
- super(ASN1.encode(issuer));
- }
-
- /**
* Creates an object on the base of its encoded form.
*/
public CertificateIssuer(byte[] encoding) {
super(encoding);
}
- /**
- * Returns the issuer.
- */
public X500Principal getIssuer() throws IOException {
if (issuer == null) {
issuer = (X500Principal) ASN1.decode(getEncoded());
@@ -70,7 +59,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Certificate Issuer: ");
if (issuer == null) {
try {
@@ -87,15 +76,13 @@
/**
* ASN.1 Encoder/Decoder.
*/
- public static final ASN1Type ASN1 = new ASN1Sequence(new ASN1Type[] {
- GeneralName.ASN1
- }) {
- public Object getDecodedObject(BerInputStream in) {
+ public static final ASN1Type ASN1 = new ASN1Sequence(new ASN1Type[] { GeneralName.ASN1 }) {
+ @Override public Object getDecodedObject(BerInputStream in) {
return ((Name) ((GeneralName) ((Object[]) in.content)[0])
.getName()).getX500Principal();
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
values[0] = object;
}
};
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/CertificateList.java b/luni/src/main/java/org/apache/harmony/security/x509/CertificateList.java
index fbc170d..f588ef5 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/CertificateList.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/CertificateList.java
@@ -45,23 +45,16 @@
* }
* </pre>
*/
-public class CertificateList {
-
- // the value of tbsCertList field of the structure
+public final class CertificateList {
+ /** the value of tbsCertList field of the structure */
private final TBSCertList tbsCertList;
- // the value of signatureAlgorithm field of the structure
+ /** the value of signatureAlgorithm field of the structure */
private final AlgorithmIdentifier signatureAlgorithm;
- // the value of signatureValue field of the structure
+ /** the value of signatureValue field of the structure */
private final byte[] signatureValue;
- // the ASN.1 encoded form of CertList
+ /** the ASN.1 encoded form of CertList */
private byte[] encoding;
- /**
- * TODO
- * @param tbsCertList: TBSCertList
- * @param signatureAlgorithm: AlgorithmIdentifier
- * @param signatureValue: byte[]
- */
public CertificateList(TBSCertList tbsCertList,
AlgorithmIdentifier signatureAlgorithm,
byte[] signatureValue) {
@@ -72,13 +65,6 @@
signatureValue.length);
}
- //
- // TODO
- // @param tbsCertList: TBSCertList
- // @param signatureAlgorithm: AlgorithmIdentifier
- // @param signatureValue: byte[]
- // @param encoding: byte[]
- //
private CertificateList(TBSCertList tbsCertList,
AlgorithmIdentifier signatureAlgorithm,
byte[] signatureValue, byte[] encoding) {
@@ -88,23 +74,13 @@
/**
* Returns the value of tbsCertList field of the structure.
- * @return tbsCertList
*/
public TBSCertList getTbsCertList() {
return tbsCertList;
}
/**
- * Returns the value of signatureAlgorithm field of the structure.
- * @return signatureAlgorithm
- */
- public AlgorithmIdentifier getSignatureAlgorithm() {
- return signatureAlgorithm;
- }
-
- /**
* Returns the value of signatureValue field of the structure.
- * @return signatureValue
*/
public byte[] getSignatureValue() {
byte[] result = new byte[signatureValue.length];
@@ -112,7 +88,7 @@
return result;
}
- public String toString() {
+ @Override public String toString() {
StringBuffer res = new StringBuffer();
tbsCertList.dumpValue(res);
res.append("\nSignature Value:\n");
@@ -122,7 +98,6 @@
/**
* Returns ASN.1 encoded form of this X.509 TBSCertList value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -139,7 +114,7 @@
{TBSCertList.ASN1, AlgorithmIdentifier.ASN1,
ASN1BitString.getInstance()}) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new CertificateList(
(TBSCertList) values[0],
@@ -149,13 +124,11 @@
);
}
- protected void getValues(Object object, Object[] values) {
-
- CertificateList certlist = (CertificateList) object;
-
- values[0] = certlist.tbsCertList;
- values[1] = certlist.signatureAlgorithm;
- values[2] = new BitString(certlist.signatureValue, 0);
+ @Override protected void getValues(Object object, Object[] values) {
+ CertificateList certificateList = (CertificateList) object;
+ values[0] = certificateList.tbsCertList;
+ values[1] = certificateList.signatureAlgorithm;
+ values[2] = new BitString(certificateList.signatureValue, 0);
}
};
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/CertificatePolicies.java b/luni/src/main/java/org/apache/harmony/security/x509/CertificatePolicies.java
index 86ac9a1..90bc3a3 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/CertificatePolicies.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/CertificatePolicies.java
@@ -25,7 +25,6 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import org.apache.harmony.security.asn1.ASN1SequenceOf;
import org.apache.harmony.security.asn1.ASN1Type;
@@ -42,14 +41,11 @@
* <pre>
* certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
* </pre>
- *
*/
-
-public class CertificatePolicies extends ExtensionValue {
-
- // the values of policyInformation field of the structure
- private List policyInformations;
- // the ASN.1 encoded form of CertificatePolicies
+public final class CertificatePolicies extends ExtensionValue {
+ /** the values of policyInformation field of the structure */
+ private List<PolicyInformation> policyInformations;
+ /** the ASN.1 encoded form of CertificatePolicies */
private byte[] encoding;
/**
@@ -57,49 +53,28 @@
*/
public CertificatePolicies() {}
- /**
- * TODO
- * @param policyInformations: List
- */
- public CertificatePolicies(List policyInformations) {
- this.policyInformations = policyInformations;
- }
-
- public static CertificatePolicies decode(byte[] encoding)
- throws IOException {
+ public static CertificatePolicies decode(byte[] encoding) throws IOException {
CertificatePolicies cps = ((CertificatePolicies) ASN1.decode(encoding));
cps.encoding = encoding;
return cps;
}
- //
- // TODO
- // @param policyInformations: List
- // @param encoding: byte[]
- //
- private CertificatePolicies(List policyInformations, byte[] encoding) {
+ private CertificatePolicies(List<PolicyInformation> policyInformations, byte[] encoding) {
this.policyInformations = policyInformations;
this.encoding = encoding;
}
/**
* Returns the values of policyInformation field of the structure.
- * @return policyInformations
*/
- public List getPolicyInformations() {
- return new ArrayList(policyInformations);
+ public List<PolicyInformation> getPolicyInformations() {
+ return new ArrayList<PolicyInformation>(policyInformations);
}
- /**
- * TODO
- * @param policyInformation: PolicyInformation
- * @return
- */
- public CertificatePolicies addPolicyInformation(
- PolicyInformation policyInformation) {
+ public CertificatePolicies addPolicyInformation(PolicyInformation policyInformation) {
encoding = null;
if (policyInformations == null) {
- policyInformations = new ArrayList();
+ policyInformations = new ArrayList<PolicyInformation>();
}
policyInformations.add(policyInformation);
return this;
@@ -107,9 +82,8 @@
/**
* Returns ASN.1 encoded form of this X.509 CertificatePolicies value.
- * @return a byte array containing ASN.1 encode form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
@@ -120,12 +94,12 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("CertificatePolicies [\n");
- for (Iterator it=policyInformations.iterator(); it.hasNext();) {
+ for (PolicyInformation policyInformation : policyInformations) {
buffer.append(prefix);
buffer.append(" ");
- ((PolicyInformation) it.next()).dumpValue(buffer);
+ policyInformation.dumpValue(buffer);
buffer.append('\n');
}
buffer.append(prefix).append("]\n");
@@ -134,14 +108,12 @@
/**
* ASN.1 DER X.509 CertificatePolicies encoder/decoder class.
*/
- public static final ASN1Type ASN1 =
- new ASN1SequenceOf(PolicyInformation.ASN1) {
-
- public Object getDecodedObject(BerInputStream in) {
- return new CertificatePolicies((List) in.content, in.getEncoded());
+ public static final ASN1Type ASN1 = new ASN1SequenceOf(PolicyInformation.ASN1) {
+ @Override public Object getDecodedObject(BerInputStream in) {
+ return new CertificatePolicies((List<PolicyInformation>) in.content, in.getEncoded());
}
- public Collection getValues(Object object) {
+ @Override public Collection getValues(Object object) {
CertificatePolicies cps = (CertificatePolicies) object;
return cps.policyInformations;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/DNParser.java b/luni/src/main/java/org/apache/harmony/security/x509/DNParser.java
index 4f2ccd8..980ab05 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/DNParser.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/DNParser.java
@@ -42,45 +42,38 @@
* RFC 1779: A String Representation of Distinguished Names
* http://www.ietf.org/rfc/rfc1779.txt
*/
-public class DNParser {
+public final class DNParser {
+ private int pos;
+ private int beg;
+ private int end;
- // length of distinguished name string
- protected final int length;
+ /** distinguished name chars */
+ private final char[] chars;
- protected int pos, beg, end;
+ /** raw string contains '"' or '\' */
+ private boolean hasQE;
- // tmp vars to store positions of the currently parsed item
- protected int cur;
-
- // distinguished name chars
- protected char[] chars;
-
- // raw string contains '"' or '\'
- protected boolean hasQE;
-
- // DER encoding of currently parsed item
- protected byte[] encoded;
+ /** DER encoding of currently parsed item */
+ private byte[] encoded;
/**
- * Constructs DN parser
- *
* @param dn - distinguished name string to be parsed
*/
public DNParser(String dn) throws IOException {
- this.length = dn.length();
chars = dn.toCharArray();
}
- // gets next attribute type: (ALPHA 1*keychar) / oid
- protected String nextAT() throws IOException {
-
+ /**
+ * Returns the next attribute type: (ALPHA 1*keychar) / oid
+ */
+ private String nextAT() throws IOException {
hasQE = false; // reset
// skip preceding space chars, they can present after
// comma or semicolon (compatibility with RFC 1779)
- for (; pos < length && chars[pos] == ' '; pos++) {
+ for (; pos < chars.length && chars[pos] == ' '; pos++) {
}
- if (pos == length) {
+ if (pos == chars.length) {
return null; // reached the end of DN
}
@@ -89,11 +82,11 @@
// attribute type chars
pos++;
- for (; pos < length && chars[pos] != '=' && chars[pos] != ' '; pos++) {
+ for (; pos < chars.length && chars[pos] != '=' && chars[pos] != ' '; pos++) {
// we don't follow exact BNF syntax here:
// accept any char except space and '='
}
- if (pos >= length) {
+ if (pos >= chars.length) {
// unexpected end of DN
throw new IOException("Invalid distinguished name string");
}
@@ -104,10 +97,10 @@
// skip trailing space chars between attribute type and '='
// (compatibility with RFC 1779)
if (chars[pos] == ' ') {
- for (; pos < length && chars[pos] != '=' && chars[pos] == ' '; pos++) {
+ for (; pos < chars.length && chars[pos] != '=' && chars[pos] == ' '; pos++) {
}
- if (chars[pos] != '=' || pos == length) {
+ if (chars[pos] != '=' || pos == chars.length) {
// unexpected end of DN
throw new IOException("Invalid distinguished name string");
}
@@ -117,7 +110,7 @@
// skip space chars between '=' and attribute value
// (compatibility with RFC 1779)
- for (; pos < length && chars[pos] == ' '; pos++) {
+ for (; pos < chars.length && chars[pos] == ' '; pos++) {
}
// in case of oid attribute type skip its prefix: "oid." or "OID."
@@ -132,15 +125,15 @@
return new String(chars, beg, end - beg);
}
- // gets quoted attribute value: QUOTATION *( quotechar / pair ) QUOTATION
- protected String quotedAV() throws IOException {
-
+ /**
+ * Returns a quoted attribute value: QUOTATION *( quotechar / pair ) QUOTATION
+ */
+ private String quotedAV() throws IOException {
pos++;
beg = pos;
end = beg;
while (true) {
-
- if (pos == length) {
+ if (pos == chars.length) {
// unexpected end of DN
throw new IOException("Invalid distinguished name string");
}
@@ -161,16 +154,17 @@
// skip trailing space chars before comma or semicolon.
// (compatibility with RFC 1779)
- for (; pos < length && chars[pos] == ' '; pos++) {
+ for (; pos < chars.length && chars[pos] == ' '; pos++) {
}
return new String(chars, beg, end - beg);
}
- // gets hex string attribute value: "#" hexstring
+ /**
+ * Returns a hex string attribute value: "#" hexstring
+ */
private String hexAV() throws IOException {
-
- if (pos + 4 >= length) {
+ if (pos + 4 >= chars.length) {
// encoded byte array must be not less then 4 c
throw new IOException("Invalid distinguished name string");
}
@@ -178,10 +172,9 @@
beg = pos; // store '#' position
pos++;
while (true) {
-
// check for end of attribute value
// looks for space and component separators
- if (pos == length || chars[pos] == '+' || chars[pos] == ','
+ if (pos == chars.length || chars[pos] == '+' || chars[pos] == ','
|| chars[pos] == ';') {
end = pos;
break;
@@ -192,7 +185,7 @@
pos++;
// skip trailing space chars before comma or semicolon.
// (compatibility with RFC 1779)
- for (; pos < length && chars[pos] == ' '; pos++) {
+ for (; pos < chars.length && chars[pos] == ' '; pos++) {
}
break;
} else if (chars[pos] >= 'A' && chars[pos] <= 'F') {
@@ -218,14 +211,14 @@
return new String(chars, beg, hexLen);
}
- // gets string attribute value: *( stringchar / pair )
- protected String escapedAV() throws IOException {
-
+ /**
+ * Returns a string attribute value: *( stringchar / pair ).
+ */
+ private String escapedAV() throws IOException {
beg = pos;
end = pos;
while (true) {
-
- if (pos >= length) {
+ if (pos >= chars.length) {
// the end of DN has been found
return new String(chars, beg, end - beg);
}
@@ -244,15 +237,15 @@
case ' ':
// need to figure out whether space defines
// the end of attribute value or not
- cur = end;
+ int cur = end;
pos++;
chars[end++] = ' ';
- for (; pos < length && chars[pos] == ' '; pos++) {
+ for (; pos < chars.length && chars[pos] == ' '; pos++) {
chars[end++] = ' ';
}
- if (pos == length || chars[pos] == ',' || chars[pos] == '+'
+ if (pos == chars.length || chars[pos] == ',' || chars[pos] == '+'
|| chars[pos] == ';') {
// separator char or the end of DN has beed found
return new String(chars, beg, cur - beg);
@@ -265,11 +258,12 @@
}
}
- // returns escaped char
+ /**
+ * Returns an escaped char
+ */
private char getEscaped() throws IOException {
-
pos++;
- if (pos == length) {
+ if (pos == chars.length) {
throw new IOException("Invalid distinguished name string");
}
@@ -299,10 +293,10 @@
}
}
- // decodes UTF-8 char
- // see http://www.unicode.org for UTF-8 bit distribution table
+ /**
+ * Decodes a UTF-8 char.
+ */
protected char getUTF8() throws IOException {
-
int res = getByte(pos);
pos++; //FIXME tmp
@@ -325,7 +319,7 @@
int b;
for (int i = 0; i < count; i++) {
pos++;
- if (pos == length || chars[pos] != '\\') {
+ if (pos == chars.length || chars[pos] != '\\') {
return 0x3F; //FIXME failed to decode UTF-8 char - return '?'
}
pos++;
@@ -344,22 +338,21 @@
}
}
- // Returns byte representation of a char pair
- // The char pair is composed of DN char in
- // specified 'position' and the next char
- // According to BNF syntax:
- // hexchar = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
- // / "a" / "b" / "c" / "d" / "e" / "f"
- protected int getByte(int position) throws IOException {
-
- if ((position + 1) >= length) {
+ /**
+ * Returns byte representation of a char pair
+ * The char pair is composed of DN char in
+ * specified 'position' and the next char
+ * According to BNF syntax:
+ * hexchar = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
+ * / "a" / "b" / "c" / "d" / "e" / "f"
+ */
+ private int getByte(int position) throws IOException {
+ if ((position + 1) >= chars.length) {
// to avoid ArrayIndexOutOfBoundsException
throw new IOException("Invalid distinguished name string");
}
- int b1, b2;
-
- b1 = chars[position];
+ int b1 = chars[position];
if (b1 >= '0' && b1 <= '9') {
b1 = b1 - '0';
} else if (b1 >= 'a' && b1 <= 'f') {
@@ -370,7 +363,7 @@
throw new IOException("Invalid distinguished name string");
}
- b2 = chars[position + 1];
+ int b2 = chars[position + 1];
if (b2 >= '0' && b2 <= '9') {
b2 = b2 - '0';
} else if (b2 >= 'a' && b2 <= 'f') {
@@ -390,62 +383,49 @@
* @return a list of Relative Distinguished Names(RND),
* each RDN is represented as a list of AttributeTypeAndValue objects
*/
- public List parse() throws IOException {
+ public List<List<AttributeTypeAndValue>> parse() throws IOException {
+ List<List<AttributeTypeAndValue>> list = new ArrayList<List<AttributeTypeAndValue>>();
- List list = new ArrayList();
-
- String attValue;
String attType = nextAT();
if (attType == null) {
return list; //empty list of RDNs
}
- List atav = new ArrayList();
+ List<AttributeTypeAndValue> atav = new ArrayList<AttributeTypeAndValue>();
while (true) {
-
- if (pos == length) {
-
+ if (pos == chars.length) {
//empty Attribute Value
- atav.add(new AttributeTypeAndValue(attType, new AttributeValue(
- "", false)));
+ atav.add(new AttributeTypeAndValue(attType, new AttributeValue("", false)));
list.add(0, atav);
-
return list;
}
switch (chars[pos]) {
case '"':
- attValue = quotedAV();
- atav.add(new AttributeTypeAndValue(attType, new AttributeValue(
- attValue, hasQE)));
+ atav.add(new AttributeTypeAndValue(attType, new AttributeValue(quotedAV(), hasQE)));
break;
case '#':
- attValue = hexAV();
-
- atav.add(new AttributeTypeAndValue(attType, new AttributeValue(
- attValue, encoded)));
+ atav.add(new AttributeTypeAndValue(attType, new AttributeValue(hexAV(), encoded)));
break;
case '+':
case ',':
case ';': // compatibility with RFC 1779: semicolon can separate RDNs
//empty attribute value
- atav.add(new AttributeTypeAndValue(attType, new AttributeValue(
- "", false)));
+ atav.add(new AttributeTypeAndValue(attType, new AttributeValue("", false)));
break;
default:
- attValue = escapedAV();
atav.add(new AttributeTypeAndValue(attType, new AttributeValue(
- attValue, hasQE)));
+ escapedAV(), hasQE)));
}
- if (pos >= length) {
+ if (pos >= chars.length) {
list.add(0, atav);
return list;
}
if (chars[pos] == ',' || chars[pos] == ';') {
list.add(0, atav);
- atav = new ArrayList();
+ atav = new ArrayList<AttributeTypeAndValue>();
} else if (chars[pos] != '+') {
throw new IOException("Invalid distinguished name string");
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/DistributionPoint.java b/luni/src/main/java/org/apache/harmony/security/x509/DistributionPoint.java
index f631582..ce0644a 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/DistributionPoint.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/DistributionPoint.java
@@ -64,18 +64,11 @@
* }
* </pre>
*/
-public class DistributionPoint {
-
+public final class DistributionPoint {
private final DistributionPointName distributionPoint;
private final ReasonFlags reasons;
private final GeneralNames cRLIssuer;
- public DistributionPoint() {
- distributionPoint = null;
- reasons = null;
- cRLIssuer = null;
- }
-
public DistributionPoint(DistributionPointName distributionPoint,
ReasonFlags reasons, GeneralNames cRLIssuer) {
if ((reasons != null) && (distributionPoint == null) && (cRLIssuer == null)) {
@@ -124,13 +117,13 @@
setOptional(2);
}
- protected Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
Object[] values = (Object[]) in.content;
return new DistributionPoint((DistributionPointName) values[0],
(ReasonFlags) values[1], (GeneralNames) values[2]);
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
DistributionPoint dp = (DistributionPoint) object;
values[0] = dp.distributionPoint;
values[1] = dp.reasons;
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/DistributionPointName.java b/luni/src/main/java/org/apache/harmony/security/x509/DistributionPointName.java
index 79bee58..72cf674 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/DistributionPointName.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/DistributionPointName.java
@@ -66,12 +66,10 @@
* }
* </pre>
*/
-public class DistributionPointName {
-
+public final class DistributionPointName {
private final GeneralNames fullName;
private final Name nameRelativeToCRLIssuer;
-
public DistributionPointName(GeneralNames fullName) {
this.fullName = fullName;
this.nameRelativeToCRLIssuer = null;
@@ -110,7 +108,7 @@
return (dpn.fullName == null) ? 1 : 0;
}
- protected Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
DistributionPointName result = null;
if (in.choiceIndex == 0) {
result = new DistributionPointName((GeneralNames) in.content);
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/EDIPartyName.java b/luni/src/main/java/org/apache/harmony/security/x509/EDIPartyName.java
index c0197b4..d64e65b 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/EDIPartyName.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/EDIPartyName.java
@@ -51,56 +51,22 @@
* }
* </pre>
*/
-public class EDIPartyName {
- // the value of nameAssigner field of the structure
- private String nameAssigner;
- // the value of partyName field of the structure
- private String partyName;
- // the ASN.1 encoded form of EDIPartyName
+public final class EDIPartyName {
+ /** the value of nameAssigner field of the structure */
+ private final String nameAssigner;
+ /** the value of partyName field of the structure */
+ private final String partyName;
+ /** the ASN.1 encoded form of EDIPartyName */
private byte[] encoding;
- /**
- * TODO
- * @param nameAssigner: String
- * @param partyName: String
- */
- public EDIPartyName(String nameAssigner, String partyName) {
- this.nameAssigner = nameAssigner;
- this.partyName = partyName;
- }
-
- //
- // TODO
- // @param nameAssigner: String
- // @param partyName: String
- // @param encoding: byte[]
- //
- private EDIPartyName(String nameAssigner, String partyName,
- byte[] encoding) {
+ private EDIPartyName(String nameAssigner, String partyName, byte[] encoding) {
this.nameAssigner = nameAssigner;
this.partyName = partyName;
this.encoding = encoding;
}
/**
- * Returns the value of nameAssigner field of the structure.
- * @return nameAssigner
- */
- public String getNameAssigner() {
- return nameAssigner;
- }
-
- /**
- * Returns the value of partyName field of the structure.
- * @return partyName
- */
- public String getPartyName() {
- return partyName;
- }
-
- /**
* Returns ASN.1 encoded form of this X.509 EDIPartyName value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -121,13 +87,13 @@
setOptional(0);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new EDIPartyName((String) values[0], (String) values[1],
in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
EDIPartyName epn = (EDIPartyName) object;
values[0] = epn.nameAssigner;
values[1] = epn.partyName;
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/ExtendedKeyUsage.java b/luni/src/main/java/org/apache/harmony/security/x509/ExtendedKeyUsage.java
index fd9223a..e75716d 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/ExtendedKeyUsage.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/ExtendedKeyUsage.java
@@ -40,18 +40,10 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt
*/
-public class ExtendedKeyUsage extends ExtensionValue {
+public final class ExtendedKeyUsage extends ExtensionValue {
// the value of extension
- private List keys;
-
- /**
- * Creates an object on the base of list of integer arrays representing
- * key purpose IDs.
- */
- public ExtendedKeyUsage(List keys) {
- this.keys = keys;
- }
+ private List<String> keys;
/**
* Creates the extension object on the base of its encoded form.
@@ -64,28 +56,21 @@
* Returns the list of string representation of OIDs corresponding
* to key purpose IDs.
*/
- public List getExtendedKeyUsage() throws IOException {
+ public List<String> getExtendedKeyUsage() throws IOException {
if (keys == null) {
- keys = (List) ASN1.decode(getEncoded());
+ keys = (List<String>) ASN1.decode(getEncoded());
}
return keys;
}
- /**
- * Returns the encoded form of the object.
- */
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(keys);
}
return encoding;
}
- /**
- * Places the string representation of extension value
- * into the StringBuffer object.
- */
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Extended Key Usage: ");
if (keys == null) {
try {
@@ -97,7 +82,7 @@
}
}
buffer.append('[');
- for (Iterator it=keys.iterator(); it.hasNext();) {
+ for (Iterator<?> it = keys.iterator(); it.hasNext();) {
buffer.append(" \"").append(it.next()).append('"');
if (it.hasNext()) {
buffer.append(',');
@@ -109,14 +94,10 @@
/**
* ASN.1 Encoder/Decoder.
*/
- public static final ASN1Type ASN1 =
- new ASN1SequenceOf(new ASN1Oid() {
-
- public Object getDecodedObject(BerInputStream in)
- throws IOException {
- int[] oid = (int[]) super.getDecodedObject(in);
- return ObjectIdentifier.toString(oid);
- }
-
- });
+ public static final ASN1Type ASN1 = new ASN1SequenceOf(new ASN1Oid() {
+ public Object getDecodedObject(BerInputStream in) throws IOException {
+ int[] oid = (int[]) super.getDecodedObject(in);
+ return ObjectIdentifier.toString(oid);
+ }
+ });
}
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 f30c73f..1a7502e 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
@@ -49,8 +49,7 @@
* }
* </pre>
*/
-
-public class Extension {
+public final class Extension {
// critical constants
public static final boolean CRITICAL = true;
public static final boolean NON_CRITICAL = false;
@@ -102,12 +101,6 @@
// tells whether extension value has been decoded or not
private boolean valueDecoded = false;
- /**
- * TODO
- * @param extnID: String
- * @param critical: boolean
- * @param extnValue: byte[]
- */
public Extension(String extnID, boolean critical,
ExtensionValue extnValueObject) {
this.extnID_str = extnID;
@@ -118,12 +111,6 @@
this.extnValue = extnValueObject.getEncoded();
}
- /**
- * TODO
- * @param extnID: String
- * @param critical: boolean
- * @param extnValue: byte[]
- */
public Extension(String extnID, boolean critical, byte[] extnValue) {
this.extnID_str = extnID;
this.extnID = ObjectIdentifier.toIntArray(extnID);
@@ -131,43 +118,20 @@
this.extnValue = extnValue;
}
- /**
- * TODO
- * @param extnID: int[]
- * @param critical: boolean
- * @param extnValue: byte[]
- */
public Extension(int[] extnID, boolean critical, byte[] extnValue) {
this.extnID = extnID;
this.critical = critical;
this.extnValue = extnValue;
}
- /**
- * TODO
- * @param extnID: String
- * @param extnValue: byte[]
- */
public Extension(String extnID, byte[] extnValue) {
this(extnID, NON_CRITICAL, extnValue);
}
- /**
- * TODO
- * @param extnID: int[]
- * @param extnValue: byte[]
- */
public Extension(int[] extnID, byte[] extnValue) {
this(extnID, NON_CRITICAL, extnValue);
}
- //
- // TODO
- // @param extnID: int[]
- // @param critical: boolean
- // @param extnValue: byte[]
- // @param encoding: byte[]
- //
private Extension(int[] extnID, boolean critical, byte[] extnValue,
byte[] rawExtnValue, byte[] encoding,
ExtensionValue decodedExtValue) {
@@ -180,7 +144,6 @@
/**
* Returns the value of extnID field of the structure.
- * @return extnID
*/
public String getExtnID() {
if (extnID_str == null) {
@@ -191,7 +154,6 @@
/**
* Returns the value of critical field of the structure.
- * @return critical
*/
public boolean getCritical() {
return critical;
@@ -199,7 +161,6 @@
/**
* Returns the value of extnValue field of the structure.
- * @return extnValue
*/
public byte[] getExtnValue() {
return extnValue;
@@ -208,7 +169,6 @@
/**
* Returns the raw (undecoded octet string) value of extnValue
* field of the structure.
- * @return rawExtnValue
*/
public byte[] getRawExtnValue() {
if (rawExtnValue == null) {
@@ -219,7 +179,6 @@
/**
* Returns ASN.1 encoded form of this X.509 Extension value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -228,17 +187,17 @@
return encoding;
}
- public boolean equals(Object ext) {
+ @Override public boolean equals(Object ext) {
if (!(ext instanceof Extension)) {
return false;
}
- Extension extn = (Extension) ext;
- return Arrays.equals(extnID, extn.extnID)
- && (critical == extn.critical)
- && Arrays.equals(extnValue, extn.extnValue);
+ Extension extension = (Extension) ext;
+ return Arrays.equals(extnID, extension.extnID)
+ && (critical == extension.critical)
+ && Arrays.equals(extnValue, extension.extnValue);
}
- public int hashCode() {
+ @Override public int hashCode() {
return (extnID.hashCode() * 37 + (critical ? 1 : 0)) * 37 + extnValue.hashCode();
}
@@ -253,7 +212,8 @@
if (!valueDecoded) {
try {
decodeExtensionValue();
- } catch (IOException e) { }
+ } catch (IOException ignored) {
+ }
}
if (extnValueObject instanceof KeyUsage) {
return (KeyUsage) extnValueObject;
@@ -266,7 +226,8 @@
if (!valueDecoded) {
try {
decodeExtensionValue();
- } catch (IOException e) { }
+ } catch (IOException ignored) {
+ }
}
if (extnValueObject instanceof BasicConstraints) {
return (BasicConstraints) extnValueObject;
@@ -280,47 +241,47 @@
return;
}
valueDecoded = true;
- if (oidEquals(extnID, SUBJ_KEY_ID)) {
+ if (Arrays.equals(extnID, SUBJ_KEY_ID)) {
extnValueObject = SubjectKeyIdentifier.decode(extnValue);
- } else if (oidEquals(extnID, KEY_USAGE)) {
+ } else if (Arrays.equals(extnID, KEY_USAGE)) {
extnValueObject = new KeyUsage(extnValue);
- } else if (oidEquals(extnID, SUBJECT_ALT_NAME)) {
+ } else if (Arrays.equals(extnID, SUBJECT_ALT_NAME)) {
extnValueObject = new AlternativeName(
AlternativeName.SUBJECT, extnValue);
- } else if (oidEquals(extnID, ISSUER_ALTERNATIVE_NAME)) {
+ } else if (Arrays.equals(extnID, ISSUER_ALTERNATIVE_NAME)) {
extnValueObject = new AlternativeName(
AlternativeName.SUBJECT, extnValue);
- } else if (oidEquals(extnID, BASIC_CONSTRAINTS)) {
+ } else if (Arrays.equals(extnID, BASIC_CONSTRAINTS)) {
extnValueObject = new BasicConstraints(extnValue);
- } else if (oidEquals(extnID, NAME_CONSTRAINTS)) {
+ } else if (Arrays.equals(extnID, NAME_CONSTRAINTS)) {
extnValueObject = NameConstraints.decode(extnValue);
- } else if (oidEquals(extnID, CERTIFICATE_POLICIES)) {
+ } else if (Arrays.equals(extnID, CERTIFICATE_POLICIES)) {
extnValueObject = CertificatePolicies.decode(extnValue);
- } else if (oidEquals(extnID, AUTH_KEY_ID)) {
+ } else if (Arrays.equals(extnID, AUTH_KEY_ID)) {
extnValueObject = AuthorityKeyIdentifier.decode(extnValue);
- } else if (oidEquals(extnID, POLICY_CONSTRAINTS)) {
+ } else if (Arrays.equals(extnID, POLICY_CONSTRAINTS)) {
extnValueObject = new PolicyConstraints(extnValue);
- } else if (oidEquals(extnID, EXTENDED_KEY_USAGE)) {
+ } else if (Arrays.equals(extnID, EXTENDED_KEY_USAGE)) {
extnValueObject = new ExtendedKeyUsage(extnValue);
- } else if (oidEquals(extnID, INHIBIT_ANY_POLICY)) {
+ } else if (Arrays.equals(extnID, INHIBIT_ANY_POLICY)) {
extnValueObject = new InhibitAnyPolicy(extnValue);
- } else if (oidEquals(extnID, CERTIFICATE_ISSUER)) {
+ } else if (Arrays.equals(extnID, CERTIFICATE_ISSUER)) {
extnValueObject = new CertificateIssuer(extnValue);
- } else if (oidEquals(extnID, CRL_DISTR_POINTS)) {
+ } else if (Arrays.equals(extnID, CRL_DISTR_POINTS)) {
extnValueObject = CRLDistributionPoints.decode(extnValue);
- } else if (oidEquals(extnID, CERTIFICATE_ISSUER)) {
+ } else if (Arrays.equals(extnID, CERTIFICATE_ISSUER)) {
extnValueObject = new ReasonCode(extnValue);
- } else if (oidEquals(extnID, INVALIDITY_DATE)) {
+ } else if (Arrays.equals(extnID, INVALIDITY_DATE)) {
extnValueObject = new InvalidityDate(extnValue);
- } else if (oidEquals(extnID, REASON_CODE)) {
+ } else if (Arrays.equals(extnID, REASON_CODE)) {
extnValueObject = new ReasonCode(extnValue);
- } else if (oidEquals(extnID, CRL_NUMBER)) {
+ } else if (Arrays.equals(extnID, CRL_NUMBER)) {
extnValueObject = new CRLNumber(extnValue);
- } else if (oidEquals(extnID, ISSUING_DISTR_POINTS)) {
+ } else if (Arrays.equals(extnID, ISSUING_DISTR_POINTS)) {
extnValueObject = IssuingDistributionPoint.decode(extnValue);
- } else if (oidEquals(extnID, AUTHORITY_INFO_ACCESS)) {
+ } else if (Arrays.equals(extnID, AUTHORITY_INFO_ACCESS)) {
extnValueObject = InfoAccessSyntax.decode(extnValue);
- } else if (oidEquals(extnID, SUBJECT_INFO_ACCESS)) {
+ } else if (Arrays.equals(extnID, SUBJECT_INFO_ACCESS)) {
extnValueObject = InfoAccessSyntax.decode(extnValue);
}
}
@@ -334,7 +295,8 @@
if (!valueDecoded) {
try {
decodeExtensionValue();
- } catch (IOException e) { }
+ } catch (IOException ignored) {
+ }
}
if (extnValueObject != null) {
extnValueObject.dumpValue(buffer, prefix);
@@ -342,45 +304,45 @@
}
// else: dump unparsed hex representation
buffer.append(prefix);
- if (oidEquals(extnID, SUBJ_DIRECTORY_ATTRS)) {
+ if (Arrays.equals(extnID, SUBJ_DIRECTORY_ATTRS)) {
buffer.append("Subject Directory Attributes Extension");
- } else if (oidEquals(extnID, SUBJ_KEY_ID)) {
+ } else if (Arrays.equals(extnID, SUBJ_KEY_ID)) {
buffer.append("Subject Key Identifier Extension");
- } else if (oidEquals(extnID, KEY_USAGE)) {
+ } else if (Arrays.equals(extnID, KEY_USAGE)) {
buffer.append("Key Usage Extension");
- } else if (oidEquals(extnID, PRIVATE_KEY_USAGE_PERIOD)) {
+ } else if (Arrays.equals(extnID, PRIVATE_KEY_USAGE_PERIOD)) {
buffer.append("Private Key Usage Period Extension");
- } else if (oidEquals(extnID, SUBJECT_ALT_NAME)) {
+ } else if (Arrays.equals(extnID, SUBJECT_ALT_NAME)) {
buffer.append("Subject Alternative Name Extension");
- } else if (oidEquals(extnID, ISSUER_ALTERNATIVE_NAME)) {
+ } else if (Arrays.equals(extnID, ISSUER_ALTERNATIVE_NAME)) {
buffer.append("Issuer Alternative Name Extension");
- } else if (oidEquals(extnID, BASIC_CONSTRAINTS)) {
+ } else if (Arrays.equals(extnID, BASIC_CONSTRAINTS)) {
buffer.append("Basic Constraints Extension");
- } else if (oidEquals(extnID, NAME_CONSTRAINTS)) {
+ } else if (Arrays.equals(extnID, NAME_CONSTRAINTS)) {
buffer.append("Name Constraints Extension");
- } else if (oidEquals(extnID, CRL_DISTR_POINTS)) {
+ } else if (Arrays.equals(extnID, CRL_DISTR_POINTS)) {
buffer.append("CRL Distribution Points Extension");
- } else if (oidEquals(extnID, CERTIFICATE_POLICIES)) {
+ } else if (Arrays.equals(extnID, CERTIFICATE_POLICIES)) {
buffer.append("Certificate Policies Extension");
- } else if (oidEquals(extnID, POLICY_MAPPINGS)) {
+ } else if (Arrays.equals(extnID, POLICY_MAPPINGS)) {
buffer.append("Policy Mappings Extension");
- } else if (oidEquals(extnID, AUTH_KEY_ID)) {
+ } else if (Arrays.equals(extnID, AUTH_KEY_ID)) {
buffer.append("Authority Key Identifier Extension");
- } else if (oidEquals(extnID, POLICY_CONSTRAINTS)) {
+ } else if (Arrays.equals(extnID, POLICY_CONSTRAINTS)) {
buffer.append("Policy Constraints Extension");
- } else if (oidEquals(extnID, EXTENDED_KEY_USAGE)) {
+ } else if (Arrays.equals(extnID, EXTENDED_KEY_USAGE)) {
buffer.append("Extended Key Usage Extension");
- } else if (oidEquals(extnID, INHIBIT_ANY_POLICY)) {
+ } else if (Arrays.equals(extnID, INHIBIT_ANY_POLICY)) {
buffer.append("Inhibit Any-Policy Extension");
- } else if (oidEquals(extnID, AUTHORITY_INFO_ACCESS)) {
+ } else if (Arrays.equals(extnID, AUTHORITY_INFO_ACCESS)) {
buffer.append("Authority Information Access Extension");
- } else if (oidEquals(extnID, SUBJECT_INFO_ACCESS)) {
+ } else if (Arrays.equals(extnID, SUBJECT_INFO_ACCESS)) {
buffer.append("Subject Information Access Extension");
- } else if (oidEquals(extnID, INVALIDITY_DATE)) {
+ } else if (Arrays.equals(extnID, INVALIDITY_DATE)) {
buffer.append("Invalidity Date Extension");
- } else if (oidEquals(extnID, CRL_NUMBER)) {
+ } else if (Arrays.equals(extnID, CRL_NUMBER)) {
buffer.append("CRL Number Extension");
- } else if (oidEquals(extnID, REASON_CODE)) {
+ } else if (Arrays.equals(extnID, REASON_CODE)) {
buffer.append("Reason Code Extension");
} else {
buffer.append("Unknown Extension");
@@ -391,20 +353,6 @@
}
- // Compares two OIDs
- private static boolean oidEquals(int[] oid1, int[] oid2) {
- int length = oid1.length;
- if (length != oid2.length) {
- return false;
- }
- while (length > 0) {
- if (oid1[--length] != oid2[length]) {
- return false;
- }
- }
- return true;
- }
-
/**
* X.509 Extension encoder/decoder.
*/
@@ -412,8 +360,7 @@
ASN1Oid.getInstance(),
ASN1Boolean.getInstance(),
new ASN1OctetString() {
- public Object getDecodedObject(BerInputStream in)
- throws IOException {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
// first - decoded octet string,
// second - raw encoding of octet string
return new Object[]
@@ -425,7 +372,7 @@
setDefault(Boolean.FALSE, 1);
}
- protected Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
Object[] values = (Object[]) in.content;
int[] oid = (int[]) values[0];
@@ -434,22 +381,18 @@
ExtensionValue decodedExtValue = null;
// decode Key Usage and Basic Constraints extension values
- if (oidEquals(oid, KEY_USAGE)) {
+ if (Arrays.equals(oid, KEY_USAGE)) {
decodedExtValue = new KeyUsage(extnValue);
- } else if (oidEquals(oid, BASIC_CONSTRAINTS)) {
+ } else if (Arrays.equals(oid, BASIC_CONSTRAINTS)) {
decodedExtValue = new BasicConstraints(extnValue);
}
- return
- new Extension((int[]) values[0],
- ((Boolean) values[1]).booleanValue(),
+ return new Extension((int[]) values[0], (Boolean) values[1],
extnValue, rawExtnValue, in.getEncoded(), decodedExtValue);
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
Extension ext = (Extension) object;
-
values[0] = ext.extnID;
values[1] = (ext.critical) ? Boolean.TRUE : Boolean.FALSE;
values[2] = ext.extnValue;
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/ExtensionValue.java b/luni/src/main/java/org/apache/harmony/security/x509/ExtensionValue.java
index 87f72eb..a9abf32 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/ExtensionValue.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/ExtensionValue.java
@@ -24,26 +24,18 @@
*/
public class ExtensionValue {
- /**
- * Encoded form of the extension.
- */
+ /** Encoded form of the extension. */
protected byte[] encoding;
- /**
- * Default constructor.
- */
- public ExtensionValue() { }
+ /** Default constructor. */
+ public ExtensionValue() {}
- /**
- * Creates the object on the base of its encoded form.
- */
+ /** Creates the object on the base of its encoded form. */
public ExtensionValue(byte[] encoding) {
this.encoding = encoding;
}
- /**
- * Returns encoded form of the object.
- */
+ /** Returns encoded form of the object. */
public byte[] getEncoded() {
return encoding;
}
@@ -70,6 +62,6 @@
*/
public void dumpValue(StringBuffer buffer) {
dumpValue(buffer, "");
- };
+ }
}
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 9bff5f2..10c40f9 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
@@ -28,7 +28,6 @@
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
@@ -48,8 +47,7 @@
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
* </pre>
*/
-
-public class Extensions {
+public final class Extensions {
// Supported critical extensions oids:
private static List SUPPORTED_CRITICAL = Arrays.asList(
@@ -58,14 +56,14 @@
// the values of extensions of the structure
private List<Extension> extensions;
- private Set critical;
- private Set noncritical;
+ private Set<String> critical;
+ private Set<String> noncritical;
// the flag showing is there any unsupported critical extension
// in the list of extensions or not.
private boolean hasUnsupported;
// map containing the oid of extensions as a keys and
// Extension objects as values
- private HashMap oidMap;
+ private HashMap<String, Extension> oidMap;
// the ASN.1 encoded form of Extensions
private byte[] encoding;
@@ -74,11 +72,7 @@
*/
public Extensions() {}
- /**
- * TODO
- * @param extensions: List
- */
- public Extensions(List extensions) {
+ public Extensions(List<Extension> extensions) {
this.extensions = extensions;
}
@@ -88,9 +82,8 @@
/**
* Returns the list of critical extensions.
- * @return extensions
*/
- public Set getCriticalExtensions() {
+ public Set<String> getCriticalExtensions() {
if (critical == null) {
makeOidsLists();
}
@@ -99,9 +92,8 @@
/**
* Returns the list of critical extensions.
- * @return extensions
*/
- public Set getNonCriticalExtensions() {
+ public Set<String> getNonCriticalExtensions() {
if (noncritical == null) {
makeOidsLists();
}
@@ -124,12 +116,11 @@
return;
}
int size = extensions.size();
- critical = new HashSet(size);
- noncritical = new HashSet(size);
- for (int i=0; i<size; i++) {
- Extension extn = extensions.get(i);
- String oid = extn.getExtnID();
- if (extn.getCritical()) {
+ critical = new HashSet<String>(size);
+ noncritical = new HashSet<String>(size);
+ for (Extension extension : extensions) {
+ String oid = extension.getExtnID();
+ if (extension.getCritical()) {
if (!SUPPORTED_CRITICAL.contains(oid)) {
hasUnsupported = true;
}
@@ -142,22 +133,18 @@
/**
* Returns the values of extensions.
- * @param oid - the OID of needed extension.
- * @return extensions
*/
public Extension getExtensionByOID(String oid) {
if (extensions == null) {
return null;
}
if (oidMap == null) {
- oidMap = new HashMap();
- Iterator it = extensions.iterator();
- while (it.hasNext()) {
- Extension extn = (Extension) it.next();
- oidMap.put(extn.getExtnID(), extn);
+ oidMap = new HashMap<String, Extension>();
+ for (Extension extension : extensions) {
+ oidMap.put(extension.getExtnID(), extension);
}
}
- return (Extension) oidMap.get(oid);
+ return oidMap.get(oid);
}
@@ -188,9 +175,9 @@
* than 9.
*/
public boolean[] valueOfKeyUsage() {
- Extension extn = getExtensionByOID("2.5.29.15");
- KeyUsage kUsage = null;
- if ((extn == null) || ((kUsage = extn.getKeyUsageValue()) == null)) {
+ Extension extension = getExtensionByOID("2.5.29.15");
+ KeyUsage kUsage;
+ if ((extension == null) || ((kUsage = extension.getKeyUsageValue()) == null)) {
return null;
}
return kUsage.getKeyUsage();
@@ -213,13 +200,12 @@
* and null
* @throws IOException if extension was incorrectly encoded.
*/
- public List valueOfExtendedKeyUsage() throws IOException {
- Extension extn = getExtensionByOID("2.5.29.37");
- if (extn == null) {
+ public List<String> valueOfExtendedKeyUsage() throws IOException {
+ Extension extension = getExtensionByOID("2.5.29.37");
+ if (extension == null) {
return null;
}
- return ((ExtendedKeyUsage)
- extn.getDecodedExtensionValue()).getExtendedKeyUsage();
+ return ((ExtendedKeyUsage) extension.getDecodedExtensionValue()).getExtendedKeyUsage();
}
/**
@@ -240,10 +226,9 @@
* and Integer.MAX_VALUE if does not.
*/
public int valueOfBasicConstrains() {
- Extension extn = getExtensionByOID("2.5.29.19");
- BasicConstraints bc = null;
- if ((extn == null)
- || ((bc = extn.getBasicConstraintsValue()) == null)) {
+ Extension extension = getExtensionByOID("2.5.29.19");
+ BasicConstraints bc;
+ if ((extension == null) || ((bc = extension.getBasicConstraintsValue()) == null)) {
return Integer.MAX_VALUE;
}
return bc.getPathLenConstraint();
@@ -264,13 +249,12 @@
* (Integer (tag), Object (name value)) if extension presents, and
* null if does not.
*/
- public List valueOfSubjectAlternativeName() throws IOException {
- Extension extn = getExtensionByOID("2.5.29.17");
- if (extn == null) {
+ public Collection<List<?>> valueOfSubjectAlternativeName() throws IOException {
+ Extension extension = getExtensionByOID("2.5.29.17");
+ if (extension == null) {
return null;
}
- return ((GeneralNames) GeneralNames.ASN1.decode(extn.getExtnValue()))
- .getPairsList();
+ return ((GeneralNames) GeneralNames.ASN1.decode(extension.getExtnValue())).getPairsList();
}
/**
@@ -288,13 +272,12 @@
* (Integer (tag), Object (name value)) if extension presents, and
* null if does not.
*/
- public List valueOfIssuerAlternativeName() throws IOException {
- Extension extn = getExtensionByOID("2.5.29.18");
- if (extn == null) {
+ public Collection<List<?>> valueOfIssuerAlternativeName() throws IOException {
+ Extension extension = getExtensionByOID("2.5.29.18");
+ if (extension == null) {
return null;
}
- return ((GeneralNames)
- GeneralNames.ASN1.decode(extn.getExtnValue())).getPairsList();
+ return ((GeneralNames) GeneralNames.ASN1.decode(extension.getExtnValue())).getPairsList();
}
/**
@@ -310,46 +293,16 @@
*
* @return the value of Certificate Issuer Extension
*/
- public X500Principal valueOfCertificateIssuerExtension()
- throws IOException {
- Extension extn = getExtensionByOID("2.5.29.29");
- if (extn == null) {
+ public X500Principal valueOfCertificateIssuerExtension() throws IOException {
+ Extension extension = getExtensionByOID("2.5.29.29");
+ if (extension == null) {
return null;
}
- return ((CertificateIssuer)
- extn.getDecodedExtensionValue()).getIssuer();
- }
-
- /**
- * TODO
- * @param extn: Extension
- * @return
- */
- public void addExtension(Extension extn) {
- encoding = null;
- if (extensions == null) {
- extensions = new ArrayList();
- }
- extensions.add(extn);
- if (oidMap != null) {
- oidMap.put(extn.getExtnID(), extn);
- }
- if (critical != null) {
- String oid = extn.getExtnID();
- if (extn.getCritical()) {
- if (!SUPPORTED_CRITICAL.contains(oid)) {
- hasUnsupported = true;
- }
- critical.add(oid);
- } else {
- noncritical.add(oid);
- }
- }
+ return ((CertificateIssuer) extension.getDecodedExtensionValue()).getIssuer();
}
/**
* Returns ASN.1 encoded form of this X.509 Extensions value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -358,28 +311,22 @@
return encoding;
}
- public boolean equals(Object exts) {
- if (!(exts instanceof Extensions)) {
+ @Override public boolean equals(Object other) {
+ if (!(other instanceof Extensions)) {
return false;
}
- Extensions extns = (Extensions) exts;
- return ((extensions == null) || (extensions.size() == 0)
- ? ((extns.extensions == null)
- || (extns.extensions.size() == 0))
- : ((extns.extensions == null)
- || (extns.extensions.size() == 0))
- ? false
- : (extensions.containsAll(extns.extensions)
- && (extensions.size() == extns.extensions.size()))
- );
+ Extensions that = (Extensions) other;
+ return (this.extensions == null || this.extensions.isEmpty())
+ ? (that.extensions == null || that.extensions.isEmpty())
+ : (this.extensions.equals(that.extensions));
}
- public int hashCode() {
- int hashcode = 0;
+ @Override public int hashCode() {
+ int hashCode = 0;
if (extensions != null) {
- hashcode = extensions.hashCode();
+ hashCode = extensions.hashCode();
}
- return hashcode;
+ return hashCode;
}
/**
@@ -401,14 +348,13 @@
* Custom X.509 Extensions decoder.
*/
public static final ASN1Type ASN1 = new ASN1SequenceOf(Extension.ASN1) {
-
- public Object getDecodedObject(BerInputStream in) {
- return new Extensions((List)in.content);
+ @Override public Object getDecodedObject(BerInputStream in) {
+ return new Extensions((List<Extension>) in.content);
}
- public Collection getValues(Object object) {
- Extensions exts = (Extensions) object;
- return (exts.extensions == null) ? new ArrayList() : exts.extensions;
+ @Override public Collection getValues(Object object) {
+ Extensions extensions = (Extensions) object;
+ return (extensions.extensions == null) ? new ArrayList() : extensions.extensions;
}
};
}
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 d52fe89..94bb7ad 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
@@ -23,13 +23,15 @@
package org.apache.harmony.security.x509;
import java.io.IOException;
+import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
-import java.nio.charset.Charsets;
+import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import javax.security.auth.x500.X500Principal;
import org.apache.harmony.security.asn1.ASN1Choice;
import org.apache.harmony.security.asn1.ASN1Implicit;
@@ -39,6 +41,7 @@
import org.apache.harmony.security.asn1.ASN1Type;
import org.apache.harmony.security.asn1.BerInputStream;
import org.apache.harmony.security.asn1.ObjectIdentifier;
+import org.apache.harmony.security.utils.Array;
import org.apache.harmony.security.x501.Name;
/**
@@ -83,10 +86,14 @@
*
* </pre>
*
+ * <p>This class doesn't support masked addresses like "10.9.8.0/255.255.255.0".
+ * These are only necessary for NameConstraints, which are not exposed in the
+ * Java certificate API.
+ *
* @see org.apache.harmony.security.x509.NameConstraints
* @see org.apache.harmony.security.x509.GeneralSubtree
*/
-public class GeneralName {
+public final class GeneralName {
/**
* The values of the tags of fields
@@ -116,13 +123,13 @@
nameASN1[REG_ID] = ASN1Oid.getInstance();
}
- // the tag of the name type
+ /** the tag of the name type */
private int tag;
- // the name value (can be String or byte array)
+ /** the name value (can be String or byte array) */
private Object name;
- // the ASN.1 encoded form of GeneralName
+ /** the ASN.1 encoded form of GeneralName */
private byte[] encoding;
- // the ASN.1 encoded form of GeneralName's field
+ /** the ASN.1 encoded form of GeneralName's field */
private byte[] name_encoding;
/**
@@ -141,7 +148,6 @@
* To make the GeneralName object with such names use another constructor.
* @param tag is an integer which value corresponds to the name type.
* @param name is a name value corresponding to the tag.
- * <pre>
*/
public GeneralName(int tag, String name) throws IOException {
if (name == null) {
@@ -183,37 +189,21 @@
}
}
- /**
- * TODO
- * @param name: OtherName
- */
public GeneralName(OtherName name) {
this.tag = OTHER_NAME;
this.name = name;
}
- /**
- * TODO
- * @param name: ORAddress
- */
public GeneralName(ORAddress name) {
this.tag = X400_ADDR;
this.name = name;
}
- /**
- * TODO
- * @param name: Name
- */
public GeneralName(Name name) {
this.tag = DIR_NAME;
this.name = name;
}
- /**
- * TODO
- * @param name: EDIPartyName
- */
public GeneralName(EDIPartyName name) {
this.tag = EDIP_NAME;
this.name = name;
@@ -259,7 +249,6 @@
/**
* Returns the tag of the name in the structure
- * @return the tag of the name
*/
public int getTag() {
return tag;
@@ -288,16 +277,11 @@
return name;
}
- /**
- * TODO
- * @param _gname: Object
- * @return
- */
- public boolean equals(Object _gname) {
- if (!(_gname instanceof GeneralName)) {
+ public boolean equals(Object other) {
+ if (!(other instanceof GeneralName)) {
return false;
}
- GeneralName gname = (GeneralName) _gname;
+ GeneralName gname = (GeneralName) other;
if (this.tag != gname.tag) {
return false;
}
@@ -320,7 +304,6 @@
default:
// should never happen
}
- //System.out.println(false);
return false;
}
@@ -365,8 +348,8 @@
// Mail address [1]:
// a@b.c - particular address is acceptable by the same address,
// or by b.c - host name.
- return ((String) gname.getName()).toLowerCase()
- .endsWith(((String) name).toLowerCase());
+ return ((String) gname.getName()).toLowerCase(Locale.US)
+ .endsWith(((String) name).toLowerCase(Locale.US));
case DNS_NAME:
// DNS name [2] that can be constructed by simply adding
// to the left hand side of the name satisfies the name
@@ -376,7 +359,7 @@
if (dns.equalsIgnoreCase(_dns)) {
return true;
} else {
- return _dns.toLowerCase().endsWith("." + dns.toLowerCase());
+ return _dns.toLowerCase(Locale.US).endsWith("." + dns.toLowerCase(Locale.US));
}
case UR_ID:
// For URIs the constraint ".xyz.com" is satisfied by both
@@ -398,7 +381,7 @@
? uri.substring(begin)
: uri.substring(begin, end);
if (host.startsWith(".")) {
- return _host.toLowerCase().endsWith(host.toLowerCase());
+ return _host.toLowerCase(Locale.US).endsWith(host.toLowerCase(Locale.US));
} else {
return host.equalsIgnoreCase(_host);
}
@@ -411,9 +394,12 @@
if (length == _length) {
return Arrays.equals(address, _address);
} else if (length == 2*_length) {
- for (int i=0; i<_address.length; i++) {
- if ((_address[i] < address[i])
- || (_address[i] > address[i+_length])) {
+ for (int i = 0; i < _address.length; i++) {
+ // TODO: should the 2nd IP address be treated as a range or as a mask?
+ int octet = _address[i] & 0xff;
+ int min = address[i] & 0xff;
+ int max = address[i + _length] & 0xff;
+ if ((octet < min) || (octet > max)) {
return false;
}
}
@@ -457,9 +443,9 @@
* otherName, X400Address, ediPartyName returned as byte arrays
* containing the ASN.1 DER encoded form of the name.
*/
- public List getAsList() {
- ArrayList result = new ArrayList();
- result.add(Integer.valueOf(tag)); // android-changed
+ public List<Object> getAsList() {
+ ArrayList<Object> result = new ArrayList<Object>();
+ result.add(tag);
switch (tag) {
case OTHER_NAME:
result.add(((OtherName) name).getEncoded());
@@ -490,33 +476,12 @@
return Collections.unmodifiableList(result);
}
- //
- // TODO
- // @param data: byte[]
- // @return
- //
- private String getBytesAsString(byte[] data) {
- String result = "";
- for (int i=0; i<data.length; i++) {
- String tail = Integer.toHexString(0x00ff & data[i]);
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- result += tail + " ";
- }
- return result;
- }
-
- /**
- * TODO
- * @return
- */
public String toString() {
String result = "";
switch (tag) {
case OTHER_NAME:
result = "otherName[0]: "
- + getBytesAsString(getEncoded());
+ + Array.getBytesAsString(getEncoded());
break;
case RFC822_NAME:
result = "rfc822Name[1]: " + name;
@@ -532,7 +497,7 @@
break;
case X400_ADDR:
result = "x400Address[3]: "
- + getBytesAsString(getEncoded());
+ + Array.getBytesAsString(getEncoded());
break;
case DIR_NAME:
result = "directoryName[4]: "
@@ -540,7 +505,7 @@
break;
case EDIP_NAME:
result = "ediPartyName[5]: "
- + getBytesAsString(getEncoded());
+ + Array.getBytesAsString(getEncoded());
break;
case IP_ADDR:
result = "iPAddress[7]: " + ipBytesToStr((byte[]) name);
@@ -553,7 +518,6 @@
/**
* Returns ASN.1 encoded form of this X.509 GeneralName value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -580,13 +544,14 @@
* by RFC 1123 (section 2.1).
*/
public static void checkDNS(String dns) throws IOException {
- byte[] bytes = dns.toLowerCase().getBytes(Charsets.UTF_8);
+ String string = dns.toLowerCase(Locale.US);
+ int length = string.length();
// indicates if it is a first letter of the label
boolean first_letter = true;
- for (int i=0; i<bytes.length; i++) {
- byte ch = bytes[i];
+ for (int i = 0; i < length; i++) {
+ char ch = string.charAt(i);
if (first_letter) {
- if ((bytes.length > 2) && (ch == '*') && (bytes[1] == '.')) {
+ if ((length > 2) && (ch == '*') && (string.charAt(1) == '.')) {
first_letter = false;
continue;
}
@@ -603,7 +568,7 @@
if (ch == '.') {
// check the end of the previous label, it should not
// be '-' sign
- if (bytes[i-1] == '-') {
+ if (string.charAt(i-1) == '-') {
throw new IOException("Incorrect DNS name: label ends with '-': " + dns);
}
first_letter = true;
@@ -631,231 +596,64 @@
}
/**
- * Converts OID into array of bytes.
+ * Converts OID into array of ints.
*/
public static int[] oidStrToInts(String oid) throws IOException {
- byte[] bytes = oid.getBytes(Charsets.UTF_8);
- if (bytes[bytes.length-1] == '.') {
+ int length = oid.length();
+ if (oid.charAt(length-1) == '.') {
throw new IOException("Bad OID: " + oid);
}
- int[] result = new int[bytes.length/2+1]; // best case: a.b.c.d.e
+ int[] result = new int[length/2+1]; // best case: a.b.c.d.e
int number = 0; // the number of OID's components
- for (int i=0; i<bytes.length; i++) {
+ for (int i = 0; i < length; i++) {
int value = 0;
int pos = i;
- while ((i < bytes.length) && (bytes[i] >= '0')
- && (bytes[i] <= '9')) {
- value = 10 * value + (bytes[i++] - 48);
+ for (; i < length; i++) {
+ char ch = oid.charAt(i);
+ if ((ch < '0') || (ch > '9')) {
+ break;
+ }
+ value = 10 * value + (ch - '0');
}
if (i == pos) {
// the number was not read
throw new IOException("Bad OID: " + oid);
}
result[number++] = value;
- if (i >= bytes.length) {
+ if (i == length) {
break;
}
- if (bytes[i] != '.') {
+ char ch = oid.charAt(i);
+ if (ch != '.') {
throw new IOException("Bad OID: " + oid);
}
}
if (number < 2) {
throw new IOException("OID should consist of no less than 2 components: " + oid);
}
- int[] res = new int[number];
- for (int i=0; i<number; i++) {
- res[i] = result[i];
- }
- return res;
+ return Arrays.copyOfRange(result, 0, number);
}
/**
- * Helper method. Converts the String representation of IP address
- * to the array of bytes. IP addresses are expected in two versions:<br>
- * IPv4 - in dot-decimal notation<br>
- * IPv6 - in colon hexadecimal notation<br>
- * Also method works with the ranges of the addresses represented
- * as 2 addresses separated by '/' character.
- * @param address : String representation of IP address
- * @return byte representation of IP address
+ * Returns the bytes of the given IP address or masked IP address.
*/
public static byte[] ipStrToBytes(String ip) throws IOException {
- boolean isIPv4 = (ip.indexOf('.') > 0);
- // number of components (should be 4 or 8)
- int num_components = (isIPv4) ? 4 : 16;
- if (ip.indexOf('/') > 0) {
- num_components *= 2; // this is a range of addresses
+ if (!InetAddress.isNumeric(ip)) {
+ throw new IOException("Not an IP address: " + ip);
}
- // the resulting array
- byte[] result = new byte[num_components];
- byte[] ip_bytes = ip.getBytes(Charsets.UTF_8);
- // number of address component to be read
- int component = 0;
- // if it is reading the second bound of a range
- boolean reading_second_bound = false;
- if (isIPv4) {
- // IPv4 address is expected in the form of dot-decimal notation:
- // 1.100.2.200
- // or in the range form:
- // 1.100.2.200/1.100.3.300
- int i = 0;
- while (i < ip_bytes.length) {
- int digits = 0;
- // the value of the address component
- int value = 0;
- while ((i < ip_bytes.length) && (ip_bytes[i] >= '0') && (ip_bytes[i] <= '9')) {
- digits++;
- if (digits > 3) {
- throw new IOException("Component of IPv4 address should consist of no more than 3 decimal digits: " + ip);
- }
- value = 10 * value + (ip_bytes[i] - 48);
- i++;
- }
- if (digits == 0) {
- // ip_bytes[i] is not a number
- throw badIp(4, ip);
- }
- result[component] = (byte) value;
- component++;
- if (i >= ip_bytes.length) {
- // no more bytes
- break;
- }
- // check the reached delimiter
- if ((ip_bytes[i] != '.' && ip_bytes[i] != '/')) {
- throw badIp(4, ip);
- }
- // check the correctness of the range
- if (ip_bytes[i] == '/') {
- if (reading_second_bound) {
- // more than 2 bounds in the range
- throw badIp(4, ip);
- }
- if (component != 4) {
- throw new IOException("IPv4 address should consist of 4 decimal numbers: " + ip);
- }
- reading_second_bound = true;
- }
- // check the number of the components
- if (component > ((reading_second_bound) ? 7 : 3)) {
- throw new IOException("IPv4 address should consist of 4 decimal numbers: " + ip);
- }
- i++;
- }
- // check the number of read components
- if (component != num_components) {
- throw new IOException("IPv4 address should consist of 4 decimal numbers: " + ip);
- }
- } else {
- // IPv6 address is expected in the form of
- // colon hexadecimal notation:
- // 010a:020b:3337:1000:FFFA:ABCD:9999:0000
- // or in a range form:
- // 010a:020b:3337:1000:FFFA:ABCD:9999:0000/010a:020b:3337:1000:FFFA:ABCD:9999:1111
- if (ip_bytes.length != 39 && ip_bytes.length != 79) {
- // incorrect length of the string representation
- throw badIp(6, ip);
- }
- int value = 0;
- // indicates the reading of the second half of byte
- boolean second_hex = false;
- // if the delimiter (':' or '/') is expected
- boolean expect_delimiter = false;
- for (int i=0; i<ip_bytes.length; i++) {
- byte bytik = ip_bytes[i];
- if ((bytik >= '0') && (bytik <= '9')) {
- value = (bytik - 48); // '0':0, '1':1, ... , '9':9
- } else if ((bytik >= 'A') && (bytik <= 'F')) {
- value = (bytik - 55); // 'A':10, 'B':11, ... , 'F':15
- } else if ((bytik >= 'a') && (bytik <= 'f')) {
- value = (bytik - 87); // 'a':10, 'b':11, ... , 'f':15
- } else if (second_hex) {
- // second hex value of a byte is expected but was not read
- // (it is the situation like: ...ABCD:A:ABCD...)
- throw badIp(6, ip);
- } else if ((bytik == ':') || (bytik == '/')) {
- if (component % 2 == 1) {
- // second byte of the component is omitted
- // (it is the situation like: ... ABDC:AB:ABCD ...)
- throw badIp(6, ip);
- }
- if (bytik == '/') {
- if (reading_second_bound) {
- // more than 2 bounds in the range
- throw badIp(6, ip);
- }
- if (component != 16) {
- // check the number of read components
- throw new IOException("IPv6 address should consist of 8 hexadecimal numbers: " + ip);
- }
- reading_second_bound = true;
- }
- expect_delimiter = false;
- continue;
- } else {
- throw badIp(6, ip);
- }
- if (expect_delimiter) { // delimiter is expected but was not read
- throw badIp(6, ip);
- }
- if (!second_hex) {
- // first half of byte has been read
- result[component] = (byte) (value << 4);
- second_hex = true;
- } else {
- // second half of byte has been read
- result[component] = (byte)
- ((result[component] & 0xFF) | value);
- // delimiter is expected if 2 bytes were read
- expect_delimiter = (component % 2 == 1);
- second_hex = false;
- component++;
- }
- }
- // check the correctness of the read address:
- if (second_hex || (component % 2 == 1)) {
- throw badIp(6, ip);
- }
- }
- return result;
- }
-
- private static IOException badIp(int v, String ip) throws IOException {
- throw new IOException("Incorrect IPv" + v + " representation: " + ip);
+ return InetAddress.getByName(ip).getAddress();
}
/**
- * Helper method. Converts the byte array representation of ip address
- * to the String.
- * @param ip : byte array representation of ip address
- * If the length of byte array 4 then it represents an IP v4
- * and the output String will be in the dotted quad form.
- * If the length is 16 then it represents an IP v6
- * and the output String will be returned in format "p1:p2:...:p8",
- * where p1-p8 are hexadecimal values representing the eight 16-bit
- * pieces of the address.
- * If the length is 8 or 32 then it represents an address range (RFC 1519)
- * and the output String will contain 2 IP address divided by "/"
- * @return String representation of ip address
+ * Returns the string form of the given IP address. Addresses of length 2x
+ * the canonical length are treated as a route/mask pair.
*/
public static String ipBytesToStr(byte[] ip) {
- String result = "";
- if (ip.length < 9) { // IP v4
- for (int i=0; i<ip.length; i++) {
- result += Integer.toString(ip[i] & 0xff);
- if (i != ip.length-1) {
- result += (i == 3) ? "/": ".";
- }
- }
- } else {
- for (int i=0; i<ip.length; i++) {
- result += Integer.toHexString(0x00ff & ip[i]);
- if ((i % 2 != 0) && (i != ip.length-1)) {
- result += (i == 15) ? "/": ":";
- }
- }
+ try {
+ return InetAddress.getByAddress(null, ip).getHostAddress();
+ } catch (UnknownHostException e) {
+ throw new IllegalArgumentException("Unexpected IP address: " + Arrays.toString(ip));
}
- return result;
}
public static final ASN1Choice ASN1 = new ASN1Choice(new ASN1Type[] {
@@ -877,7 +675,7 @@
return ((GeneralName) object).tag;
}
- public Object getDecodedObject(BerInputStream in) throws IOException {
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
GeneralName result;
switch (in.choiceIndex) {
case OTHER_NAME: // OtherName
@@ -917,44 +715,4 @@
return result;
}
};
-
- // public static void printAsHex(int perLine,
- // String prefix,
- // String delimiter,
- // byte[] data) {
- // for (int i=0; i<data.length; i++) {
- // String tail = Integer.toHexString(0x000000ff & data[i]);
- // if (tail.length() == 1) {
- // tail = "0" + tail;
- // }
- // System.out.print(prefix + "0x" + tail + delimiter);
-
- // if (((i+1)%perLine) == 0) {
- // System.out.println();
- // }
- // }
- // System.out.println();
- // }
-
- // public static void main(String[] args) {
- // System.out.println(">> "+new BigInteger(new byte[] {(byte)23, (byte)255}).toString(2));
- // System.out.println(ipBytesToStr(new byte[] {(byte)255, (byte)23, (byte)128, (byte)130}));
- // System.out.println(ipBytesToStr(new byte[] {(byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130}));
- // System.out.println(ipBytesToStr(new byte[] {(byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130}));
- // System.out.println(ipBytesToStr(new byte[] {(byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130,
- // (byte)255, (byte)23, (byte)128, (byte)130}));
- // ipStrToBytes("1.2.3.4");
- // ipStrToBytes("1.2.3.4/4.3.2.1");
- // printAsHex(8, "", " ", ipStrToBytes("ff17:8082:ff17:8082:ff17:8082:ff17:8082/ff17:8082:ff17:8082:ff17:8082:ff17:8082"));
- // }
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/GeneralNames.java b/luni/src/main/java/org/apache/harmony/security/x509/GeneralNames.java
index adec066..957380b 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/GeneralNames.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/GeneralNames.java
@@ -24,7 +24,6 @@
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import org.apache.harmony.security.asn1.ASN1SequenceOf;
import org.apache.harmony.security.asn1.ASN1Type;
@@ -47,99 +46,59 @@
* @see org.apache.harmony.security.x509.NameConstraints
* @see org.apache.harmony.security.x509.GeneralSubtree
*/
-public class GeneralNames {
-
- // the values of GeneralName
- private List generalNames;
- // the ASN.1 encoded form of GeneralNames
+public final class GeneralNames {
+ /** the values of GeneralName */
+ private List<GeneralName> generalNames;
+ /** the ASN.1 encoded form of GeneralNames */
private byte[] encoding;
- /**
- * Constructs an object representing the value of GeneralNames.
- */
public GeneralNames() {
- generalNames = new ArrayList();
+ generalNames = new ArrayList<GeneralName>();
}
- /**
- * TODO
- * @param generalNames: List
- */
- public GeneralNames(List generalNames) {
+ public GeneralNames(List<GeneralName> generalNames) {
this.generalNames = generalNames;
}
- //
- // TODO
- // @param generalNames: List
- // @param encoding: byte[]
- //
- private GeneralNames(List generalNames, byte[] encoding) {
+ private GeneralNames(List<GeneralName> generalNames, byte[] encoding) {
this.generalNames = generalNames;
this.encoding = encoding;
}
/**
* Returns the list of values.
- * @return names
*/
- public List getNames() {
+ public List<GeneralName> getNames() {
if ((generalNames == null) || (generalNames.size() == 0)) {
return null;
}
- return new ArrayList(generalNames);
+ return new ArrayList<GeneralName>(generalNames);
}
/**
* Returns the collection of pairs: (Integer (tag), Object (name value))*
- * @return the collection of pairs: (Integer (tag), Object (name value))*
*/
- public List getPairsList() {
- ArrayList result = new ArrayList();
+ public Collection<List<?>> getPairsList() {
+ Collection<List<?>> result = new ArrayList<List<?>>();
if (generalNames == null) {
return result;
}
- Iterator it = generalNames.iterator();
- while (it.hasNext()) {
- result.add(((GeneralName) it.next()).getAsList());
+ for (GeneralName generalName : generalNames) {
+ result.add(generalName.getAsList());
}
return result;
}
- /**
- * TODO
- * @param name: GeneralName
- * @return
- */
public void addName(GeneralName name) {
encoding = null;
if (generalNames == null) {
- generalNames = new ArrayList();
+ generalNames = new ArrayList<GeneralName>();
}
generalNames.add(name);
}
- /* *
- * TODO
- * @param name: GeneralName
- * @return
- *
- public GeneralName getNameByTag(int tag) {
- encoding = null;
- if ((generalNames == null) || (generalNames.size() == 0)) {
- return null;
- }
- for (int i=0; i<generalNames.size(); i++) {
- if (((GeneralName) generalName.get(i)).getTag() == tag) {
- }
- }
- generalNames.add(name);
- }
- */
-
/**
* Returns ASN.1 encoded form of this X.509 GeneralNames value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -156,9 +115,9 @@
if (generalNames == null) {
return;
}
- for (Iterator it=generalNames.iterator(); it.hasNext();) {
+ for (GeneralName generalName : generalNames) {
buffer.append(prefix);
- buffer.append(it.next());
+ buffer.append(generalName);
buffer.append('\n');
}
}
@@ -167,12 +126,11 @@
* ASN.1 DER X.509 GeneralNames encoder/decoder class.
*/
public static final ASN1Type ASN1 = new ASN1SequenceOf(GeneralName.ASN1) {
-
- public Object getDecodedObject(BerInputStream in) {
- return new GeneralNames((List)in.content, in.getEncoded());
+ @Override public Object getDecodedObject(BerInputStream in) {
+ return new GeneralNames((List<GeneralName>) in.content, in.getEncoded());
}
- public Collection getValues(Object object) {
+ @Override public Collection getValues(Object object) {
GeneralNames gns = (GeneralNames) object;
return gns.generalNames;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtree.java b/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtree.java
index 4ea1b41..ce21634 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtree.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtree.java
@@ -50,40 +50,16 @@
* @see org.apache.harmony.security.x509.NameConstraints
* @see org.apache.harmony.security.x509.GeneralName
*/
-public class GeneralSubtree {
-
- // the value of base field of the structure
+public final class GeneralSubtree {
+ /** the value of base field of the structure */
private final GeneralName base;
- // the value of minimum field of the structure
+ /** the value of minimum field of the structure */
private final int minimum;
- // the value of maximum field of the structure
+ /** the value of maximum field of the structure */
private final int maximum;
- // the ASN.1 encoded form of GeneralSubtree
+ /** the ASN.1 encoded form of GeneralSubtree */
private byte[] encoding;
- /**
- * TODO
- * @param base: GeneralName
- */
- public GeneralSubtree(GeneralName base) {
- this(base, 0, -1);
- }
-
- /**
- * TODO
- * @param base: GeneralName
- * @param minimum: int
- */
- public GeneralSubtree(GeneralName base, int minimum) {
- this(base, minimum, -1);
- }
-
- /**
- * TODO
- * @param base: GeneralName
- * @param minimum: int
- * @param maximum: int
- */
public GeneralSubtree(GeneralName base, int minimum, int maximum) {
this.base = base;
this.minimum = minimum;
@@ -92,31 +68,13 @@
/**
* Returns the value of base field of the structure.
- * @return base
*/
public GeneralName getBase() {
return base;
}
/**
- * Returns the value of maximum field of the structure.
- * @return maximum
- */
- public int getMaximum() {
- return maximum;
- }
-
- /**
- * Returns the value of minimum field of the structure.
- * @return minimum
- */
- public int getMinimum() {
- return minimum;
- }
-
- /**
* Returns ASN.1 encoded form of this X.509 GeneralSubtree value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -153,7 +111,7 @@
setOptional(2); // maximum optional
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
int maximum = -1; // is optional maximum missing?
if (values[2] != null) {
@@ -164,10 +122,8 @@
maximum);
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
GeneralSubtree gs = (GeneralSubtree) object;
-
values[0] = gs.base;
values[1] = ASN1Integer.fromIntValue(gs.minimum);
if (gs.maximum > -1) {
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtrees.java b/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtrees.java
index 426454a..34f4bc7 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtrees.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/GeneralSubtrees.java
@@ -44,53 +44,26 @@
* @see org.apache.harmony.security.x509.NameConstraints
* @see org.apache.harmony.security.x509.GeneralSubtree
*/
-
-public class GeneralSubtrees {
-
- // the list of values of GeneralSubtrees
- private List generalSubtrees;
- // the ASN.1 encoded form of GeneralSubtrees
+public final class GeneralSubtrees {
+ /** the list of values of GeneralSubtrees */
+ private List<GeneralSubtree> generalSubtrees;
+ /** the ASN.1 encoded form of GeneralSubtrees */
private byte[] encoding;
- /**
- * Constructs an object representing the value of GeneralSubtrees.
- */
- public GeneralSubtrees() {}
-
- /**
- * TODO
- * @param generalSubtrees: List
- */
- public GeneralSubtrees(List generalSubtrees) {
+ public GeneralSubtrees(List<GeneralSubtree> generalSubtrees) {
// TODO: the size should not be less than one
this.generalSubtrees = generalSubtrees;
}
/**
* Returns the list of values of subtrees.
- * @return subtrees
*/
- public List getSubtrees() {
+ public List<GeneralSubtree> getSubtrees() {
return generalSubtrees;
}
/**
- * TODO
- * @param subtree: GeneralSubtree
- * @return
- */
- public GeneralSubtrees addSubtree(GeneralSubtree subtree) {
- encoding = null;
- if (generalSubtrees == null) {
- generalSubtrees = new ArrayList();
- }
- generalSubtrees.add(subtree);
- return this;
- }
-
- /**
* Returns ASN.1 encoded form of this X.509 AlgorithmIdentifier value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -103,15 +76,15 @@
* ASN.1 DER X.509 GeneralSubtrees encoder/decoder class.
*/
public static final ASN1Type ASN1 = new ASN1SequenceOf(GeneralSubtree.ASN1) {
-
- public Object getDecodedObject(BerInputStream in) {
- return new GeneralSubtrees((List)in.content);
+ @Override public Object getDecodedObject(BerInputStream in) {
+ return new GeneralSubtrees((List<GeneralSubtree>) in.content);
}
- public Collection getValues(Object object) {
+ @Override public Collection getValues(Object object) {
GeneralSubtrees gss = (GeneralSubtrees) object;
return (gss.generalSubtrees == null)
- ? new ArrayList() : gss.generalSubtrees;
+ ? new ArrayList<GeneralSubtree>()
+ : gss.generalSubtrees;
}
};
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/InfoAccessSyntax.java b/luni/src/main/java/org/apache/harmony/security/x509/InfoAccessSyntax.java
index 5f26b1e..bf04391 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/InfoAccessSyntax.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/InfoAccessSyntax.java
@@ -18,9 +18,7 @@
package org.apache.harmony.security.x509;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.Iterator;
import java.util.List;
import org.apache.harmony.security.asn1.ASN1SequenceOf;
import org.apache.harmony.security.asn1.ASN1Type;
@@ -46,16 +44,10 @@
* accessLocation GeneralName }
*
*/
-public class InfoAccessSyntax extends ExtensionValue {
+public final class InfoAccessSyntax extends ExtensionValue {
+ private final List<?> accessDescriptions;
- private final List accessDescriptions;
-
- public InfoAccessSyntax(List accessDescriptions) throws IOException {
- this(accessDescriptions, null);
- }
-
- private InfoAccessSyntax(List accessDescriptions, byte[] encoding)
- throws IOException {
+ private InfoAccessSyntax(List<?> accessDescriptions, byte[] encoding) throws IOException {
if (accessDescriptions == null || accessDescriptions.isEmpty()) {
throw new IOException("AccessDescriptions list is null or empty");
}
@@ -63,15 +55,10 @@
this.encoding = encoding;
}
- public List getAccessDescriptions() {
- return new ArrayList(accessDescriptions);
- }
-
/**
* Returns ASN.1 encoded form of this X.509 InfoAccessSyntax.
- * @return a byte array containing ASN.1 encoded form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
@@ -82,13 +69,13 @@
return ((InfoAccessSyntax) ASN1.decode(encoding));
}
- public String toString() {
+ @Override public String toString() {
StringBuilder res = new StringBuilder();
res.append("\n---- InfoAccessSyntax:");
if (accessDescriptions != null) {
- for (Iterator it = accessDescriptions.iterator(); it.hasNext();) {
+ for (Object accessDescription : accessDescriptions) {
res.append('\n');
- res.append(it.next());
+ res.append(accessDescription);
}
}
res.append("\n---- InfoAccessSyntax END\n");
@@ -99,14 +86,13 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("AccessDescriptions:\n");
if (accessDescriptions == null || accessDescriptions.isEmpty()) {
buffer.append("NULL\n");
} else {
- Iterator itr = accessDescriptions.iterator();
- while (itr.hasNext()) {
- buffer.append(itr.next().toString());
+ for (Object accessDescription : accessDescriptions) {
+ buffer.append(accessDescription.toString());
}
}
}
@@ -117,14 +103,12 @@
* encoder/decoder class.
*/
public static final ASN1Type ASN1 = new ASN1SequenceOf(AccessDescription.ASN1) {
-
- public Object getDecodedObject(BerInputStream in) throws IOException {
- return new InfoAccessSyntax((List)in.content, in.getEncoded());
+ @Override public Object getDecodedObject(BerInputStream in) throws IOException {
+ return new InfoAccessSyntax((List<?>) in.content, in.getEncoded());
}
- public Collection getValues(Object object) {
- InfoAccessSyntax aias = (InfoAccessSyntax) object;
- return aias.accessDescriptions;
+ @Override public Collection getValues(Object object) {
+ return ((InfoAccessSyntax) object).accessDescriptions;
}
};
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/InhibitAnyPolicy.java b/luni/src/main/java/org/apache/harmony/security/x509/InhibitAnyPolicy.java
index df0d95d..b80b446 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/InhibitAnyPolicy.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/InhibitAnyPolicy.java
@@ -33,17 +33,10 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt).
*/
-public class InhibitAnyPolicy extends ExtensionValue {
+public final class InhibitAnyPolicy extends ExtensionValue {
- // the value of the extension
- private int skipCerts;
-
- /**
- * Create the object on the base of SkipCerts value.
- */
- public InhibitAnyPolicy(int skipCerts) {
- this.skipCerts = skipCerts;
- }
+ /** the value of the extension */
+ private final int skipCerts;
/**
* Creates an object on the base of its encoded form.
@@ -55,17 +48,9 @@
}
/**
- * Return the value of the extension.
- */
- public int getSkipCerts() {
- return skipCerts;
- }
-
- /**
* Returns ASN.1 encoded form of the object.
- * @return a byte array containing ASN.1 encoded form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1Integer.getInstance()
.encode(ASN1Integer.fromIntValue(skipCerts));
@@ -77,7 +62,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Inhibit Any-Policy: ")
.append(skipCerts).append('\n');
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java b/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java
index a0dce86..8c8073c 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/InvalidityDate.java
@@ -31,19 +31,11 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt)
*/
-public class InvalidityDate extends ExtensionValue {
-
- // invalidity date value
+public final class InvalidityDate extends ExtensionValue {
+ /** invalidity date value */
private final Date date;
/**
- * Constructs the object on the base of the invalidity date value.
- */
- public InvalidityDate(Date date) {
- this.date = date;
- }
-
- /**
* Constructs the object on the base of its encoded form.
*/
public InvalidityDate(byte[] encoding) throws IOException {
@@ -60,9 +52,8 @@
/**
* Returns ASN.1 encoded form of this X.509 InvalidityDate value.
- * @return a byte array containing ASN.1 encoded form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(date);
}
@@ -73,7 +64,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Invalidity Date: [ ")
.append(date).append(" ]\n");
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/IssuingDistributionPoint.java b/luni/src/main/java/org/apache/harmony/security/x509/IssuingDistributionPoint.java
index a92a622..6c11616 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/IssuingDistributionPoint.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/IssuingDistributionPoint.java
@@ -41,8 +41,7 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt)
*/
-public class IssuingDistributionPoint extends ExtensionValue {
-
+public final class IssuingDistributionPoint extends ExtensionValue {
// values of the fields of the structure
private DistributionPointName distributionPoint;
private boolean onlyContainsUserCerts = false;
@@ -101,53 +100,7 @@
this.onlyContainsAttributeCerts = onlyContainsAttributeCerts;
}
- /**
- * Returns value of distributionPoint field of the structure.
- */
- public DistributionPointName getDistributionPoint() {
- return distributionPoint;
- }
-
- /**
- * Returns value of onlyContainsUserCerts field of the structure.
- */
- public boolean getOnlyContainsUserCerts() {
- return onlyContainsUserCerts;
- }
-
- /**
- * Returns value of onlyContainsCACerts field of the structure.
- */
- public boolean getOnlyContainsCACerts() {
- return onlyContainsCACerts;
- }
-
- /**
- * Returns value of onlySomeReasons field of the structure.
- */
- public ReasonFlags getOnlySomeReasons() {
- return onlySomeReasons;
- }
-
- /**
- * Returns value of indirectCRL field of the structure.
- */
- public boolean getIndirectCRL() {
- return indirectCRL;
- }
-
- /**
- * Returns value of onlyContainsAttributeCerts field of the structure.
- */
- public boolean getOnlyContainsAttributeCerts() {
- return onlyContainsAttributeCerts;
- }
-
- /**
- * Returns ASN.1 encoded form of this X.509 IssuingDistributionPoint value.
- * @return a byte array containing ASN.1 encoded form.
- */
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
@@ -158,7 +111,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Issuing Distribution Point: [\n");
if (distributionPoint != null) {
distributionPoint.dumpValue(buffer, " " + prefix);
@@ -200,26 +153,20 @@
protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
- IssuingDistributionPoint idp =
- new IssuingDistributionPoint(
- (DistributionPointName) values[0],
- (ReasonFlags) values[3]);
+ IssuingDistributionPoint idp = new IssuingDistributionPoint(
+ (DistributionPointName) values[0], (ReasonFlags) values[3]);
idp.encoding = in.getEncoded();
if (values[1] != null) {
- idp.setOnlyContainsUserCerts(
- ((Boolean) values[1]).booleanValue());
+ idp.setOnlyContainsUserCerts((Boolean) values[1]);
}
if (values[2] != null) {
- idp.setOnlyContainsCACerts(
- ((Boolean) values[2]).booleanValue());
+ idp.setOnlyContainsCACerts((Boolean) values[2]);
}
if (values[4] != null) {
- idp.setIndirectCRL(
- ((Boolean) values[4]).booleanValue());
+ idp.setIndirectCRL((Boolean) values[4]);
}
if (values[5] != null) {
- idp.setOnlyContainsAttributeCerts(
- ((Boolean) values[5]).booleanValue());
+ idp.setOnlyContainsAttributeCerts((Boolean) values[5]);
}
return idp;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/KeyUsage.java b/luni/src/main/java/org/apache/harmony/security/x509/KeyUsage.java
index 2207a1ac..02a71e2 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/KeyUsage.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/KeyUsage.java
@@ -43,11 +43,9 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt)
*/
-public class KeyUsage extends ExtensionValue {
+public final class KeyUsage extends ExtensionValue {
- /**
- * The names of the usages.
- */
+ /** The names of the usages. */
private static final String[] USAGES = {
"digitalSignature",
"nonRepudiation",
@@ -60,17 +58,10 @@
"decipherOnly",
};
- // the value of extension
+ /** the value of extension */
private final boolean[] keyUsage;
/**
- * Creates the extension object corresponding to the given key usage.
- */
- public KeyUsage(boolean[] keyUsage) {
- this.keyUsage = keyUsage;
- }
-
- /**
* Creates the extension object on the base of its encoded form.
*/
public KeyUsage(byte[] encoding) throws IOException {
@@ -82,22 +73,14 @@
return keyUsage;
}
- /**
- * Returns the encoded of the object.
- * @return a byte array containing ASN.1 encoded form.
- */
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(keyUsage);
}
return encoding;
}
- /**
- * Places the string representation of extension value
- * into the StringBuffer object.
- */
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("KeyUsage [\n");
for (int i=0; i<keyUsage.length; i++) {
if (keyUsage[i]) {
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/NameConstraints.java b/luni/src/main/java/org/apache/harmony/security/x509/NameConstraints.java
index e1a5588..e6f5812 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/NameConstraints.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/NameConstraints.java
@@ -25,7 +25,6 @@
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import org.apache.harmony.security.asn1.ASN1Implicit;
import org.apache.harmony.security.asn1.ASN1OctetString;
@@ -51,46 +50,34 @@
*
* </pre>
*
- *
* @see org.apache.harmony.security.x509.GeneralSubtree
* @see org.apache.harmony.security.x509.GeneralName
*/
-public class NameConstraints extends ExtensionValue {
-
- // the value of permittedSubtrees field of the structure
+public final class NameConstraints extends ExtensionValue {
+ /** the value of permittedSubtrees field of the structure */
private final GeneralSubtrees permittedSubtrees;
- // the value of excludedSubtrees field of the structure
+ /** the value of excludedSubtrees field of the structure */
private final GeneralSubtrees excludedSubtrees;
- // the ASN.1 encoded form of NameConstraints
+ /** the ASN.1 encoded form of NameConstraints */
private byte[] encoding;
- // helper fields
- private ArrayList[] permitted_names;
- private ArrayList[] excluded_names;
-
- /**
- * Default ctor
- */
- public NameConstraints() {
- this(null, null);
- }
+ private ArrayList<GeneralName>[] permitted_names;
+ private ArrayList<GeneralName>[] excluded_names;
/**
* Constructs <code>NameConstrains</code> object
- * @param permittedSubtrees: GeneralSubtrees
- * @param excludedSubtrees: GeneralSubtrees
*/
public NameConstraints(GeneralSubtrees permittedSubtrees,
GeneralSubtrees excludedSubtrees) {
if (permittedSubtrees != null) {
- List ps = permittedSubtrees.getSubtrees();
- if ((ps == null) || (ps.size() == 0)) {
+ List<GeneralSubtree> ps = permittedSubtrees.getSubtrees();
+ if (ps == null || ps.isEmpty()) {
throw new IllegalArgumentException("permittedSubtrees are empty");
}
}
if (excludedSubtrees != null) {
- List es = excludedSubtrees.getSubtrees();
- if ((es == null) || (es.size() == 0)) {
+ List<GeneralSubtree> es = excludedSubtrees.getSubtrees();
+ if (es == null || es.isEmpty()) {
throw new IllegalArgumentException("excludedSubtrees are empty");
}
}
@@ -98,12 +85,6 @@
this.excludedSubtrees = excludedSubtrees;
}
- //
- // Constructs NameConstrains object
- // @param permittedSubtrees: GeneralSubtrees
- // @param excludedSubtrees: GeneralSubtrees
- // @param encoding: byte[]
- //
private NameConstraints(GeneralSubtrees permittedSubtrees,
GeneralSubtrees excludedSubtrees, byte[] encoding) {
this(permittedSubtrees, excludedSubtrees);
@@ -114,31 +95,25 @@
return (NameConstraints) ASN1.decode(encoding);
}
- /**
- * Returns ASN.1 encoded form of this X.509 NameConstraints value.
- * @return a byte array containing ASN.1 encode form.
- */
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
return encoding;
}
- //
- // Prepare the data structure to speed up the checking process.
- //
+ /**
+ * Prepare the data structure to speed up the checking process.
+ */
private void prepareNames() {
// array of lists with permitted General Names divided by type
permitted_names = new ArrayList[9];
if (permittedSubtrees != null) {
- Iterator it = permittedSubtrees.getSubtrees().iterator();
- while (it.hasNext()) {
- GeneralName name = ((GeneralSubtree) it.next()).getBase();
- //System.out.println("PERMITTED: "+name);
+ for (GeneralSubtree generalSubtree : permittedSubtrees.getSubtrees()) {
+ GeneralName name = generalSubtree.getBase();
int tag = name.getTag();
if (permitted_names[tag] == null) {
- permitted_names[tag] = new ArrayList();
+ permitted_names[tag] = new ArrayList<GeneralName>();
}
permitted_names[tag].add(name);
}
@@ -146,22 +121,20 @@
// array of lists with excluded General Names divided by type
excluded_names = new ArrayList[9];
if (excludedSubtrees != null) {
- Iterator it = excludedSubtrees.getSubtrees().iterator();
- while (it.hasNext()) {
- GeneralName name = ((GeneralSubtree) it.next()).getBase();
- //System.out.println("EXCLUDED: "+name);
+ for (GeneralSubtree generalSubtree : excludedSubtrees.getSubtrees()) {
+ GeneralName name = generalSubtree.getBase();
int tag = name.getTag();
if (excluded_names[tag] == null) {
- excluded_names[tag] = new ArrayList();
+ excluded_names[tag] = new ArrayList<GeneralName>();
}
excluded_names[tag].add(name);
}
}
}
- //
- // Returns the value of certificate extension
- //
+ /**
+ * Returns the value of certificate extension
+ */
private byte[] getExtensionValue(X509Certificate cert, String OID) {
try {
byte[] bytes = cert.getExtensionValue(OID);
@@ -185,9 +158,9 @@
* names the same (i.e. method does not check if it CA's certificate or not,
* or if the names differ or not. This check if it is needed should be done
* by caller before calling this method).
- * @param X509Certificate : X.509 Certificate to be checked.
- * @return true, if the certificate is acceptable according
- * these NameConstraints restrictions, and false otherwise.
+ * @param cert X.509 Certificate to be checked.
+ * @return true if the certificate is acceptable according
+ * these NameConstraints restrictions
*/
public boolean isAcceptable(X509Certificate cert) {
if (permitted_names == null) {
@@ -195,10 +168,10 @@
}
byte[] bytes = getExtensionValue(cert, "2.5.29.17");
- List names;
+ List<GeneralName> names;
try {
names = (bytes == null)
- ? new ArrayList(1) // will check the subject field only
+ ? new ArrayList<GeneralName>(1) // will check the subject field only
: ((GeneralNames) GeneralNames.ASN1.decode(bytes)).getNames();
} catch (IOException e) {
// the certificate is broken;
@@ -217,31 +190,26 @@
}
/**
- * Check if this list of names is acceptable accoring to this
+ * Check if this list of names is acceptable according to this
* NameConstraints object.
- * @param names: List
- * @return
*/
- public boolean isAcceptable(List names) {
+ public boolean isAcceptable(List<GeneralName> names) {
if (permitted_names == null) {
prepareNames();
}
- Iterator it = names.iterator();
// check map: shows which types of permitted alternative names are
// presented in the certificate
boolean[] types_presented = new boolean[9];
// check map: shows if permitted name of presented type is found
// among the certificate's alternative names
boolean[] permitted_found = new boolean[9];
- while (it.hasNext()) {
- GeneralName name = (GeneralName) it.next();
+ for (GeneralName name : names) {
int type = name.getTag();
// search the name in excluded names
if (excluded_names[type] != null) {
- for (int i=0; i<excluded_names[type].size(); i++) {
- if (((GeneralName) excluded_names[type].get(i))
- .isAcceptable(name)) {
+ for (int i = 0; i < excluded_names[type].size(); i++) {
+ if (excluded_names[type].get(i).isAcceptable(name)) {
return false;
}
}
@@ -251,16 +219,15 @@
// names - we do not need to check others)
if ((permitted_names[type] != null) && (!permitted_found[type])) {
types_presented[type] = true;
- for (int i=0; i<permitted_names[type].size(); i++) {
- if (((GeneralName) permitted_names[type].get(i))
- .isAcceptable(name)) {
+ for (int i = 0; i < permitted_names[type].size(); i++) {
+ if (permitted_names[type].get(i).isAcceptable(name)) {
// found one permitted name of such type
permitted_found[type] = true;
}
}
}
}
- for (int type=0; type<9; type++) {
+ for (int type = 0; type < 9; type++) {
if (types_presented[type] && !permitted_found[type]) {
return false;
}
@@ -268,25 +235,19 @@
return true;
}
- /**
- * Places the string representation of extension value
- * into the StringBuffer object.
- */
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Name Constraints: [\n");
if (permittedSubtrees != null) {
buffer.append(prefix).append(" Permitted: [\n");
- for (Iterator it=permittedSubtrees.getSubtrees().iterator();
- it.hasNext();) {
- ((GeneralSubtree) it.next()).dumpValue(buffer, prefix + " ");
+ for (GeneralSubtree generalSubtree : permittedSubtrees.getSubtrees()) {
+ generalSubtree.dumpValue(buffer, prefix + " ");
}
buffer.append(prefix).append(" ]\n");
}
if (excludedSubtrees != null) {
buffer.append(prefix).append(" Excluded: [\n");
- for (Iterator it=excludedSubtrees.getSubtrees().iterator();
- it.hasNext();) {
- ((GeneralSubtree) it.next()).dumpValue(buffer, prefix + " ");
+ for (GeneralSubtree generalSubtree : excludedSubtrees.getSubtrees()) {
+ generalSubtree.dumpValue(buffer, prefix + " ");
}
buffer.append(prefix).append(" ]\n");
}
@@ -304,7 +265,7 @@
setOptional(1);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new NameConstraints(
(GeneralSubtrees) values[0],
@@ -312,10 +273,8 @@
in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
NameConstraints nc = (NameConstraints) object;
-
values[0] = nc.permittedSubtrees;
values[1] = nc.excludedSubtrees;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/ORAddress.java b/luni/src/main/java/org/apache/harmony/security/x509/ORAddress.java
index f5b4bae..1e6b0a7 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/ORAddress.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/ORAddress.java
@@ -45,19 +45,13 @@
*
* TODO: this class needs to be finished.
*/
-public class ORAddress {
+public final class ORAddress {
- // the ASN.1 encoded form of ORAddress
+ /** the ASN.1 encoded form of ORAddress */
private byte[] encoding;
/**
- * TODO
- */
- public ORAddress() {}
-
- /**
* Returns ASN.1 encoded form of this X.509 ORAddress value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -71,21 +65,16 @@
*/
public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
new ASN1Sequence(new ASN1Type[] {}) {
- protected Object getDecodedObject(Object[] values) {
- return null;
- }
-
- protected void getValues(Object object, Object[] values) {
- }
+ @Override protected void getValues(Object object, Object[] values) {}
}}) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
return new ORAddress();
}
- private final Object foo = new Object(); //$NON-LOCK-1$
+ private final Object foo = new Object();
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
values[0] = foo;
}
};
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/OtherName.java b/luni/src/main/java/org/apache/harmony/security/x509/OtherName.java
index d0e9693..cb83f2e 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/OtherName.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/OtherName.java
@@ -45,29 +45,18 @@
* }
* </pre>
*/
-public class OtherName {
- // the value of typeID field of the structure
+public final class OtherName {
+ /** the value of typeID field of the structure */
private String typeID;
- // the value of value field of the structure
+ /** the value of value field of the structure */
private byte[] value;
- // the ASN.1 encoded form of OtherName
+ /** the ASN.1 encoded form of OtherName */
private byte[] encoding;
- /**
- * TODO
- * @param typeID: String
- * @param value: byte[]
- */
public OtherName(String typeID, byte[] value) {
this(typeID, value, null);
}
- //
- // TODO
- // @param typeID: String
- // @param value: byte[]
- // @param encoding: byte[]
- //
private OtherName(String typeID, byte[] value, byte[] encoding) {
this.typeID = typeID;
this.value = value;
@@ -75,16 +64,7 @@
}
/**
- * Returns the value of typeID field of the structure.
- * @return typeID
- */
- public String getTypeID() {
- return typeID;
- }
-
- /**
* Returns the value of value field of the structure.
- * @return value
*/
public byte[] getValue() {
return value;
@@ -92,7 +72,6 @@
/**
* Returns ASN.1 encoded form of this X.509 OtherName value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -108,16 +87,14 @@
ASN1Oid.getInstance(),
new ASN1Explicit(0, ASN1Any.getInstance()) }) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new OtherName(ObjectIdentifier.toString((int[]) values[0]),
(byte[]) values[1], in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
OtherName on = (OtherName) object;
-
values[0] = ObjectIdentifier.toIntArray(on.typeID);
values[1] = on.value;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/PolicyConstraints.java b/luni/src/main/java/org/apache/harmony/security/x509/PolicyConstraints.java
index fffcdbd..e86a498 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/PolicyConstraints.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/PolicyConstraints.java
@@ -53,44 +53,20 @@
* @see org.apache.harmony.security.x509.GeneralSubtree
* @see org.apache.harmony.security.x509.GeneralName
*/
-public class PolicyConstraints extends ExtensionValue {
-
- // the value of requireExplicitPolicy field of the structure
+public final class PolicyConstraints extends ExtensionValue {
+ /** the value of requireExplicitPolicy field of the structure */
private final BigInteger requireExplicitPolicy;
- // the value of inhibitPolicyMapping field of the structure
+ /** the value of inhibitPolicyMapping field of the structure */
private final BigInteger inhibitPolicyMapping;
- // the ASN.1 encoded form of PolicyConstraints;
+ /** the ASN.1 encoded form of PolicyConstraints */
private byte[] encoding;
- /**
- * TODO
- */
- public PolicyConstraints() {
- this(null, null);
- }
-
- /**
- * TODO
- * @param requireExplicitPolicy: GeneralSubtrees
- * @param inhibitPolicyMapping: GeneralSubtrees
- */
public PolicyConstraints(BigInteger requireExplicitPolicy,
BigInteger inhibitPolicyMapping) {
this.requireExplicitPolicy = requireExplicitPolicy;
this.inhibitPolicyMapping = inhibitPolicyMapping;
}
- /**
- * TODO
- * @param requireExplicitPolicy: GeneralSubtrees
- * @param inhibitPolicyMapping: GeneralSubtrees
- */
- public PolicyConstraints(int requireExplicitPolicy,
- int inhibitPolicyMapping) {
- this.requireExplicitPolicy = BigInteger.valueOf(requireExplicitPolicy);
- this.inhibitPolicyMapping = BigInteger.valueOf(inhibitPolicyMapping);
- }
-
public PolicyConstraints(byte[] encoding) throws IOException {
super(encoding);
PolicyConstraints pc = (PolicyConstraints) ASN1.decode(encoding);
@@ -98,12 +74,6 @@
this.inhibitPolicyMapping = pc.inhibitPolicyMapping;
}
- //
- // TODO
- // @param requireExplicitPolicy: GeneralSubtrees
- // @param inhibitPolicyMapping: GeneralSubtrees
- // @param encoding: byte[]
- //
private PolicyConstraints(BigInteger requireExplicitPolicy,
BigInteger inhibitPolicyMapping, byte[] encoding) {
this(requireExplicitPolicy, inhibitPolicyMapping);
@@ -112,9 +82,8 @@
/**
* Returns ASN.1 encoded form of this X.509 PolicyConstraints value.
- * @return a byte array containing ASN.1 encode form.
*/
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(this);
}
@@ -125,7 +94,7 @@
* Places the string representation of extension value
* into the StringBuffer object.
*/
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("PolicyConstraints: [\n");
if (requireExplicitPolicy != null) {
buffer.append(prefix).append(" requireExplicitPolicy: ")
@@ -149,7 +118,7 @@
setOptional(1);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
BigInteger requireExplicitPolicy = null;
BigInteger inhibitPolicyMapping = null;
@@ -164,10 +133,8 @@
in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
PolicyConstraints pc = (PolicyConstraints) object;
-
values[0] = pc.requireExplicitPolicy.toByteArray();
values[1] = pc.inhibitPolicyMapping.toByteArray();
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/PolicyInformation.java b/luni/src/main/java/org/apache/harmony/security/x509/PolicyInformation.java
index bdade63..51ab57e0 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/PolicyInformation.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/PolicyInformation.java
@@ -48,25 +48,18 @@
* TODO: This class is not fully implemented, implemented only work
* with OIDs.
*/
-
-public class PolicyInformation {
-
- // the value of policyIdentifier field of the structure
- private String policyIdentifier;
- // the ASN.1 encoded form of PolicyInformation
+public final class PolicyInformation {
+ /** the value of policyIdentifier field of the structure */
+ private final String policyIdentifier;
+ /** the ASN.1 encoded form of PolicyInformation */
private byte[] encoding;
- /**
- * TODO
- * @param policyIdentifier: String
- */
public PolicyInformation(String policyIdentifier) {
this.policyIdentifier = policyIdentifier;
}
/**
* Returns the value of policyIdentifier field of the structure.
- * @return policyIdentifier
*/
public String getPolicyIdentifier() {
return policyIdentifier;
@@ -74,7 +67,6 @@
/**
* Returns ASN.1 encoded form of this X.509 PolicyInformation value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -101,16 +93,13 @@
setOptional(1);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
- return new PolicyInformation(ObjectIdentifier
- .toString((int[]) values[0]));
+ return new PolicyInformation(ObjectIdentifier.toString((int[]) values[0]));
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
PolicyInformation pi = (PolicyInformation) object;
-
values[0] = ObjectIdentifier.toIntArray(pi.policyIdentifier);
}
};
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/PolicyQualifierInfo.java b/luni/src/main/java/org/apache/harmony/security/x509/PolicyQualifierInfo.java
index 7eda5cf..96aa633 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/PolicyQualifierInfo.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/PolicyQualifierInfo.java
@@ -48,7 +48,7 @@
* </pre>
*
*/
-public class PolicyQualifierInfo {
+public final class PolicyQualifierInfo {
// Contains only ASN1 DER decoder currently
public static final ASN1Sequence ASN1 =
new ASN1Sequence(new ASN1Type[] {ASN1Oid.getInstance(), ASN1Any.getInstance()}) {
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/PrivateKeyUsagePeriod.java b/luni/src/main/java/org/apache/harmony/security/x509/PrivateKeyUsagePeriod.java
index b0e14d5..5cb2cb9 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/PrivateKeyUsagePeriod.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/PrivateKeyUsagePeriod.java
@@ -44,32 +44,19 @@
* }
* </pre>
*/
-public class PrivateKeyUsagePeriod {
-
- // the value of notBeforeDate field of the structure
+public final class PrivateKeyUsagePeriod {
+ /** the value of notBeforeDate field of the structure */
private final Date notBeforeDate;
- // the value of notAfterDate field of the structure
+ /** the value of notAfterDate field of the structure */
private final Date notAfterDate;
- // the ASN.1 encoded form of PrivateKeyUsagePeriod
+ /** the ASN.1 encoded form of PrivateKeyUsagePeriod */
private byte[] encoding;
- /**
- * TODO
- * @param notBeforeDate: Date
- * @param notAfterDate: Date
- */
public PrivateKeyUsagePeriod(Date notBeforeDate, Date notAfterDate) {
this(notBeforeDate, notAfterDate, null);
}
- //
- // TODO
- // @param notBeforeDate: Date
- // @param notAfterDate: Date
- // @param encoding: byte[]
- //
- private PrivateKeyUsagePeriod(Date notBeforeDate,
- Date notAfterDate, byte[] encoding) {
+ private PrivateKeyUsagePeriod(Date notBeforeDate, Date notAfterDate, byte[] encoding) {
this.notBeforeDate = notBeforeDate;
this.notAfterDate = notAfterDate;
this.encoding = encoding;
@@ -77,7 +64,6 @@
/**
* Returns the value of notBefore field of the structure.
- * @return notBefore
*/
public Date getNotBefore() {
return notBeforeDate;
@@ -85,7 +71,6 @@
/**
* Returns the value of notAfter field of the structure.
- * @return notAfter
*/
public Date getNotAfter() {
return notAfterDate;
@@ -93,7 +78,6 @@
/**
* Returns ASN.1 encoded form of this X.509 PrivateKeyUsagePeriod value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -113,17 +97,13 @@
setOptional(1);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[])in.content;
- return
- new PrivateKeyUsagePeriod((Date) values[0], (Date) values[1],
- in.getEncoded());
+ return new PrivateKeyUsagePeriod((Date) values[0], (Date) values[1], in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
PrivateKeyUsagePeriod pkup = (PrivateKeyUsagePeriod) object;
-
values[0] = pkup.notBeforeDate;
values[1] = pkup.notAfterDate;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java b/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java
index d94e8b3..61fbbc6 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/ReasonCode.java
@@ -42,7 +42,7 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt)
*/
-public class ReasonCode extends ExtensionValue {
+public final class ReasonCode extends ExtensionValue {
// predefined reason code values
public static final byte UNSPECIFIED = 0;
@@ -59,35 +59,19 @@
// the reason code value
private final byte code;
- public ReasonCode(byte code) {
- this.code = code;
- }
-
public ReasonCode(byte[] encoding) throws IOException {
super(encoding);
this.code = ((byte[]) ASN1.decode(encoding))[0];
}
- public int getCode() {
- return code;
- }
-
- /**
- * Returns ASN.1 encoded form of this X.509 ReasonCode value.
- * @return a byte array containing ASN.1 encode form.
- */
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1.encode(new byte[] { code });
}
return encoding;
}
- /**
- * Places the string representation of extension value
- * into the StringBuffer object.
- */
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("Reason Code: [ ");
switch (code) {
case UNSPECIFIED:
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/ReasonFlags.java b/luni/src/main/java/org/apache/harmony/security/x509/ReasonFlags.java
index 0be3637..beb4a1c 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/ReasonFlags.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/ReasonFlags.java
@@ -49,7 +49,7 @@
* }
* </pre>
*/
-public class ReasonFlags {
+public final class ReasonFlags {
/**
* The names of the reasons.
@@ -66,8 +66,8 @@
"aACompromise"
};
- // the value of extension
- private boolean[] flags;
+ /** the value of extension */
+ private final boolean[] flags;
/**
* Creates the extension object corresponding to the given flags.
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/SubjectKeyIdentifier.java b/luni/src/main/java/org/apache/harmony/security/x509/SubjectKeyIdentifier.java
index 185a6ca..5f22505 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/SubjectKeyIdentifier.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/SubjectKeyIdentifier.java
@@ -35,7 +35,7 @@
* </pre>
* (as specified in RFC 3280 http://www.ietf.org/rfc/rfc3280.txt)
*/
-public class SubjectKeyIdentifier extends ExtensionValue {
+public final class SubjectKeyIdentifier extends ExtensionValue {
// the value of key identifier
private final byte[] keyIdentifier;
@@ -58,22 +58,14 @@
return res;
}
- /**
- * Returns ASN.1 encoded form of extension.
- * @return a byte array containing ASN.1 encoded form.
- */
- public byte[] getEncoded() {
+ @Override public byte[] getEncoded() {
if (encoding == null) {
encoding = ASN1OctetString.getInstance().encode(keyIdentifier);
}
return encoding;
}
- /**
- * Places the string representation of extension value
- * into the StringBuffer object.
- */
- public void dumpValue(StringBuffer buffer, String prefix) {
+ @Override public void dumpValue(StringBuffer buffer, String prefix) {
buffer.append(prefix).append("SubjectKeyIdentifier: [\n");
buffer.append(Array.toString(keyIdentifier, prefix));
buffer.append(prefix).append("]\n");
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/SubjectPublicKeyInfo.java b/luni/src/main/java/org/apache/harmony/security/x509/SubjectPublicKeyInfo.java
index 1117fc2..545d489 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/SubjectPublicKeyInfo.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/SubjectPublicKeyInfo.java
@@ -49,47 +49,26 @@
* }
* </pre>
*/
-public class SubjectPublicKeyInfo {
-
- // the value of algorithmID field of the structure
+public final class SubjectPublicKeyInfo {
+ /** the value of algorithmID field of the structure */
private AlgorithmIdentifier algorithmID;
- // the value of subjectPublicKey field of the structure
+ /** the value of subjectPublicKey field of the structure */
private byte[] subjectPublicKey;
- // the public key corresponding to this SubjectPublicKeyInfo
+ /** the public key corresponding to this SubjectPublicKeyInfo */
private PublicKey publicKey;
- // the value of unusedBits field of the structure
+ /** the value of unusedBits field of the structure */
private int unusedBits;
- // the ASN.1 encoded form of SubjectPublicKeyInfo
+ /** the ASN.1 encoded form of SubjectPublicKeyInfo */
private byte[] encoding;
- /**
- * TODO
- * @param algID: AlgorithmIdentifier
- * @param subjectPublicKey: byte[]
- */
- public SubjectPublicKeyInfo(AlgorithmIdentifier algID,
- byte[] subjectPublicKey) {
+ public SubjectPublicKeyInfo(AlgorithmIdentifier algID, byte[] subjectPublicKey) {
this(algID, subjectPublicKey, 0);
}
- /**
- * TODO
- * @param algID: AlgorithmIdentifier
- * @param subjectPublicKey: byte[]
- * @param unused: int
- */
- public SubjectPublicKeyInfo(AlgorithmIdentifier algID,
- byte[] subjectPublicKey, int unused) {
+ public SubjectPublicKeyInfo(AlgorithmIdentifier algID, byte[] subjectPublicKey, int unused) {
this(algID, subjectPublicKey, 0, null);
}
- //
- // TODO
- // @param algID: AlgorithmIdentifier
- // @param subjectPublicKey: byte[]
- // @param unused: int
- // @param encoding: byte[]
- //
private SubjectPublicKeyInfo(AlgorithmIdentifier algID,
byte[] subjectPublicKey, int unused,
byte[] encoding) {
@@ -101,7 +80,6 @@
/**
* Returns the value of algorithmIdentifier field of the structure.
- * @return algorithmIdentifier
*/
public AlgorithmIdentifier getAlgorithmIdentifier() {
return algorithmID;
@@ -109,23 +87,13 @@
/**
* Returns the value of subjectPublicKey field of the structure.
- * @return subjectPublicKey
*/
public byte[] getSubjectPublicKey() {
return subjectPublicKey;
}
/**
- * Returns the value of unusedBits field of the structure.
- * @return unusedBits
- */
- public int getUnusedBits() {
- return unusedBits;
- }
-
- /**
* Returns ASN.1 encoded form of this X.509 SubjectPublicKeyInfo value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -137,7 +105,6 @@
/**
* Returns The PublicKey corresponding to this SubjectPublicKeyInfo
* instance.
- * @return public key corresponding to this SubjectPublicKeyInfo.
*/
public PublicKey getPublicKey() {
if (publicKey == null) {
@@ -151,8 +118,8 @@
}
publicKey = KeyFactory.getInstance(alg)
.generatePublic(new X509EncodedKeySpec(getEncoded()));
- } catch (InvalidKeySpecException e) {
- } catch (NoSuchAlgorithmException e) {
+ } catch (InvalidKeySpecException ignored) {
+ } catch (NoSuchAlgorithmException ignored) {
}
if (publicKey == null) {
publicKey = new X509PublicKey(alg_oid, getEncoded(),
@@ -164,8 +131,7 @@
public static final ASN1Sequence ASN1 = new ASN1Sequence(new ASN1Type[] {
AlgorithmIdentifier.ASN1, ASN1BitString.getInstance() }) {
-
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new SubjectPublicKeyInfo(
(AlgorithmIdentifier) values[0],
@@ -174,10 +140,8 @@
in.getEncoded());
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) object;
-
values[0] = spki.algorithmID;
values[1] = new BitString(spki.subjectPublicKey, spki.unusedBits);
}
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 78b294d..e031dbb 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
@@ -26,7 +26,6 @@
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
-import java.util.Iterator;
import java.util.List;
import javax.security.auth.x500.X500Principal;
import org.apache.harmony.security.asn1.ASN1Explicit;
@@ -65,23 +64,22 @@
* }
* </pre>
*/
-public class TBSCertList {
-
- // the value of version field of the structure
+public final class TBSCertList {
+ /** the value of version field of the structure */
private final int version;
- // the value of signature field of the structure
+ /** the value of signature field of the structure */
private final AlgorithmIdentifier signature;
- // the value of issuer field of the structure
+ /** the value of issuer field of the structure */
private final Name issuer;
- // the value of thisUpdate of the structure
+ /** the value of thisUpdate of the structure */
private final Date thisUpdate;
- // the value of nextUpdate of the structure
+ /** the value of nextUpdate of the structure */
private final Date nextUpdate;
- // the value of revokedCertificates of the structure
- private final List revokedCertificates;
- // the value of crlExtensions field of the structure
+ /** the value of revokedCertificates of the structure */
+ private final List<RevokedCertificate> revokedCertificates;
+ /** the value of crlExtensions field of the structure */
private final Extensions crlExtensions;
- // the ASN.1 encoded form of TBSCertList
+ /** the ASN.1 encoded form of TBSCertList */
private byte[] encoding;
public static class RevokedCertificate {
@@ -181,9 +179,8 @@
setOptional(2);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
-
return new RevokedCertificate(
new BigInteger((byte[]) values[0]),
(Date) values[1],
@@ -191,9 +188,8 @@
);
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
RevokedCertificate rcert = (RevokedCertificate) object;
-
values[0] = rcert.userCertificate.toByteArray();
values[1] = rcert.revocationDate;
values[2] = rcert.crlEntryExtensions;
@@ -201,63 +197,10 @@
};
}
- /**
- * Constructs the instance of TBSCertList without optional fields.
- * Take a note, that regarding to the rfc 3280 (p. 49):
- * "When CRLs are issued, the CRLs MUST be version 2 CRLs, include the date
- * by which the next CRL will be issued in the nextUpdate field (section
- * 5.1.2.5), include the CRL number extension (section 5.2.3), and include
- * the authority key identifier extension (section 5.2.1). Conforming
- * applications that support CRLs are REQUIRED to process both version 1 and
- * version 2 complete CRLs that provide revocation information for all
- * certificates issued by one CA. Conforming applications are NOT REQUIRED
- * to support processing of delta CRLs, indirect CRLs, or CRLs with a scope
- * other than all certificates issued by one CA."
- * @param signature: AlgorithmIdentifier
- * @param issuer: Name
- * @param thisUpdate: Time
- */
- public TBSCertList(AlgorithmIdentifier signature,
- Name issuer, Date thisUpdate) {
- this.version = 1;
- this.signature = signature;
- this.issuer = issuer;
- this.thisUpdate = thisUpdate;
- this.nextUpdate = null;
- this.revokedCertificates = null;
- this.crlExtensions = null;
- }
-
- /**
- * Constructs the instance of TBSCertList with all optional fields
- * @param version: version of the CRL. Should be 1 or 2.
- * Note that if the version of CRL is 1, then nextUpdate,
- * crlExtensions fields of CRL and crlEntryExtensions field
- * of CRL entry must not be presented in CRL.
- * FIXME: do check for it.
- * @param signature: AlgorithmIdentifier
- * @param issuer: Name
- * @param thisUpdate: Time
- * @param nextUpdate: Time
- * @param revokedCertificates: List
- * @param crlExtensions: Extensions
- */
- public TBSCertList(int version, AlgorithmIdentifier signature,
- Name issuer, Date thisUpdate, Date nextUpdate,
- List revokedCertificates, Extensions crlExtensions) {
- this.version = version;
- this.signature = signature;
- this.issuer = issuer;
- this.thisUpdate = thisUpdate;
- this.nextUpdate = nextUpdate;
- this.revokedCertificates = revokedCertificates;
- this.crlExtensions = crlExtensions;
- }
-
- // Constructs the object with associated ASN.1 encoding
+ /** Constructs the object with associated ASN.1 encoding */
private TBSCertList(int version, AlgorithmIdentifier signature,
Name issuer, Date thisUpdate, Date nextUpdate,
- List revokedCertificates, Extensions crlExtensions,
+ List<RevokedCertificate> revokedCertificates, Extensions crlExtensions,
byte[] encoding) {
this.version = version;
this.signature = signature;
@@ -271,7 +214,6 @@
/**
* Returns the value of version field of the structure.
- * @return version
*/
public int getVersion() {
return version;
@@ -279,7 +221,6 @@
/**
* Returns the value of signature field of the structure.
- * @return signature
*/
public AlgorithmIdentifier getSignature() {
return signature;
@@ -287,7 +228,6 @@
/**
* Returns the value of issuer field of the structure.
- * @return issuer
*/
public Name getIssuer() {
return issuer;
@@ -295,7 +235,6 @@
/**
* Returns the value of thisUpdate field of the structure.
- * @return thisUpdate
*/
public Date getThisUpdate() {
return thisUpdate;
@@ -303,7 +242,6 @@
/**
* Returns the value of nextUpdate field of the structure.
- * @return nextUpdate
*/
public Date getNextUpdate() {
return nextUpdate;
@@ -311,15 +249,13 @@
/**
* Returns the value of revokedCertificates field of the structure.
- * @return revokedCertificates
*/
- public List getRevokedCertificates() {
+ public List<RevokedCertificate> getRevokedCertificates() {
return revokedCertificates;
}
/**
* Returns the value of crlExtensions field of the structure.
- * @return extensions
*/
public Extensions getCrlExtensions() {
return crlExtensions;
@@ -327,7 +263,6 @@
/**
* Returns ASN.1 encoded form of this X.509 TBSCertList value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -336,33 +271,29 @@
return encoding;
}
- public boolean equals(Object tbs) {
- if (!(tbs instanceof TBSCertList)) {
+ @Override public boolean equals(Object other) {
+ if (!(other instanceof TBSCertList)) {
return false;
}
- TBSCertList tbscert = (TBSCertList) tbs;
- return (version == tbscert.version)
- && (signature.equals(tbscert.signature))
- // FIXME use Name.equals when it will be implemented
- && (Arrays.equals(issuer.getEncoded(), tbscert.issuer.getEncoded()))
- && ((thisUpdate.getTime() / 1000)
- == (tbscert.thisUpdate.getTime() / 1000))
- && ((nextUpdate == null)
- ? tbscert.nextUpdate == null
- : ((nextUpdate.getTime() / 1000)
- == (tbscert.nextUpdate.getTime() / 1000)))
- && ((((revokedCertificates == null)
- || (tbscert.revokedCertificates == null))
- && (revokedCertificates == tbscert.revokedCertificates))
- || (revokedCertificates.containsAll(tbscert.revokedCertificates)
- && (revokedCertificates.size()
- == tbscert.revokedCertificates.size())))
- && ((crlExtensions == null)
- ? tbscert.crlExtensions == null
- : crlExtensions.equals(tbscert.crlExtensions));
+ TBSCertList that = (TBSCertList) other;
+ return version == that.version
+ && signature.equals(that.signature)
+ && Arrays.equals(issuer.getEncoded(), that.issuer.getEncoded())
+ && thisUpdate.getTime() / 1000
+ == that.thisUpdate.getTime() / 1000
+ && (nextUpdate == null
+ ? that.nextUpdate == null
+ : nextUpdate.getTime() / 1000
+ == that.nextUpdate.getTime() / 1000)
+ && ((revokedCertificates == null || that.revokedCertificates == null)
+ && revokedCertificates == that.revokedCertificates
+ || revokedCertificates.equals(that.revokedCertificates))
+ && (crlExtensions == null
+ ? that.crlExtensions == null
+ : crlExtensions.equals(that.crlExtensions));
}
- public int hashCode() {
+ @Override public int hashCode() {
return ((version * 37 + signature.hashCode()) * 37
+ issuer.getEncoded().hashCode()) * 37
+ (int)thisUpdate.getTime() / 1000;
@@ -384,9 +315,9 @@
buffer.append("\nRevoked Certificates: ")
.append(revokedCertificates.size()).append(" [");
int number = 1;
- for (Iterator it = revokedCertificates.iterator();it.hasNext();) {
+ for (RevokedCertificate revokedCertificate : revokedCertificates) {
buffer.append("\n [").append(number++).append(']');
- ((RevokedCertificate) it.next()).dumpValue(buffer, " ");
+ revokedCertificate.dumpValue(buffer, " ");
buffer.append('\n');
}
buffer.append("]\n");
@@ -418,8 +349,7 @@
setOptional(6);
}
- protected Object getDecodedObject(BerInputStream in)
- throws IOException {
+ @Override protected Object getDecodedObject(BerInputStream in) throws IOException {
Object[] values = (Object[]) in.content;
return new TBSCertList(
(values[0] == null)
@@ -429,13 +359,13 @@
(Name) values[2],
(Date) values[3],
(Date) values[4],
- (List) values[5],
+ (List<RevokedCertificate>) values[5],
(Extensions) values[6],
in.getEncoded()
);
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
TBSCertList tbs = (TBSCertList) object;
values[0] = (tbs.version > 1)
? ASN1Integer.fromIntValue(tbs.version - 1) : null;
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/TBSCertificate.java b/luni/src/main/java/org/apache/harmony/security/x509/TBSCertificate.java
index 5711630..da8325d 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/TBSCertificate.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/TBSCertificate.java
@@ -60,63 +60,31 @@
* }
* </pre>
*/
-public class TBSCertificate {
+public final class TBSCertificate {
- // the value of version field of the structure
+ /** the value of version field of the structure */
private final int version;
- // the value of serialNumber field of the structure
+ /** the value of serialNumber field of the structure */
private final BigInteger serialNumber;
- // the value of signature field of the structure
+ /** the value of signature field of the structure */
private final AlgorithmIdentifier signature;
- // the value of issuer field of the structure
+ /** the value of issuer field of the structure */
private final Name issuer;
- // the value of validity field of the structure
+ /** the value of validity field of the structure */
private final Validity validity;
- // the value of subject field of the structure
+ /** the value of subject field of the structure */
private final Name subject;
- // the value of subjectPublicKeyInfo field of the structure
+ /** the value of subjectPublicKeyInfo field of the structure */
private final SubjectPublicKeyInfo subjectPublicKeyInfo;
- // the value of issuerUniqueID field of the structure
+ /** the value of issuerUniqueID field of the structure */
private final boolean[] issuerUniqueID;
- // the value of subjectUniqueID field of the structure
+ /** the value of subjectUniqueID field of the structure */
private final boolean[] subjectUniqueID;
- // the value of extensions field of the structure
+ /** the value of extensions field of the structure */
private final Extensions extensions;
- // the ASN.1 encoded form of TBSCertificate
- byte[] encoding;
+ /** the ASN.1 encoded form of TBSCertificate */
+ private byte[] encoding;
- /**
- * Constructs the instance of TBSCertificate without optional
- * fields (issuerUniqueID, subjectUniqueID, extensions)
- * @param version : int
- * @param serialNumber : BigInteger
- * @param signature : AlgorithmIdentifier
- * @param issuer : Name
- * @param validity : Validity
- * @param subject : Name
- * @param subjectPublicKeyInfo : SubjectPublicKeyInfo
- */
- public TBSCertificate(int version, BigInteger serialNumber,
- AlgorithmIdentifier signature, Name issuer,
- Validity validity, Name subject,
- SubjectPublicKeyInfo subjectPublicKeyInfo) {
- this(version, serialNumber, signature, issuer, validity, subject,
- subjectPublicKeyInfo, null, null, null);
- }
-
- /**
- * TODO
- * @param version: int
- * @param serialNumber: BigInteger
- * @param signature: AlgorithmIdentifier
- * @param issuer: Name
- * @param validity: Validity
- * @param subject: Name
- * @param subjectPublicKeyInfo: SubjectPublicKeyInfo
- * @param issuerUniqueID: byte[]
- * @param subjectUniqueID: byte[]
- * @param extensions: Extensions
- */
public TBSCertificate(int version, BigInteger serialNumber,
AlgorithmIdentifier signature, Name issuer,
Validity validity, Name subject,
@@ -135,20 +103,6 @@
this.extensions = extensions;
}
- //
- // TODO
- // @param version: int
- // @param serialNumber: BigInteger
- // @param signature: AlgorithmIdentifier
- // @param issuer: Name
- // @param validity: Validity
- // @param subject: Name
- // @param subjectPublicKeyInfo: SubjectPublicKeyInfo
- // @param issuerUniqueID: byte[]
- // @param subjectUniqueID: byte[]
- // @param extensions: Extensions
- // @param encoding: byte[]
- //
private TBSCertificate(int version, BigInteger serialNumber,
AlgorithmIdentifier signature, Name issuer,
Validity validity, Name subject,
@@ -162,7 +116,6 @@
/**
* Returns the value of version field of the structure.
- * @return version
*/
public int getVersion() {
return version;
@@ -170,7 +123,6 @@
/**
* Returns the value of serialNumber field of the structure.
- * @return serialNumber
*/
public BigInteger getSerialNumber() {
return serialNumber;
@@ -178,7 +130,6 @@
/**
* Returns the value of signature field of the structure.
- * @return signature
*/
public AlgorithmIdentifier getSignature() {
return signature;
@@ -186,7 +137,6 @@
/**
* Returns the value of issuer field of the structure.
- * @return issuer
*/
public Name getIssuer() {
return issuer;
@@ -194,7 +144,6 @@
/**
* Returns the value of validity field of the structure.
- * @return validity
*/
public Validity getValidity() {
return validity;
@@ -202,7 +151,6 @@
/**
* Returns the value of subject field of the structure.
- * @return subject
*/
public Name getSubject() {
return subject;
@@ -210,7 +158,6 @@
/**
* Returns the value of subjectPublicKeyInfo field of the structure.
- * @return subjectPublicKeyInfo
*/
public SubjectPublicKeyInfo getSubjectPublicKeyInfo() {
return subjectPublicKeyInfo;
@@ -218,7 +165,6 @@
/**
* Returns the value of issuerUniqueID field of the structure.
- * @return issuerUniqueID
*/
public boolean[] getIssuerUniqueID() {
return issuerUniqueID;
@@ -226,7 +172,6 @@
/**
* Returns the value of subjectUniqueID field of the structure.
- * @return subjectUniqueID
*/
public boolean[] getSubjectUniqueID() {
return subjectUniqueID;
@@ -234,7 +179,6 @@
/**
* Returns the value of extensions field of the structure.
- * @return extensions
*/
public Extensions getExtensions() {
return extensions;
@@ -242,7 +186,6 @@
/**
* Returns ASN.1 encoded form of this X.509 TBSCertificate value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -273,14 +216,14 @@
buffer.append(serialNumber);
if (issuerUniqueID != null) {
buffer.append("\n Issuer Id: ");
- for (int i=0; i<issuerUniqueID.length; i++) {
- buffer.append(issuerUniqueID[i] ? '1' : '0');
+ for (boolean b : issuerUniqueID) {
+ buffer.append(b ? '1' : '0');
}
}
if (subjectUniqueID != null) {
buffer.append("\n Subject Id: ");
- for (int i=0; i<subjectUniqueID.length; i++) {
- buffer.append(subjectUniqueID[i] ? '1' : '0');
+ for (boolean b : subjectUniqueID) {
+ buffer.append(b ? '1' : '0');
}
}
if (extensions != null) {
@@ -309,7 +252,7 @@
setOptional(9);
}
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
boolean[] issuerUniqueID = (values[7] == null)
@@ -331,7 +274,7 @@
);
}
- protected void getValues(Object object, Object[] values) {
+ @Override protected void getValues(Object object, Object[] values) {
TBSCertificate tbs = (TBSCertificate) object;
values[0] = ASN1Integer.fromIntValue(tbs.version);
values[1] = tbs.serialNumber.toByteArray();
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Time.java b/luni/src/main/java/org/apache/harmony/security/x509/Time.java
index b60711a..5576ac3 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Time.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Time.java
@@ -41,8 +41,7 @@
* }
* </pre>
*/
-public class Time {
-
+public final class Time {
private static final long JAN_01_2050 = 2524608000000L;
public static final ASN1Choice ASN1 = new ASN1Choice(new ASN1Type[] {
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Utils.java b/luni/src/main/java/org/apache/harmony/security/x509/Utils.java
index 99951a1..5e168c4 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Utils.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Utils.java
@@ -25,8 +25,8 @@
/**
* Text utils for processing DN string representations
*/
-
-public class Utils {
+public final class Utils {
+ private Utils() {}
/**
* Checks if the string is PrintableString (see X.680)
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Validity.java b/luni/src/main/java/org/apache/harmony/security/x509/Validity.java
index 5f5cbd2..708979e 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Validity.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Validity.java
@@ -42,19 +42,14 @@
* }
* </pre>
*/
-public class Validity {
- // the value of notBefore field of the structure
+public final class Validity {
+ /** the value of notBefore field of the structure */
private final Date notBefore;
- // the value of notAfter field of the structure
+ /** the value of notAfter field of the structure */
private final Date notAfter;
- // the ASN.1 encoded form of Validity
+ /** the ASN.1 encoded form of Validity */
private byte[] encoding;
- /**
- * TODO
- * @param notBefore: Date
- * @param notAfter: Date
- */
public Validity(Date notBefore, Date notAfter) {
this.notBefore = notBefore;
this.notAfter = notAfter;
@@ -62,7 +57,6 @@
/**
* Returns the value of notBefore field of the structure.
- * @return notBefore
*/
public Date getNotBefore() {
return notBefore;
@@ -70,7 +64,6 @@
/**
* Returns the value of notAfter field of the structure.
- * @return notAfter
*/
public Date getNotAfter() {
return notAfter;
@@ -78,7 +71,6 @@
/**
* Returns ASN.1 encoded form of this X.509 Validity value.
- * @return a byte array containing ASN.1 encode form.
*/
public byte[] getEncoded() {
if (encoding == null) {
@@ -93,15 +85,13 @@
public static final ASN1Sequence ASN1
= new ASN1Sequence(new ASN1Type[] {Time.ASN1, Time.ASN1 }) {
- protected Object getDecodedObject(BerInputStream in) {
+ @Override protected Object getDecodedObject(BerInputStream in) {
Object[] values = (Object[]) in.content;
return new Validity((Date) values[0], (Date) values[1]);
}
- protected void getValues(Object object, Object[] values) {
-
+ @Override protected void getValues(Object object, Object[] values) {
Validity validity = (Validity) object;
-
values[0] = validity.notBefore;
values[1] = validity.notAfter;
}
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/X509PublicKey.java b/luni/src/main/java/org/apache/harmony/security/x509/X509PublicKey.java
index 08b19d5..b08bd8a 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/X509PublicKey.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/X509PublicKey.java
@@ -19,12 +19,9 @@
import java.security.PublicKey;
-public class X509PublicKey implements PublicKey {
-
+public final class X509PublicKey implements PublicKey {
private final String algorithm;
-
private final byte[] encoded;
-
private final byte[] keyBytes;
public X509PublicKey(String algorithm, byte[] encoded, byte[] keyBytes) {
@@ -52,7 +49,6 @@
buf.append(", params unparsed, unparsed keybits = \n");
// TODO: implement compatible toString method()
// buf.append(Arrays.toString(keyBytes));
-
return buf.toString();
}
}
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 01b08f2..8e648a4 100644
--- a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
+++ b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
@@ -39,7 +39,6 @@
* Adapts SAX API to the Expat native XML parser. Not intended for reuse
* across documents.
*
- * @see org.apache.harmony.xml.ExpatPullParser
* @see org.apache.harmony.xml.ExpatReader
*/
class ExpatParser {
diff --git a/luni/src/main/java/org/apache/harmony/xml/ExpatPullParser.java b/luni/src/main/java/org/apache/harmony/xml/ExpatPullParser.java
deleted file mode 100644
index 2ddf464..0000000
--- a/luni/src/main/java/org/apache/harmony/xml/ExpatPullParser.java
+++ /dev/null
@@ -1,963 +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.xml;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import org.xml.sax.Attributes;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-/**
- * Fast, partial XmlPullParser implementation based upon Expat. Does not
- * support validation or {@code DOCTYPE} processing.
- */
-public class ExpatPullParser implements XmlPullParser {
- /**
- * This feature is identified by http://xmlpull.org/v1/doc/features.html#relaxed
- * If this feature is supported that means that XmlPull parser will be
- * lenient when checking XML well formedness.
- * NOTE: use it only if XML input is not well-formed and in general usage
- * if this feature is discouraged
- * NOTE: as there is no definition of what is relaxed XML parsing
- * therefore what parser will do completely depends on implementation used
- */
- public static final String FEATURE_RELAXED =
- "http://xmlpull.org/v1/doc/features.html#relaxed";
-
- private static final int BUFFER_SIZE = 8096;
-
- private static final String NOT_A_START_TAG = "This is not a start tag.";
-
- private Document document;
- private boolean processNamespaces = false;
- private boolean relaxed = false;
-
- public void setFeature(String name, boolean state)
- throws XmlPullParserException {
- if (name == null) {
- // Required by API.
- throw new IllegalArgumentException("Null feature name");
- }
-
- if (name.equals(FEATURE_PROCESS_NAMESPACES)) {
- processNamespaces = state;
- return;
- }
-
- if (name.equals(FEATURE_RELAXED)) {
- relaxed = true;
- return;
- }
-
- // You're free to turn these features off because we don't support them.
- if (!state && (name.equals(FEATURE_REPORT_NAMESPACE_ATTRIBUTES)
- || name.equals(FEATURE_PROCESS_DOCDECL)
- || name.equals(FEATURE_VALIDATION))) {
- return;
- }
-
- throw new XmlPullParserException("Unsupported feature: " + name);
- }
-
- public boolean getFeature(String name) {
- if (name == null) {
- // Required by API.
- throw new IllegalArgumentException("Null feature name");
- }
-
- // We always support namespaces, but no other features.
- return name.equals(FEATURE_PROCESS_NAMESPACES) && processNamespaces;
- }
-
- /**
- * Returns true if this parser processes namespaces.
- *
- * @see #setNamespaceProcessingEnabled(boolean)
- */
- public boolean isNamespaceProcessingEnabled() {
- return processNamespaces;
- }
-
- /**
- * Enables or disables namespace processing. Set to false by default.
- *
- * @see #isNamespaceProcessingEnabled()
- */
- public void setNamespaceProcessingEnabled(boolean processNamespaces) {
- this.processNamespaces = processNamespaces;
- }
-
- public void setProperty(String name, Object value)
- throws XmlPullParserException {
- if (name == null) {
- // Required by API.
- throw new IllegalArgumentException("Null feature name");
- }
-
- // We don't support any properties.
- throw new XmlPullParserException("Properties aren't supported.");
- }
-
- public Object getProperty(String name) {
- return null;
- }
-
- public void setInput(Reader in) throws XmlPullParserException {
- this.document = new CharDocument(in, processNamespaces);
- }
-
- public void setInput(InputStream in, String encodingName)
- throws XmlPullParserException {
- this.document = new ByteDocument(in, encodingName, processNamespaces);
- }
-
- public String getInputEncoding() {
- return this.document.getEncoding();
- }
-
- /**
- * Not supported.
- *
- * @throws UnsupportedOperationException always
- */
- public void defineEntityReplacementText(String entityName,
- String replacementText) throws XmlPullParserException {
- throw new UnsupportedOperationException();
- }
-
- public int getNamespaceCount(int depth) throws XmlPullParserException {
- return document.currentEvent.namespaceStack.countAt(depth);
- }
-
- public String getNamespacePrefix(int pos) throws XmlPullParserException {
- String prefix = document.currentEvent.namespaceStack.prefixAt(pos);
- @SuppressWarnings("StringEquality")
- boolean hasPrefix = prefix != "";
- return hasPrefix ? prefix : null;
- }
-
- public String getNamespaceUri(int pos) throws XmlPullParserException {
- return document.currentEvent.namespaceStack.uriAt(pos);
- }
-
- public String getNamespace(String prefix) {
- // In XmlPullParser API, null == default namespace.
- if (prefix == null) {
- // Internally, we use empty string instead of null.
- prefix = "";
- }
-
- return document.currentEvent.namespaceStack.uriFor(prefix);
- }
-
- public int getDepth() {
- return this.document.getDepth();
- }
-
- public String getPositionDescription() {
- return "line " + getLineNumber() + ", column " + getColumnNumber();
- }
-
- /**
- * Not supported.
- *
- * @return {@literal -1} always
- */
- public int getLineNumber() {
- // We would have to record the line number in each event.
- return -1;
- }
-
- /**
- * Not supported.
- *
- * @return {@literal -1} always
- */
- public int getColumnNumber() {
- // We would have to record the column number in each event.
- return -1;
- }
-
- public boolean isWhitespace() throws XmlPullParserException {
- if (getEventType() != TEXT) {
- throw new XmlPullParserException("Not on text.");
- }
-
- String text = getText();
-
- if (text.length() == 0) {
- return true;
- }
-
- int length = text.length();
- for (int i = 0; i < length; i++) {
- if (!Character.isWhitespace(text.charAt(i))) {
- return false;
- }
- }
-
- return true;
- }
-
- public String getText() {
- final StringBuilder builder = this.document.currentEvent.getText();
- return builder == null ? null : builder.toString();
- }
-
- public char[] getTextCharacters(int[] holderForStartAndLength) {
- final StringBuilder builder = this.document.currentEvent.getText();
-
- final int length = builder.length();
- char[] characters = new char[length];
- builder.getChars(0, length, characters, 0);
-
- holderForStartAndLength[0] = 0;
- holderForStartAndLength[1] = length;
-
- return characters;
- }
-
- public String getNamespace() {
- return this.document.currentEvent.getNamespace();
- }
-
- public String getName() {
- return this.document.currentEvent.getName();
- }
-
- /**
- * Not supported.
- *
- * @throws UnsupportedOperationException always
- */
- public String getPrefix() {
- throw new UnsupportedOperationException();
- }
-
- public boolean isEmptyElementTag() throws XmlPullParserException {
- return this.document.isCurrentElementEmpty();
- }
-
- public int getAttributeCount() {
- return this.document.currentEvent.getAttributeCount();
- }
-
- public String getAttributeNamespace(int index) {
- return this.document.currentEvent.getAttributeNamespace(index);
- }
-
- public String getAttributeName(int index) {
- return this.document.currentEvent.getAttributeName(index);
- }
-
- /**
- * Not supported.
- *
- * @throws UnsupportedOperationException always
- */
- public String getAttributePrefix(int index) {
- throw new UnsupportedOperationException();
- }
-
- public String getAttributeType(int index) {
- return "CDATA";
- }
-
- public boolean isAttributeDefault(int index) {
- return false;
- }
-
- public String getAttributeValue(int index) {
- return this.document.currentEvent.getAttributeValue(index);
- }
-
- public String getAttributeValue(String namespace, String name) {
- return this.document.currentEvent.getAttributeValue(namespace, name);
- }
-
- public int getEventType() throws XmlPullParserException {
- return this.document.currentEvent.getType();
- }
-
- public int next() throws XmlPullParserException, IOException {
- return this.document.dequeue();
- }
-
- /**
- * Not supported.
- *
- * @throws UnsupportedOperationException always
- */
- public int nextToken() throws XmlPullParserException, IOException {
- throw new UnsupportedOperationException();
- }
-
- public void require(int type, String namespace, String name)
- throws XmlPullParserException, IOException {
- if (type != getEventType()
- || (namespace != null && !namespace.equals(getNamespace()))
- || (name != null && !name.equals(getName()))) {
- throw new XmlPullParserException("expected "
- + TYPES[type] + getPositionDescription());
- }
- }
-
- public String nextText() throws XmlPullParserException, IOException {
- if (this.document.currentEvent.getType() != START_TAG)
- throw new XmlPullParserException("Not on start tag.");
-
- int next = this.document.dequeue();
- switch (next) {
- case TEXT: return getText();
- case END_TAG: return "";
- default: throw new XmlPullParserException(
- "Unexpected event type: " + TYPES[next]);
- }
- }
-
- public int nextTag() throws XmlPullParserException, IOException {
- int eventType = next();
- if (eventType == TEXT && isWhitespace()) {
- eventType = next();
- }
- if (eventType != START_TAG && eventType != END_TAG) {
- throw new XmlPullParserException(
- "Expected start or end tag", this, null);
- }
- return eventType;
- }
-
- /**
- * Immutable namespace stack. Pushing a new namespace on to the stack
- * only results in one object allocation. Most operations are O(N) where
- * N is the stack size. Accessing recently pushed namespaces, like those
- * for the current element, is significantly faster.
- */
- static class NamespaceStack {
-
- /** An empty stack. */
- static final NamespaceStack EMPTY = new NamespaceStack();
-
- private final NamespaceStack parent;
- private final String prefix;
- private final String uri;
- private final int index;
- private final int depth;
-
- /**
- * Constructs an actual namespace stack node. Internally, the nodes
- * and the stack are one in the same making for a very efficient
- * implementation. The user just sees an immutable stack and the
- * builder.
- */
- private NamespaceStack(NamespaceStack parent, String prefix,
- String uri, int depth) {
- this.parent = parent;
- this.prefix = prefix;
- this.uri = uri;
- this.index = parent.index + 1;
- this.depth = depth;
- }
-
- /**
- * Constructs a dummy node which only serves to point to the bottom
- * of the stack. Using an actual node instead of null simplifies the
- * code.
- */
- private NamespaceStack() {
- this.parent = null;
- this.prefix = null;
- this.uri = null;
-
- // This node has an index of -1 since the actual first node in the
- // stack has index 0.
- this.index = -1;
-
- // The actual first node will have a depth of 1.
- this.depth = 0;
- }
-
- String uriFor(String prefix) {
- for (NamespaceStack node = this; node.index >= 0;
- node = node.parent) {
- if (node.prefix.equals(prefix)) {
- return node.uri;
- }
- }
-
- // Not found.
- return null;
- }
-
- /**
- * Gets the prefix at the given index in the stack.
- */
- String prefixAt(int index) {
- return nodeAt(index).prefix;
- }
-
- /**
- * Gets the URI at the given index in the stack.
- */
- String uriAt(int index) {
- return nodeAt(index).uri;
- }
-
- private NamespaceStack nodeAt(int index) {
- if (index > this.index) {
- throw new IndexOutOfBoundsException("Index > size.");
- }
- if (index < 0) {
- throw new IndexOutOfBoundsException("Index < 0.");
- }
-
- NamespaceStack node = this;
- while (index != node.index) {
- node = node.parent;
- }
- return node;
- }
-
- /**
- * Gets the size of the stack at the given element depth.
- */
- int countAt(int depth) {
- if (depth > this.depth) {
- throw new IndexOutOfBoundsException("Depth > maximum.");
- }
- if (depth < 0) {
- throw new IndexOutOfBoundsException("Depth < 0.");
- }
-
- NamespaceStack node = this;
- while (depth < node.depth) {
- node = node.parent;
- }
- return node.index + 1;
- }
-
- /** Builds a NamespaceStack. */
- static class Builder {
-
- NamespaceStack top = EMPTY;
-
- /**
- * Pushes a namespace onto the stack.
- *
- * @param depth of the element upon which the namespace was
- * declared
- */
- void push(String prefix, String uri, int depth) {
- top = new NamespaceStack(top, prefix, uri, depth);
- }
-
- /**
- * Pops all namespaces from the given element depth.
- */
- void pop(int depth) {
- // Remove all nodes at the specified depth.
- while (top != null && top.depth == depth) {
- top = top.parent;
- }
- }
-
- /** Returns the current stack. */
- NamespaceStack build() {
- return top;
- }
- }
- }
-
- /**
- * Base class for events. Implements event chaining and defines event API
- * along with common implementations which can be overridden.
- */
- static abstract class Event {
-
- /** Element depth at the time of this event. */
- final int depth;
-
- /** The namespace stack at the time of this event. */
- final NamespaceStack namespaceStack;
-
- /** Next event in the queue. */
- Event next = null;
-
- Event(int depth, NamespaceStack namespaceStack) {
- this.depth = depth;
- this.namespaceStack = namespaceStack;
- }
-
- void setNext(Event next) {
- this.next = next;
- }
-
- Event getNext() {
- return next;
- }
-
- StringBuilder getText() {
- return null;
- }
-
- String getNamespace() {
- return null;
- }
-
- String getName() {
- return null;
- }
-
- int getAttributeCount() {
- return -1;
- }
-
- String getAttributeNamespace(int index) {
- throw new IndexOutOfBoundsException(NOT_A_START_TAG);
- }
-
- String getAttributeName(int index) {
- throw new IndexOutOfBoundsException(NOT_A_START_TAG);
- }
-
- String getAttributeValue(int index) {
- throw new IndexOutOfBoundsException(NOT_A_START_TAG);
- }
-
- abstract int getType();
-
- String getAttributeValue(String namespace, String name) {
- throw new IndexOutOfBoundsException(NOT_A_START_TAG);
- }
-
- public int getDepth() {
- return this.depth;
- }
- }
-
- static class StartDocumentEvent extends Event {
-
- public StartDocumentEvent() {
- super(0, NamespaceStack.EMPTY);
- }
-
- @Override
- int getType() {
- return START_DOCUMENT;
- }
- }
-
- static class StartTagEvent extends Event {
-
- final String name;
- final String namespace;
- final Attributes attributes;
- final boolean processNamespaces;
-
- StartTagEvent(String namespace,
- String name,
- ExpatParser expatParser,
- int depth,
- NamespaceStack namespaceStack,
- boolean processNamespaces) {
- super(depth, namespaceStack);
- this.namespace = namespace;
- this.name = name;
- this.attributes = expatParser.cloneAttributes();
- this.processNamespaces = processNamespaces;
- }
-
- @Override
- String getNamespace() {
- return namespace;
- }
-
- @Override
- String getName() {
- return name;
- }
-
- @Override
- int getAttributeCount() {
- return attributes.getLength();
- }
-
- @Override
- String getAttributeNamespace(int index) {
- return attributes.getURI(index);
- }
-
- @Override
- String getAttributeName(int index) {
- return processNamespaces ? attributes.getLocalName(index)
- : attributes.getQName(index);
- }
-
- @Override
- String getAttributeValue(int index) {
- return attributes.getValue(index);
- }
-
- @Override
- String getAttributeValue(String namespace, String name) {
- if (namespace == null) {
- namespace = "";
- }
-
- return attributes.getValue(namespace, name);
- }
-
- @Override
- int getType() {
- return START_TAG;
- }
- }
-
- static class EndTagEvent extends Event {
-
- final String namespace;
- final String localName;
-
- EndTagEvent(String namespace, String localName, int depth,
- NamespaceStack namespaceStack) {
- super(depth, namespaceStack);
- this.namespace = namespace;
- this.localName = localName;
- }
-
- @Override
- String getName() {
- return this.localName;
- }
-
- @Override
- String getNamespace() {
- return this.namespace;
- }
-
- @Override
- int getType() {
- return END_TAG;
- }
- }
-
- static class TextEvent extends Event {
-
- final StringBuilder builder;
-
- public TextEvent(int initialCapacity, int depth,
- NamespaceStack namespaceStack) {
- super(depth, namespaceStack);
- this.builder = new StringBuilder(initialCapacity);
- }
-
- @Override
- int getType() {
- return TEXT;
- }
-
- @Override
- StringBuilder getText() {
- return this.builder;
- }
-
- void append(char[] text, int start, int length) {
- builder.append(text, start, length);
- }
- }
-
- static class EndDocumentEvent extends Event {
-
- EndDocumentEvent() {
- super(0, NamespaceStack.EMPTY);
- }
-
- @Override
- Event getNext() {
- throw new IllegalStateException("End of document.");
- }
-
- @Override
- void setNext(Event next) {
- throw new IllegalStateException("End of document.");
- }
-
- @Override
- int getType() {
- return END_DOCUMENT;
- }
- }
-
- /**
- * Encapsulates the parsing context of the current document.
- */
- abstract class Document {
-
- final String encoding;
- final ExpatParser parser;
- final boolean processNamespaces;
-
- TextEvent textEvent = null;
- boolean finished = false;
-
- Document(String encoding, boolean processNamespaces) {
- this.encoding = encoding;
- this.processNamespaces = processNamespaces;
-
- ExpatReader xmlReader = new ExpatReader();
- xmlReader.setContentHandler(new SaxHandler());
-
- this.parser = new ExpatParser(
- encoding, xmlReader, processNamespaces, null, null);
- }
-
- /** Namespace stack builder. */
- NamespaceStack.Builder namespaceStackBuilder
- = new NamespaceStack.Builder();
-
- Event currentEvent = new StartDocumentEvent();
- Event last = currentEvent;
-
- /**
- * Sends some more XML to the parser.
- */
- void pump() throws IOException, XmlPullParserException {
- if (this.finished) {
- return;
- }
-
- int length = buffer();
-
- // End of document.
- if (length == -1) {
- this.finished = true;
- if (!relaxed) {
- try {
- parser.finish();
- } catch (SAXException e) {
- throw new XmlPullParserException(
- "Premature end of document.", ExpatPullParser.this, e);
- }
- }
- add(new EndDocumentEvent());
- return;
- }
-
- if (length == 0) {
- return; // TODO: can't happen?
- }
-
- flush(parser, length);
- }
-
- /**
- * Reads data into the buffer.
- *
- * @return the length of data buffered or {@code -1} if we've reached
- * the end of the data.
- */
- abstract int buffer() throws IOException;
-
- /**
- * Sends buffered data to the parser.
- *
- * @param parser the parser to flush to
- * @param length of data buffered
- */
- abstract void flush(ExpatParser parser, int length)
- throws XmlPullParserException;
-
- /**
- * Adds an event.
- */
- void add(Event event) {
- // Flush pre-exising text event if necessary.
- if (textEvent != null) {
- last.setNext(textEvent);
- last = textEvent;
- textEvent = null;
- }
-
- last.setNext(event);
- last = event;
- }
-
- /**
- * Moves to the next event in the queue.
- *
- * @return type of next event
- */
- int dequeue() throws XmlPullParserException, IOException {
- Event next;
-
- while ((next = currentEvent.getNext()) == null) {
- pump();
- }
-
- currentEvent.next = null;
- currentEvent = next;
-
- return currentEvent.getType();
- }
-
- String getEncoding() {
- return this.encoding;
- }
-
- int getDepth() {
- return currentEvent.getDepth();
- }
-
- /**
- * Returns true if we're on a start element and the next event is
- * its corresponding end element.
- *
- * @throws XmlPullParserException if we aren't on a start element
- */
- boolean isCurrentElementEmpty() throws XmlPullParserException {
- if (currentEvent.getType() != START_TAG) {
- throw new XmlPullParserException(NOT_A_START_TAG);
- }
-
- Event next;
-
- try {
- while ((next = currentEvent.getNext()) == null) {
- pump();
- }
- } catch (IOException ex) {
- throw new XmlPullParserException(ex.toString());
- }
-
- return next.getType() == END_TAG;
- }
-
- private class SaxHandler implements ContentHandler {
-
- int depth = 0;
-
- public void startPrefixMapping(String prefix, String uri)
- throws SAXException {
- // Depth + 1--we aren't actually in the element yet.
- namespaceStackBuilder.push(prefix, uri, depth + 1);
- }
-
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) {
- String name = processNamespaces ? localName : qName;
-
- add(new StartTagEvent(uri, name, parser, ++this.depth,
- namespaceStackBuilder.build(), processNamespaces));
- }
-
- public void endElement(String uri, String localName, String qName) {
- String name = processNamespaces ? localName : qName;
-
- int depth = this.depth--;
- add(new EndTagEvent(uri, name, depth,
- namespaceStackBuilder.build()));
- namespaceStackBuilder.pop(depth);
- }
-
- public void characters(char[] ch, int start, int length) {
- // Ignore empty strings.
- if (length == 0) {
- return;
- }
-
- // Start a new text event if necessary.
- if (textEvent == null) {
- textEvent = new TextEvent(length, this.depth,
- namespaceStackBuilder.build());
- }
-
- // Append to an existing text event.
- textEvent.append(ch, start, length);
- }
-
- public void setDocumentLocator(Locator locator) {}
- public void startDocument() throws SAXException {}
- public void endDocument() throws SAXException {}
- public void endPrefixMapping(String prefix) throws SAXException {}
- public void ignorableWhitespace(char[] ch, int start, int length)
- throws SAXException {}
- public void processingInstruction(String target, String data)
- throws SAXException {}
- public void skippedEntity(String name) throws SAXException {}
- }
- }
-
- class CharDocument extends Document {
-
- final char[] buffer = new char[BUFFER_SIZE / 2];
- final Reader in;
-
- CharDocument(Reader in, boolean processNamespaces) {
- super("UTF-16", processNamespaces);
- this.in = in;
- }
-
- @Override
- int buffer() throws IOException {
- return in.read(buffer);
- }
-
- @Override
- void flush(ExpatParser parser, int length)
- throws XmlPullParserException {
- try {
- parser.append(buffer, 0, length);
- } catch (SAXException e) {
- throw new XmlPullParserException(
- "Error parsing document.", ExpatPullParser.this, e);
- }
- }
- }
-
- class ByteDocument extends Document {
-
- final byte[] buffer = new byte[BUFFER_SIZE];
- final InputStream in;
-
- ByteDocument(InputStream in, String encoding,
- boolean processNamespaces) {
- super(encoding, processNamespaces);
- this.in = in;
- }
-
- @Override
- int buffer() throws IOException {
- return in.read(buffer);
- }
-
- @Override
- void flush(ExpatParser parser, int length)
- throws XmlPullParserException {
- try {
- parser.append(buffer, 0, length);
- } catch (SAXException e) {
- throw new XmlPullParserException(
- "Error parsing document.", ExpatPullParser.this, e);
- }
- }
- }
-}
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
index dbd9519..9bc28a0 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
@@ -23,7 +23,7 @@
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
-import java.util.Vector;
+import java.util.ArrayList;
/**
* Represents server/client certificate message
@@ -50,8 +50,7 @@
* @param length
* @throws IOException
*/
- public CertificateMessage(HandshakeIODataStream in, int length)
- throws IOException {
+ public CertificateMessage(HandshakeIODataStream in, int length) throws IOException {
int l = in.readUint24(); // total_length
if (l == 0) { // message contais no certificates
if (length != 3) { // no more bytes after total_length
@@ -70,30 +69,25 @@
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
return;
}
- Vector<Certificate> certs_vector = new Vector<Certificate>();
+ ArrayList<X509Certificate> certsList = new ArrayList<X509Certificate>();
int size = 0;
int enc_size = 0;
while (l > 0) {
size = in.readUint24();
l -= 3;
try {
- certs_vector.add(cf.generateCertificate(in));
+ certsList.add((X509Certificate) cf.generateCertificate(in));
} catch (CertificateException e) {
fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR", e);
}
l -= size;
enc_size += size;
}
- certs = new X509Certificate[certs_vector.size()];
- for (int i = 0; i < certs.length; i++) {
- certs[i] = (X509Certificate) certs_vector.elementAt(i);
- }
+ certs = certsList.toArray(new X509Certificate[certsList.size()]);
this.length = 3 + 3 * certs.length + enc_size;
if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateMessage");
+ fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect CertificateMessage");
}
-
}
/**
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
index 49f63bf..401fe39 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
@@ -19,7 +19,7 @@
import java.io.IOException;
import java.security.cert.X509Certificate;
-import java.util.Vector;
+import java.util.ArrayList;
import javax.security.auth.x500.X500Principal;
/**
@@ -85,31 +85,25 @@
* @param length
* @throws IOException
*/
- public CertificateRequest(HandshakeIODataStream in, int length)
- throws IOException {
+ public CertificateRequest(HandshakeIODataStream in, int length) throws IOException {
int size = in.readUint8();
certificate_types = new byte[size];
in.read(certificate_types, 0, size);
size = in.readUint16();
int totalPrincipalsLength = 0;
int principalLength = 0;
- Vector<X500Principal> principals = new Vector<X500Principal>();
+ ArrayList<X500Principal> principals = new ArrayList<X500Principal>();
while (totalPrincipalsLength < size) {
principalLength = in.readUint16(); // encoded X500Principal size
principals.add(new X500Principal(in));
totalPrincipalsLength += 2;
totalPrincipalsLength += principalLength;
}
- certificate_authorities = new X500Principal[principals.size()];
- for (int i = 0; i < certificate_authorities.length; i++) {
- certificate_authorities[i] = principals.elementAt(i);
- }
+ certificate_authorities = principals.toArray(new X500Principal[principals.size()]);
this.length = 3 + certificate_types.length + totalPrincipalsLength;
if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateRequest");
+ fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect CertificateRequest");
}
-
}
/**
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
index a09914e..1f1d789 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
@@ -86,13 +86,11 @@
} else if (parameters.getEnableSessionCreation()){
isResuming = false;
session = new SSLSessionImpl(parameters.getSecureRandom());
- // BEGIN android-added
if (engineOwner != null) {
session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
} else {
session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
}
- // END android-added
session.protocol = ProtocolVersion.getLatestVersion(parameters.getEnabledProtocols());
recordProtocol.setVersion(session.protocol.version);
} else {
@@ -109,13 +107,11 @@
if (parameters.getEnableSessionCreation()){
isResuming = false;
session = new SSLSessionImpl(parameters.getSecureRandom());
- // BEGIN android-added
if (engineOwner != null) {
session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
} else {
session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
}
- // END android-added
session.protocol = ProtocolVersion.getLatestVersion(parameters.getEnabledProtocols());
recordProtocol.setVersion(session.protocol.version);
startSession();
@@ -133,9 +129,7 @@
if (isResuming) {
cipher_suites = new CipherSuite[] { session.cipherSuite };
} else {
- // BEGIN android-changed
cipher_suites = parameters.getEnabledCipherSuitesMember();
- // END android-changed
}
clientHello = new ClientHello(parameters.getSecureRandom(),
session.protocol.version, session.id, cipher_suites);
@@ -215,9 +209,7 @@
}
//check cipher_suite
- // BEGIN android-changed
CipherSuite[] enabledSuites = parameters.getEnabledCipherSuitesMember();
- // END android-changed
find: {
for (int i = 0; i < enabledSuites.length; i++) {
if (serverHello.cipher_suite.equals(enabledSuites[i])) {
@@ -304,9 +296,7 @@
serverFinished = new Finished(io_stream, length);
verifyFinished(serverFinished.getData());
session.lastAccessedTime = System.currentTimeMillis();
- // BEGIN android-added
session.context = parameters.getClientSessionContext();
- // END android-added
parameters.getClientSessionContext().putSession(session);
if (isResuming) {
sendChangeCipherSpec();
@@ -578,7 +568,6 @@
return null; // starts new session
}
- // BEGIN android-changed
ClientSessionContext context = parameters.getClientSessionContext();
SSLSessionImpl session
= (SSLSessionImpl) context.getSession(host, port);
@@ -586,7 +575,6 @@
session = (SSLSessionImpl) session.clone();
}
return session;
- // END android-changed
}
}
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
index 97ededd..9f4c4db 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
@@ -39,6 +39,10 @@
super(10, 0);
}
+ public int size() {
+ return sessionsByHostAndPort.size();
+ }
+
public void setPersistentCache(SSLClientSessionCache persistentCache) {
this.persistentCache = persistentCache;
}
@@ -94,7 +98,7 @@
}
@Override
- void putSession(SSLSession session) {
+ public void putSession(SSLSession session) {
super.putSession(session);
String host = session.getPeerHost();
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
index 9859be7..c110275 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
@@ -58,6 +58,5 @@
handshaker.delegatedTaskErr = e;
}
}
-
}
}
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 9558ceb..822d829 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
@@ -39,7 +39,7 @@
*/
public class FileClientSessionCache {
- static final int MAX_SIZE = 12; // ~72k
+ public static final int MAX_SIZE = 12; // ~72k
static final java.util.logging.Logger logger
= java.util.logging.Logger.getLogger(
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
index 720e7a6..ee9f667 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
@@ -21,6 +21,7 @@
import java.io.PrintStream;
import java.security.MessageDigest;
import java.util.Arrays;
+import java.util.Locale;
import javax.net.ssl.SSLHandshakeException;
/**
@@ -367,32 +368,6 @@
return res;
}
- // ---------------------- Debud functionality -------------------------
-
- protected void printContent(PrintStream outstream) {
- int perLine = 20;
- String prefix = " ";
- String delimiter = "";
-
- for (int i=write_pos_beg; i<write_pos; i++) {
- String tail = Integer.toHexString(
- 0x00ff & buffer[i]).toUpperCase();
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- outstream.print(prefix + tail + delimiter);
-
- if (((i-write_pos_beg+1)%10) == 0) {
- outstream.print(" ");
- }
-
- if (((i-write_pos_beg+1)%perLine) == 0) {
- outstream.println();
- }
- }
- outstream.println();
- }
-
// ---------------------- Message Digest Functionality ----------------
/**
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
index bd83989..f8016f1 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
@@ -43,22 +43,22 @@
/**
* Handshake status NEED_UNWRAP - HandshakeProtocol needs to receive data
*/
- public final static int NEED_UNWRAP = 1;
+ public static final int NEED_UNWRAP = 1;
/**
* Handshake status NOT_HANDSHAKING - is not currently handshaking
*/
- public final static int NOT_HANDSHAKING = 2;
+ public static final int NOT_HANDSHAKING = 2;
/**
* Handshake status FINISHED - HandshakeProtocol has just finished
*/
- public final static int FINISHED = 3;
+ public static final int FINISHED = 3;
/**
* Handshake status NEED_TASK - HandshakeProtocol needs the results of delegated task
*/
- public final static int NEED_TASK = 4;
+ public static final int NEED_TASK = 4;
/**
* Current handshake status
@@ -518,8 +518,8 @@
}
/**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
+ * Shuts down the protocol. It will be impossible to use the instance
+ * after calling this method.
*/
protected void shutdown() {
clearMessages();
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
index 62b6560..84507bd 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
@@ -17,8 +17,6 @@
package org.apache.harmony.xnet.provider.jsse;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.security.Provider;
/**
@@ -108,17 +106,13 @@
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- put("SSLContext.SSL", SSLContextImpl.class.getName());
- put("SSLContext.SSLv3", SSLContextImpl.class.getName());
- put("SSLContext.TLS", SSLContextImpl.class.getName());
- put("SSLContext.TLSv1", SSLContextImpl.class.getName());
- put("KeyManagerFactory.X509", KeyManagerFactoryImpl.class.getName());
- put("TrustManagerFactory.X509", TrustManagerFactoryImpl.class.getName());
- return null;
- }
- });
+ put("SSLContext.SSL", SSLContextImpl.class.getName());
+ put("SSLContext.SSLv3", SSLContextImpl.class.getName());
+ put("SSLContext.TLS", SSLContextImpl.class.getName());
+ put("SSLContext.TLSv1", SSLContextImpl.class.getName());
+
+ put("KeyManagerFactory.X509", KeyManagerFactoryImpl.class.getName());
+ put("TrustManagerFactory.X509", TrustManagerFactoryImpl.class.getName());
}
}
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
index 2dcc252..261f3c7 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
@@ -20,7 +20,6 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
@@ -61,15 +60,9 @@
}
} else {
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- String keyStoreName = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System.getProperty("javax.net.ssl.keyStore");
- }
- });
+ String keyStoreName = System.getProperty("javax.net.ssl.keyStore");
String keyStorePwd = null;
- if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE")
- || keyStoreName.length() == 0) {
+ if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") || keyStoreName.isEmpty()) {
try {
keyStore.load(null, null);
} catch (IOException e) {
@@ -78,22 +71,14 @@
throw new KeyStoreException(e);
}
} else {
- keyStorePwd = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.keyStorePassword");
- }
- });
+ keyStorePwd = System.getProperty("javax.net.ssl.keyStorePassword");
if (keyStorePwd == null) {
pwd = EmptyArray.CHAR;
} else {
pwd = keyStorePwd.toCharArray();
}
try {
- keyStore.load(new FileInputStream(new File(keyStoreName)),
- pwd);
-
+ keyStore.load(new FileInputStream(new File(keyStoreName)), pwd);
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
index 6955ab1..830fd77 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
@@ -26,11 +26,12 @@
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
-import java.util.Vector;
+import java.util.Locale;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.security.auth.x500.X500Principal;
@@ -95,11 +96,9 @@
}
public X509Certificate[] getCertificateChain(String alias) {
- // BEGIN android-changed
if (alias == null) {
return null;
}
- // END android-changed
if (hash.containsKey(alias)) {
Certificate[] certs = hash.get(alias).getCertificateChain();
if (certs[0] instanceof X509Certificate) {
@@ -123,11 +122,9 @@
}
public PrivateKey getPrivateKey(String alias) {
- // BEGIN android-changed
if (alias == null) {
return null;
}
- // END android-changed
if (hash.containsKey(alias)) {
return hash.get(alias).getPrivateKey();
}
@@ -151,7 +148,7 @@
return null;
}
List<Principal> issuersList = (issuers == null) ? null : Arrays.asList(issuers);
- Vector<String> found = new Vector<String>();
+ ArrayList<String> found = new ArrayList<String>();
for (Enumeration<String> aliases = hash.keys(); aliases.hasMoreElements();) {
final String alias = aliases.nextElement();
final KeyStore.PrivateKeyEntry entry = hash.get(alias);
@@ -159,7 +156,7 @@
final Certificate cert = chain[0];
final String certKeyAlg = cert.getPublicKey().getAlgorithm();
final String certSigAlg = (cert instanceof X509Certificate
- ? ((X509Certificate) cert).getSigAlgName().toUpperCase()
+ ? ((X509Certificate) cert).getSigAlgName().toUpperCase(Locale.US)
: null);
for (String keyAlgorithm : keyTypes) {
if (keyAlgorithm == null) {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
index d4a0e39..a2688e2 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
@@ -18,6 +18,7 @@
package org.apache.harmony.xnet.provider.jsse;
import java.io.PrintStream;
+import java.util.Locale;
import java.security.AccessController;
import java.security.PrivilegedAction;
import libcore.util.EmptyArray;
@@ -67,32 +68,24 @@
printAsHex(16, " ", "", data, offset, len);
}
- public void printAsHex(int perLine,
- String prefix,
- String delimiter,
- byte[] data) {
+ public void printAsHex(int perLine, String prefix, String delimiter, byte[] data) {
printAsHex(perLine, prefix, delimiter, data, 0, data.length);
}
- public void printAsHex(int perLine,
- String prefix,
- String delimiter,
+ public void printAsHex(int perLine, String prefix, String delimiter,
byte[] data, int offset, int len) {
- String line = "";
- for (int i=0; i<len; i++) {
- String tail =
- Integer.toHexString(0x00ff & data[i+offset]).toUpperCase();
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- line += prefix + tail + delimiter;
+ StringBuilder line = new StringBuilder();
+ for (int i = 0; i < len; i++) {
+ line.append(prefix);
+ line.append(Byte.toHexString(data[i+offset], false));
+ line.append(delimiter);
if (((i+1)%perLine) == 0) {
- super.println(line);
- line = "";
+ super.println(line.toString());
+ line = new StringBuilder();
}
}
- super.println(line);
+ super.println(line.toString());
}
}
@@ -100,12 +93,7 @@
static {
try {
- names = AccessController
- .doPrivileged(new PrivilegedAction<String[]>() {
- public String[] run() {
- return System.getProperty("jsse", "").split(",");
- }
- });
+ names = System.getProperty("jsse", "").split(",");
} catch (Exception e) {
names = EmptyArray.STRING;
}
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
index 4ba1247..42d7f0e 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
@@ -23,8 +23,8 @@
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.Map;
-import java.util.Vector;
import java.util.Set;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLPermission;
@@ -363,18 +363,11 @@
/**
* Returns the context to which the actual SSL session is bound. A SSL
* context consists of (1) a possible delegate, (2) a provider and (3) a
- * protocol. If the security manager is activated and one tries to access
- * the SSL context an exception may be thrown if a
- * <code>SSLPermission("getSSLSessionContext")</code>
- * permission is not set.
+ * protocol.
* @return the SSL context used for this session, or null if it is
* unavailable.
*/
public SSLSessionContext getSessionContext() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SSLPermission("getSSLSessionContext"));
- }
return sessionContext;
}
@@ -433,7 +426,7 @@
* bound to this SSL session.
*/
public String[] getValueNames() {
- Vector<String> v = new Vector<String>();
+ ArrayList<String> v = new ArrayList<String>();
AccessControlContext current = AccessController.getContext();
Set<Map.Entry<String, Object>> set = values.entrySet();
for (Map.Entry<String, Object> o : set) {
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 d84e28a..2f0cbae 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
@@ -100,9 +100,7 @@
*/
private int timeoutMilliseconds = 0;
- // BEGIN android-added
private int handshakeTimeoutMilliseconds = -1; // -1 = same as timeout; 0 = infinite
- // END android-added
private String wrappedHost;
private int wrappedPort;
@@ -472,13 +470,11 @@
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 {
@@ -524,12 +520,10 @@
+ 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) {
@@ -1184,7 +1178,6 @@
return timeoutMilliseconds;
}
- // BEGIN android-added
/**
* Set the handshake timeout on this socket. This timeout is specified in
* milliseconds and will be used only during the handshake process.
@@ -1194,7 +1187,6 @@
public void setHandshakeTimeout(int timeoutMilliseconds) throws SocketException {
this.handshakeTimeoutMilliseconds = timeoutMilliseconds;
}
- // END android-added
/**
* Closes the SSL socket. Once closed, a socket is not available for further
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
index e09230b..0e1e130 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
@@ -28,11 +28,6 @@
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
-// BEGIN android-note
-// Modified heavily during SSLSessionContext refactoring. Added support for
-// persistent session caches.
-// END android-note
-
/**
* Implementation of SSLContext service provider interface.
*/
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 2e62e44..2a6c5d6 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
@@ -78,11 +78,9 @@
* Reads and returns uint64 value.
*/
public long readUint64() throws IOException {
- // BEGIN android-changed
long hi = readUint32();
long lo = readUint32();
return (hi << 32) | lo;
- // END android-changed
}
/**
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 405e5dd..fdad872 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
@@ -33,7 +33,7 @@
import javax.net.ssl.X509TrustManager;
/**
- * The instances of this class incapsulate all the info
+ * The instances of this class encapsulate all the info
* about enabled cipher suites and protocols,
* as well as the information about client/server mode of
* ssl socket, whether it require/want client authentication or not,
@@ -53,12 +53,10 @@
// client session context contains the set of reusable
// client-side SSL sessions
-// BEGIN android-changed
private final ClientSessionContext clientSessionContext;
// server session context contains the set of reusable
// server-side SSL sessions
private final ServerSessionContext serverSessionContext;
-// END android-changed
// source of authentication keys
private X509KeyManager keyManager;
// source of authentication trust decisions
@@ -67,9 +65,7 @@
private SecureRandom secureRandom;
// cipher suites available for SSL connection
- // BEGIN android-changed
private CipherSuite[] enabledCipherSuites;
- // END android-changed
// string representations of available cipher suites
private String[] enabledCipherSuiteNames = null;
@@ -85,14 +81,12 @@
// if the peer with this parameters allowed to cteate new SSL session
private boolean enable_session_creation = true;
-// BEGIN android-changed
protected CipherSuite[] getEnabledCipherSuitesMember() {
if (enabledCipherSuites == null) {
this.enabledCipherSuites = CipherSuite.DEFAULT_CIPHER_SUITES;
}
return enabledCipherSuites;
}
-// END android-changed
/**
* Initializes the parameters. Naturally this constructor is used
@@ -103,13 +97,11 @@
* SecureRandom)} for more information
*/
protected SSLParametersImpl(KeyManager[] kms, TrustManager[] tms,
-// BEGIN android-changed
SecureRandom sr, ClientSessionContext clientSessionContext,
ServerSessionContext serverSessionContext)
throws KeyManagementException {
this.serverSessionContext = serverSessionContext;
this.clientSessionContext = clientSessionContext;
-// END android-changed
// It's not described by the spec of SSLContext what should happen
// if the arrays of length 0 are specified. This implementation
@@ -150,7 +142,7 @@
// null, we don't replace it by a new instance. The native code below
// then directly accesses /dev/urandom. Not the most elegant solution,
// but faster than going through the SecureRandom object.
- secureRandom = sr;
+ secureRandom = sr;
// END android-added
}
@@ -170,18 +162,14 @@
/**
* @return server session context
*/
-// BEGIN android-changed
protected ServerSessionContext getServerSessionContext() {
-// END android-changed
return serverSessionContext;
}
/**
* @return client session context
*/
-// BEGIN android-changed
protected ClientSessionContext getClientSessionContext() {
-// END android-changed
return clientSessionContext;
}
@@ -215,23 +203,19 @@
return secureRandom;
}
- // BEGIN android-added
/**
* @return the secure random member reference, even it is null
*/
protected SecureRandom getSecureRandomMember() {
return secureRandom;
}
- // END android-added
/**
* @return the names of enabled cipher suites
*/
protected String[] getEnabledCipherSuites() {
if (enabledCipherSuiteNames == null) {
- // BEGIN android-added
CipherSuite[] enabledCipherSuites = getEnabledCipherSuitesMember();
- // END android-added
enabledCipherSuiteNames = new String[enabledCipherSuites.length];
for (int i = 0; i< enabledCipherSuites.length; i++) {
enabledCipherSuiteNames[i] = enabledCipherSuites[i].getName();
@@ -364,13 +348,11 @@
*/
@Override
protected Object clone() {
-// BEGIN android-changed
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
-// END android-changed
}
private static X509KeyManager getDefaultKeyManager() {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSocketImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSocketImpl.java
index f54101f..4999ea4 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSocketImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSocketImpl.java
@@ -249,16 +249,6 @@
SSLSocketImpl s = new SSLSocketImpl(
(SSLParametersImpl) sslParameters.clone());
implAccept(s);
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- try {
- sm.checkAccept(s.getInetAddress().getHostAddress(),
- s.getPort());
- } catch(SecurityException e) {
- s.close();
- throw e;
- }
- }
s.init();
if (logger != null) {
logger.println("SSLServerSocketImpl: accepted, initialized");
@@ -276,4 +266,3 @@
// -----------------------------------------------------------------
}
-
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
index d88ee95..65b8fce 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
@@ -24,9 +24,9 @@
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
-import java.util.Vector;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLPermission;
import javax.net.ssl.SSLSession;
@@ -121,9 +121,7 @@
/**
* Context of the session
*/
-// BEGIN android-changed
SSLSessionContext context;
-// END android-changed
/**
* certificates were sent to the peer
@@ -281,10 +279,6 @@
}
public SSLSessionContext getSessionContext() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SSLPermission("getSSLSessionContext"));
- }
return context;
}
@@ -296,7 +290,7 @@
}
public String[] getValueNames() {
- final Vector<String> v = new Vector<String>();
+ final ArrayList<String> v = new ArrayList<String>();
final AccessControlContext currAcc = AccessController.getContext();
for (ValueKey key : values.keySet()) {
if (Objects.equal(currAcc, key.acc)) {
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
index f9df058..7961cdc 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
@@ -264,9 +264,7 @@
clientFinished = new Finished(io_stream, length);
verifyFinished(clientFinished.getData());
- // BEGIN android-added
session.context = parameters.getServerSessionContext();
- // END android-added
parameters.getServerSessionContext().putSession(session);
if (!isResuming) {
sendChangeCipherSpec();
@@ -402,13 +400,11 @@
"SSL Session may not be created");
}
session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
- // BEGIN android-added
if (engineOwner != null) {
session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
} else {
session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
}
- // END android-added
}
recordProtocol.setVersion(clientHello.client_version);
@@ -635,13 +631,11 @@
if (!clientSuite.supported) {
continue;
}
- // BEGIN android-changed
for (CipherSuite enabledCipherSuite : parameters.getEnabledCipherSuitesMember()) {
if (clientSuite.equals(enabledCipherSuite)) {
return clientSuite;
}
}
- // END android-changed
}
return null;
}
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 a0816ae..fef4f5f 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
@@ -22,7 +22,6 @@
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
-import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
@@ -51,27 +50,14 @@
if (ks != null) {
keyStore = ks;
} else {
- // BEGIN android-added
if (System.getProperty("javax.net.ssl.trustStore") == null) {
- String file = System.getProperty("java.home")
- + java.io.File.separator + "etc" + java.io.File.separator
- + "security" + java.io.File.separator
- + "cacerts.bks";
-
- System.setProperty("javax.net.ssl.trustStore", file);
+ String filename = System.getProperty("java.home") + "/etc/security/cacerts.bks";
+ System.setProperty("javax.net.ssl.trustStore", filename);
}
- // END android-added
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- String keyStoreName = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.trustStore");
- }
- });
+ String keyStoreName = System.getProperty("javax.net.ssl.trustStore");
String keyStorePwd = null;
- if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE")
- || keyStoreName.length() == 0) {
+ if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") || keyStoreName.isEmpty()) {
try {
keyStore.load(null, null);
} catch (IOException e) {
@@ -82,13 +68,7 @@
throw new KeyStoreException(e);
}
} else {
- keyStorePwd = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.trustStorePassword");
- }
- });
+ keyStorePwd = System.getProperty("javax.net.ssl.trustStorePassword");
char[] pwd;
if (keyStorePwd == null) {
pwd = EmptyArray.CHAR;
diff --git a/luni/src/main/java/org/xml/sax/ext/Attributes2Impl.java b/luni/src/main/java/org/xml/sax/ext/Attributes2Impl.java
index 3b3b6d9..52fa1e5 100644
--- a/luni/src/main/java/org/xml/sax/ext/Attributes2Impl.java
+++ b/luni/src/main/java/org/xml/sax/ext/Attributes2Impl.java
@@ -37,18 +37,16 @@
*/
public class Attributes2Impl extends AttributesImpl implements Attributes2
{
- private boolean declared [];
- private boolean specified [];
+ private boolean[] declared;
+ private boolean[] specified;
/**
* Construct a new, empty Attributes2Impl object.
*/
public Attributes2Impl () {
- // BEGIN android-added
declared = EmptyArray.BOOLEAN;
specified = EmptyArray.BOOLEAN;
- // END android-added
}
@@ -246,12 +244,8 @@
int length = getLength ();
- // BEGIN android-changed
if (length > specified.length) {
- // END android-changed
- boolean newFlags [];
-
- newFlags = new boolean [length];
+ boolean[] newFlags = new boolean [length];
System.arraycopy (declared, 0, newFlags, 0, declared.length);
declared = newFlags;
diff --git a/luni/src/main/java/org/xml/sax/helpers/AttributeListImpl.java b/luni/src/main/java/org/xml/sax/helpers/AttributeListImpl.java
index 5b94743..1ae19da 100644
--- a/luni/src/main/java/org/xml/sax/helpers/AttributeListImpl.java
+++ b/luni/src/main/java/org/xml/sax/helpers/AttributeListImpl.java
@@ -5,7 +5,7 @@
package org.xml.sax.helpers;
-import java.util.Vector;
+import java.util.ArrayList;
import org.xml.sax.AttributeList;
@@ -136,11 +136,10 @@
* @see #removeAttribute
* @see org.xml.sax.DocumentHandler#startElement
*/
- public void addAttribute (String name, String type, String value)
- {
- names.addElement(name);
- types.addElement(type);
- values.addElement(value);
+ public void addAttribute(String name, String type, String value) {
+ names.add(name);
+ types.add(type);
+ values.add(value);
}
@@ -158,15 +157,13 @@
* @param name The attribute name.
* @see #addAttribute
*/
- public void removeAttribute (String name)
- {
- int i = names.indexOf(name);
-
- if (i >= 0) {
- names.removeElementAt(i);
- types.removeElementAt(i);
- values.removeElementAt(i);
- }
+ public void removeAttribute(String name) {
+ int i = names.indexOf(name);
+ if (i != -1) {
+ names.remove(i);
+ types.remove(i);
+ values.remove(i);
+ }
}
@@ -180,11 +177,10 @@
*
* @see org.xml.sax.DocumentHandler#startElement
*/
- public void clear ()
- {
- names.removeAllElements();
- types.removeAllElements();
- values.removeAllElements();
+ public void clear() {
+ names.clear();
+ types.clear();
+ values.clear();
}
@@ -200,9 +196,8 @@
* @return The number of attributes in the list.
* @see org.xml.sax.AttributeList#getLength
*/
- public int getLength ()
- {
- return names.size();
+ public int getLength() {
+ return names.size();
}
@@ -214,16 +209,11 @@
* is no attribute at that position.
* @see org.xml.sax.AttributeList#getName(int)
*/
- public String getName (int i)
- {
- if (i < 0) {
- return null;
- }
- try {
- return (String)names.elementAt(i);
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- }
+ public String getName(int i) {
+ if (i < 0 || i >= names.size()) {
+ return null;
+ }
+ return names.get(i);
}
@@ -237,16 +227,11 @@
* that position.
* @see org.xml.sax.AttributeList#getType(int)
*/
- public String getType (int i)
- {
- if (i < 0) {
- return null;
- }
- try {
- return (String)types.elementAt(i);
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- }
+ public String getType(int i) {
+ if (i < 0 || i >= types.size()) {
+ return null;
+ }
+ return types.get(i);
}
@@ -258,16 +243,11 @@
* there is no attribute at that position.
* @see org.xml.sax.AttributeList#getValue(int)
*/
- public String getValue (int i)
- {
- if (i < 0) {
- return null;
- }
- try {
- return (String)values.elementAt(i);
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- }
+ public String getValue(int i) {
+ if (i < 0 || i >= values.size()) {
+ return null;
+ }
+ return values.get(i);
}
@@ -280,9 +260,8 @@
* read).
* @see org.xml.sax.AttributeList#getType(java.lang.String)
*/
- public String getType (String name)
- {
- return getType(names.indexOf(name));
+ public String getType(String name) {
+ return getType(names.indexOf(name));
}
@@ -294,9 +273,8 @@
* exist.
* @see org.xml.sax.AttributeList#getValue(java.lang.String)
*/
- public String getValue (String name)
- {
- return getValue(names.indexOf(name));
+ public String getValue(String name) {
+ return getValue(names.indexOf(name));
}
@@ -305,9 +283,9 @@
// Internal state.
////////////////////////////////////////////////////////////////////
- Vector names = new Vector();
- Vector types = new Vector();
- Vector values = new Vector();
+ private ArrayList<String> names = new ArrayList<String>();
+ private ArrayList<String> types = new ArrayList<String>();
+ private ArrayList<String> values = new ArrayList<String>();
}
diff --git a/luni/src/main/java/org/xml/sax/helpers/NamespaceSupport.java b/luni/src/main/java/org/xml/sax/helpers/NamespaceSupport.java
index bff22b0..5f96797 100644
--- a/luni/src/main/java/org/xml/sax/helpers/NamespaceSupport.java
+++ b/luni/src/main/java/org/xml/sax/helpers/NamespaceSupport.java
@@ -6,11 +6,11 @@
package org.xml.sax.helpers;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.EmptyStackException;
import java.util.Enumeration;
import java.util.Hashtable;
-import java.util.Vector;
-
/**
* Encapsulate Namespace logic for use by applications using SAX,
@@ -86,7 +86,7 @@
* <p>This is the Namespace URI that is automatically mapped
* to the "xml" prefix.</p>
*/
- public final static String XMLNS =
+ public static final String XMLNS =
"http://www.w3.org/XML/1998/namespace";
@@ -106,15 +106,14 @@
* @see #setNamespaceDeclUris
* @see #isNamespaceDeclUris
*/
- public final static String NSDECL =
+ public static final String NSDECL =
"http://www.w3.org/xmlns/2000/";
/**
* An empty enumeration.
*/
- private final static Enumeration EMPTY_ENUMERATION =
- new Vector().elements();
+ private static final Enumeration EMPTY_ENUMERATION = Collections.enumeration(Collections.emptyList());
////////////////////////////////////////////////////////////////////
@@ -442,17 +441,16 @@
* @see #getDeclaredPrefixes
* @see #getURI
*/
- public Enumeration getPrefixes (String uri)
- {
- Vector prefixes = new Vector();
- Enumeration allPrefixes = getPrefixes();
- while (allPrefixes.hasMoreElements()) {
- String prefix = (String)allPrefixes.nextElement();
- if (uri.equals(getURI(prefix))) {
- prefixes.addElement(prefix);
+ public Enumeration getPrefixes(String uri) {
+ ArrayList<String> prefixes = new ArrayList<String>();
+ Enumeration allPrefixes = getPrefixes();
+ while (allPrefixes.hasMoreElements()) {
+ String prefix = (String) allPrefixes.nextElement();
+ if (uri.equals(getURI(prefix))) {
+ prefixes.add(prefix);
+ }
}
- }
- return prefixes.elements();
+ return Collections.enumeration(prefixes);
}
@@ -596,32 +594,31 @@
* @param uri The associated Namespace URI.
* @see org.xml.sax.helpers.NamespaceSupport#declarePrefix
*/
- void declarePrefix (String prefix, String uri)
- {
- // Lazy processing...
- if (!declsOK)
- throw new IllegalStateException (
- "can't declare any more prefixes in this context");
+ void declarePrefix(String prefix, String uri) {
+ // Lazy processing...
+ if (!declsOK) {
+ throw new IllegalStateException ("can't declare any more prefixes in this context");
+ }
if (!declSeen) {
- copyTables();
+ copyTables();
}
if (declarations == null) {
- declarations = new Vector();
+ declarations = new ArrayList<String>();
}
prefix = prefix.intern();
uri = uri.intern();
if ("".equals(prefix)) {
- if ("".equals(uri)) {
- defaultNS = null;
+ if ("".equals(uri)) {
+ defaultNS = null;
+ } else {
+ defaultNS = uri;
+ }
} else {
- defaultNS = uri;
+ prefixTable.put(prefix, uri);
+ uriTable.put(uri, prefix); // may wipe out another prefix
}
- } else {
- prefixTable.put(prefix, uri);
- uriTable.put(uri, prefix); // may wipe out another prefix
- }
- declarations.addElement(prefix);
+ declarations.add(prefix);
}
@@ -754,13 +751,8 @@
* @return An enumeration of prefixes (possibly empty).
* @see org.xml.sax.helpers.NamespaceSupport#getDeclaredPrefixes
*/
- Enumeration getDeclaredPrefixes ()
- {
- if (declarations == null) {
- return EMPTY_ENUMERATION;
- } else {
- return declarations.elements();
- }
+ Enumeration getDeclaredPrefixes() {
+ return (declarations == null) ? EMPTY_ENUMERATION : Collections.enumeration(declarations);
}
@@ -831,7 +823,7 @@
// Internal state.
////////////////////////////////////////////////////////////////
- private Vector declarations = null;
+ private ArrayList<String> declarations = null;
private boolean declSeen = false;
private Context parent = null;
}
diff --git a/luni/src/main/java/org/xml/sax/helpers/ParserAdapter.java b/luni/src/main/java/org/xml/sax/helpers/ParserAdapter.java
index 9910080..8e6129a 100644
--- a/luni/src/main/java/org/xml/sax/helpers/ParserAdapter.java
+++ b/luni/src/main/java/org/xml/sax/helpers/ParserAdapter.java
@@ -7,8 +7,8 @@
package org.xml.sax.helpers;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Enumeration;
-import java.util.Vector;
import org.xml.sax.AttributeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
@@ -153,10 +153,10 @@
//
// Internal constants for the sake of convenience.
//
- private final static String FEATURES = "http://xml.org/sax/features/";
- private final static String NAMESPACES = FEATURES + "namespaces";
- private final static String NAMESPACE_PREFIXES = FEATURES + "namespace-prefixes";
- private final static String XMLNS_URIs = FEATURES + "xmlns-uris";
+ private static final String FEATURES = "http://xml.org/sax/features/";
+ private static final String NAMESPACES = FEATURES + "namespaces";
+ private static final String NAMESPACE_PREFIXES = FEATURES + "namespace-prefixes";
+ private static final String XMLNS_URIs = FEATURES + "xmlns-uris";
/**
@@ -475,14 +475,12 @@
* @exception SAXException The client may raise a
* processing exception.
*/
- public void startElement (String qName, AttributeList qAtts)
- throws SAXException
- {
- // These are exceptions from the
- // first pass; they should be
- // ignored if there's a second pass,
- // but reported otherwise.
- Vector exceptions = null;
+ public void startElement (String qName, AttributeList qAtts) throws SAXException {
+ // These are exceptions from the
+ // first pass; they should be
+ // ignored if there's a second pass,
+ // but reported otherwise.
+ ArrayList<SAXParseException> exceptions = null;
// If we're not doing Namespace
// processing, dispatch this quickly.
@@ -575,18 +573,19 @@
atts.addAttribute(attName[0], attName[1], attName[2],
type, value);
} catch (SAXException e) {
- if (exceptions == null)
- exceptions = new Vector();
- exceptions.addElement(e);
- atts.addAttribute("", attQName, attQName, type, value);
+ if (exceptions == null) {
+ exceptions = new ArrayList<SAXParseException>();
+ }
+ exceptions.add((SAXParseException) e);
+ atts.addAttribute("", attQName, attQName, type, value);
}
}
// now handle the deferred exception reports
if (exceptions != null && errorHandler != null) {
- for (int i = 0; i < exceptions.size(); i++)
- errorHandler.error((SAXParseException)
- (exceptions.elementAt(i)));
+ for (SAXParseException ex : exceptions) {
+ errorHandler.error(ex);
+ }
}
// OK, finally report the event.
diff --git a/luni/src/main/native/ICU.cpp b/luni/src/main/native/ICU.cpp
index 7e05978..f5525d1 100644
--- a/luni/src/main/native/ICU.cpp
+++ b/luni/src/main/native/ICU.cpp
@@ -19,6 +19,7 @@
#include "ErrorCode.h"
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "ScopedFd.h"
#include "ScopedJavaUnicodeString.h"
#include "ScopedLocalRef.h"
#include "ScopedUtfChars.h"
@@ -42,10 +43,17 @@
#include "unicode/ustring.h"
#include "ureslocs.h"
#include "valueOf.h"
+#include <string>
+#include <errno.h>
+#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
-#include <time.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
#include <sys/time.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
class ScopedResourceBundle {
public:
@@ -532,6 +540,24 @@
return s == original ? javaString : env->NewString(s.getBuffer(), s.length());
}
+static jstring versionString(JNIEnv* env, const UVersionInfo& version) {
+ char versionString[U_MAX_VERSION_STRING_LENGTH];
+ u_versionToString(const_cast<UVersionInfo&>(version), &versionString[0]);
+ return env->NewStringUTF(versionString);
+}
+
+static jstring ICU_getIcuVersion(JNIEnv* env, jclass) {
+ UVersionInfo icuVersion;
+ u_getVersion(icuVersion);
+ return versionString(env, icuVersion);
+}
+
+static jstring ICU_getUnicodeVersion(JNIEnv* env, jclass) {
+ UVersionInfo unicodeVersion;
+ u_getUnicodeVersion(unicodeVersion);
+ return versionString(env, unicodeVersion);
+}
+
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(ICU, getAvailableBreakIteratorLocalesNative, "()[Ljava/lang/String;"),
NATIVE_METHOD(ICU, getAvailableCalendarLocalesNative, "()[Ljava/lang/String;"),
@@ -549,18 +575,64 @@
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, getIcuVersion, "()Ljava/lang/String;"),
+ NATIVE_METHOD(ICU, getUnicodeVersion, "()Ljava/lang/String;"),
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_libcore_icu_ICU(JNIEnv* env) {
+ std::string path;
+ path = u_getDataDirectory();
+ path += "/";
+ path += U_ICUDATA_NAME;
+ path += ".dat";
+ LOGI("Assuming ICU data is '%s'", path.c_str());
+
+ // Open the file and get its length.
+ ScopedFd fd(open(path.c_str(), O_RDONLY));
+ if (fd.get() == -1) {
+ LOGE("Couldn't open '%s': %s", path.c_str(), strerror(errno));
+ return -1;
+ }
+ struct stat sb;
+ if (fstat(fd.get(), &sb) == -1) {
+ LOGE("Couldn't stat '%s': %s", path.c_str(), strerror(errno));
+ return -1;
+ }
+
+ // Map it.
+ void* data = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd.get(), 0);
+ if (data == MAP_FAILED) {
+ LOGE("Couldn't map ICU data '%s': %s", path.c_str(), strerror(errno));
+ return -1;
+ }
+
+ // Tell the kernel that accesses are likely to be random rather than sequential.
+ if (madvise(data, sb.st_size, MADV_RANDOM) == -1) {
+ LOGW("madvise(MADV_RANDOM) on the ICU data failed: %s", strerror(errno));
+ }
+
+ // Tell ICU to use our memory-mapped data.
+ UErrorCode status = U_ZERO_ERROR;
+ udata_setCommonData(data, &status);
+ if (status != U_ZERO_ERROR) {
+ LOGE("Couldn't initialize ICU (udata_setCommonData): %s", u_errorName(status));
+ return -1;
+ }
+ // Tell ICU it can *only* use our memory-mapped data.
+ udata_setFileAccess(UDATA_NO_FILES, &status);
+ if (status != U_ZERO_ERROR) {
+ LOGE("Couldn't initialize ICU (udata_setFileAccess): %s", u_errorName(status));
+ return -1;
+ }
+
// 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));
+ LOGE("Couldn't initialize ICU (u_init): %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 e147e0c..9bd3598 100644
--- a/luni/src/main/native/JniConstants.cpp
+++ b/luni/src/main/native/JniConstants.cpp
@@ -43,6 +43,7 @@
jclass JniConstants::realToStringClass;
jclass JniConstants::socketClass;
jclass JniConstants::socketImplClass;
+jclass JniConstants::stringArrayClass;
jclass JniConstants::stringClass;
static jclass findClass(JNIEnv* env, const char* name) {
@@ -60,7 +61,7 @@
booleanClass = findClass(env, "java/lang/Boolean");
byteClass = findClass(env, "java/lang/Byte");
byteArrayClass = findClass(env, "[B");
- charsetICUClass = findClass(env, "libcore/icu/CharsetICU");
+ charsetICUClass = findClass(env, "java/nio/charset/CharsetICU");
constructorClass = findClass(env, "java/lang/reflect/Constructor");
datagramPacketClass = findClass(env, "java/net/DatagramPacket");
deflaterClass = findClass(env, "java/util/zip/Deflater");
@@ -80,5 +81,6 @@
realToStringClass = findClass(env, "java/lang/RealToString");
socketClass = findClass(env, "java/net/Socket");
socketImplClass = findClass(env, "java/net/SocketImpl");
+ stringArrayClass = findClass(env, "[Ljava/lang/String;");
stringClass = findClass(env, "java/lang/String");
}
diff --git a/luni/src/main/native/JniConstants.h b/luni/src/main/native/JniConstants.h
index 576b1a6..f0c8773 100644
--- a/luni/src/main/native/JniConstants.h
+++ b/luni/src/main/native/JniConstants.h
@@ -65,6 +65,7 @@
static jclass realToStringClass;
static jclass socketClass;
static jclass socketImplClass;
+ static jclass stringArrayClass;
static jclass stringClass;
};
diff --git a/luni/src/main/native/NativeConverter.cpp b/luni/src/main/native/NativeConverter.cpp
index 7587fc6..544bd99 100644
--- a/luni/src/main/native/NativeConverter.cpp
+++ b/luni/src/main/native/NativeConverter.cpp
@@ -20,6 +20,7 @@
#include "JniConstants.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
+#include "ScopedStringChars.h"
#include "ScopedUtfChars.h"
#include "UniquePtr.h"
#include "cutils/log.h"
@@ -35,16 +36,18 @@
#define NativeConverter_IGNORE 1
#define NativeConverter_REPLACE 2
+#define MAX_REPLACEMENT_LENGTH 32 // equivalent to UCNV_ERROR_BUFFER_LENGTH
+
struct DecoderCallbackContext {
- int length;
- UChar subUChars[256];
+ UChar replacementChars[MAX_REPLACEMENT_LENGTH];
+ size_t replacementCharCount;
UConverterToUCallback onUnmappableInput;
UConverterToUCallback onMalformedInput;
};
struct EncoderCallbackContext {
- int length;
- char subBytes[256];
+ char replacementBytes[MAX_REPLACEMENT_LENGTH];
+ size_t replacementByteCount;
UConverterFromUCallback onUnmappableInput;
UConverterFromUCallback onMalformedInput;
};
@@ -108,20 +111,14 @@
*sourceOffset = (mySource - uSource.get()) - *sourceOffset;
*targetOffset = (reinterpret_cast<jbyte*>(cTarget) - uTarget.get()) - *targetOffset;
- // Check how much more input is necessary to complete what's in the converter's internal buffer.
- UErrorCode minorErrorCode = U_ZERO_ERROR;
- int32_t pending = ucnv_fromUCountPending(cnv, &minorErrorCode);
- if (U_SUCCESS(minorErrorCode)) {
- myData[3] = pending;
- }
-
// If there was an error, count the problematic characters.
if (errorCode == U_ILLEGAL_CHAR_FOUND || errorCode == U_INVALID_CHAR_FOUND) {
- int8_t len = 32;
+ int8_t invalidUCharCount = 32;
UChar invalidUChars[32];
- ucnv_getInvalidUChars(cnv, invalidUChars, &len, &minorErrorCode);
+ UErrorCode minorErrorCode = U_ZERO_ERROR;
+ ucnv_getInvalidUChars(cnv, invalidUChars, &invalidUCharCount, &minorErrorCode);
if (U_SUCCESS(minorErrorCode)) {
- myData[2] = len;
+ myData[2] = invalidUCharCount;
}
}
return errorCode;
@@ -160,18 +157,14 @@
*sourceOffset = mySource - reinterpret_cast<const char*>(uSource.get()) - *sourceOffset;
*targetOffset = cTarget - uTarget.get() - *targetOffset;
- // Check how much more input is necessary to complete what's in the converter's internal buffer.
- UErrorCode minorErrorCode = U_ZERO_ERROR;
- jint pending = ucnv_toUCountPending(cnv, &minorErrorCode);
- myData[3] = pending;
-
// If there was an error, count the problematic bytes.
if (errorCode == U_ILLEGAL_CHAR_FOUND || errorCode == U_INVALID_CHAR_FOUND) {
- int8_t len = 32;
- char invalidChars[32] = {'\0'};
- ucnv_getInvalidChars(cnv, invalidChars, &len, &minorErrorCode);
+ int8_t invalidByteCount = 32;
+ char invalidBytes[32] = {'\0'};
+ UErrorCode minorErrorCode = U_ZERO_ERROR;
+ ucnv_getInvalidChars(cnv, invalidBytes, &invalidByteCount, &minorErrorCode);
if (U_SUCCESS(minorErrorCode)) {
- myData[2] = len;
+ myData[2] = invalidByteCount;
}
}
@@ -207,58 +200,6 @@
return (cnv != NULL) ? ((ucnv_getMaxCharSize(cnv) + ucnv_getMinCharSize(cnv)) / 2.0) : -1;
}
-static jint NativeConverter_flushByteToChar(JNIEnv* env, jclass, jlong address,
- jcharArray target, jint targetEnd, jintArray data) {
- UConverter* cnv = toUConverter(address);
- if (cnv == NULL) {
- return U_ILLEGAL_ARGUMENT_ERROR;
- }
- ScopedCharArrayRW uTarget(env, target);
- if (uTarget.get() == NULL) {
- return U_ILLEGAL_ARGUMENT_ERROR;
- }
- ScopedIntArrayRW myData(env, data);
- if (myData.get() == NULL) {
- return U_ILLEGAL_ARGUMENT_ERROR;
- }
- char source = '\0';
- jint* targetOffset = &myData[1];
- const char* mySource = &source;
- const char* mySourceLimit = &source;
- UChar* cTarget = uTarget.get() + *targetOffset;
- const UChar* cTargetLimit = uTarget.get() + targetEnd;
- UErrorCode errorCode = U_ZERO_ERROR;
- ucnv_toUnicode(cnv, &cTarget, cTargetLimit, &mySource, mySourceLimit, NULL, TRUE, &errorCode);
- *targetOffset = cTarget - uTarget.get() - *targetOffset;
- return errorCode;
-}
-
-static jint NativeConverter_flushCharToByte(JNIEnv* env, jclass, jlong address,
- jbyteArray target, jint targetEnd, jintArray data) {
- UConverter* cnv = toUConverter(address);
- if (cnv == NULL) {
- return U_ILLEGAL_ARGUMENT_ERROR;
- }
- ScopedByteArrayRW uTarget(env, target);
- if (uTarget.get() == NULL) {
- return U_ILLEGAL_ARGUMENT_ERROR;
- }
- ScopedIntArrayRW myData(env, data);
- if (myData.get() == NULL) {
- return U_ILLEGAL_ARGUMENT_ERROR;
- }
- jchar source = '\0';
- jint* targetOffset = &myData[1];
- const jchar* mySource = &source;
- const UChar* mySourceLimit= &source;
- char* cTarget = reinterpret_cast<char*>(uTarget.get() + *targetOffset);
- const char* cTargetLimit = reinterpret_cast<char*>(uTarget.get() + targetEnd);
- UErrorCode errorCode = U_ZERO_ERROR;
- ucnv_fromUnicode(cnv, &cTarget, cTargetLimit, &mySource, mySourceLimit, NULL, TRUE, &errorCode);
- *targetOffset = reinterpret_cast<jbyte*>(cTarget) - uTarget.get() - *targetOffset;
- return errorCode;
-}
-
static jboolean NativeConverter_canEncode(JNIEnv*, jclass, jlong address, jint codeUnit) {
UErrorCode errorCode = U_ZERO_ERROR;
UConverter* cnv = toUConverter(address);
@@ -429,58 +370,47 @@
}
const EncoderCallbackContext* context = reinterpret_cast<const EncoderCallbackContext*>(rawContext);
*err = U_ZERO_ERROR;
- ucnv_cbFromUWriteBytes(fromArgs, context->subBytes, context->length, 0, err);
+ ucnv_cbFromUWriteBytes(fromArgs, context->replacementBytes, context->replacementByteCount, 0, err);
}
static UConverterFromUCallback getFromUCallback(int32_t mode) {
switch(mode) {
- case NativeConverter_REPORT:
- return UCNV_FROM_U_CALLBACK_STOP;
- case NativeConverter_IGNORE:
- return UCNV_FROM_U_CALLBACK_SKIP;
- case NativeConverter_REPLACE:
- return encoderReplaceCallback;
+ case NativeConverter_IGNORE: return UCNV_FROM_U_CALLBACK_SKIP;
+ case NativeConverter_REPLACE: return encoderReplaceCallback;
+ case NativeConverter_REPORT: return UCNV_FROM_U_CALLBACK_STOP;
}
abort();
}
static jint NativeConverter_setCallbackEncode(JNIEnv* env, jclass, jlong address,
- jint onMalformedInput, jint onUnmappableInput, jbyteArray subBytes) {
+ jint onMalformedInput, jint onUnmappableInput, jbyteArray javaReplacement) {
UConverter* cnv = toUConverter(address);
if (!cnv) {
return U_ILLEGAL_ARGUMENT_ERROR;
}
- UConverterFromUCallback fromUOldAction = NULL;
- const void* fromUOldContext = NULL;
- ucnv_getFromUCallBack(cnv, &fromUOldAction, const_cast<const void**>(&fromUOldContext));
- /* fromUOldContext can only be DecodeCallbackContext since
- * the converter created is private data for the decoder
- * and callbacks can only be set via this method!
- */
- EncoderCallbackContext* fromUNewContext=NULL;
- UConverterFromUCallback fromUNewAction=NULL;
- if (fromUOldContext == NULL) {
- fromUNewContext = new EncoderCallbackContext;
- fromUNewAction = CHARSET_ENCODER_CALLBACK;
- } else {
- fromUNewContext = const_cast<EncoderCallbackContext*>(
- reinterpret_cast<const EncoderCallbackContext*>(fromUOldContext));
- fromUNewAction = fromUOldAction;
- fromUOldAction = NULL;
- fromUOldContext = NULL;
+ UConverterFromUCallback oldCallback = NULL;
+ const void* oldCallbackContext = NULL;
+ ucnv_getFromUCallBack(cnv, &oldCallback, const_cast<const void**>(&oldCallbackContext));
+
+ EncoderCallbackContext* callbackContext = const_cast<EncoderCallbackContext*>(
+ reinterpret_cast<const EncoderCallbackContext*>(oldCallbackContext));
+ if (callbackContext == NULL) {
+ callbackContext = new EncoderCallbackContext;
}
- fromUNewContext->onMalformedInput = getFromUCallback(onMalformedInput);
- fromUNewContext->onUnmappableInput = getFromUCallback(onUnmappableInput);
- ScopedByteArrayRO sub(env, subBytes);
- if (sub.get() == NULL) {
+
+ callbackContext->onMalformedInput = getFromUCallback(onMalformedInput);
+ callbackContext->onUnmappableInput = getFromUCallback(onUnmappableInput);
+
+ ScopedByteArrayRO replacementBytes(env, javaReplacement);
+ if (replacementBytes.get() == NULL) {
return U_ILLEGAL_ARGUMENT_ERROR;
}
- fromUNewContext->length = sub.size();
- memcpy(fromUNewContext->subBytes, sub.get(), sub.size());
+ memcpy(callbackContext->replacementBytes, replacementBytes.get(), replacementBytes.size());
+ callbackContext->replacementByteCount = replacementBytes.size();
+
UErrorCode errorCode = U_ZERO_ERROR;
- ucnv_setFromUCallBack(cnv, fromUNewAction, fromUNewContext, &fromUOldAction, &fromUOldContext,
- &errorCode);
+ ucnv_setFromUCallBack(cnv, CHARSET_ENCODER_CALLBACK, callbackContext, NULL, NULL, &errorCode);
return errorCode;
}
@@ -498,7 +428,7 @@
}
const DecoderCallbackContext* context = reinterpret_cast<const DecoderCallbackContext*>(rawContext);
*err = U_ZERO_ERROR;
- ucnv_cbToUWriteUChars(toArgs,context->subUChars, context->length, 0, err);
+ ucnv_cbToUWriteUChars(toArgs,context->replacementChars, context->replacementCharCount, 0, err);
}
static UConverterToUCallback getToUCallback(int32_t mode) {
@@ -535,43 +465,34 @@
}
static jint NativeConverter_setCallbackDecode(JNIEnv* env, jclass, jlong address,
- jint onMalformedInput, jint onUnmappableInput, jcharArray subChars) {
+ jint onMalformedInput, jint onUnmappableInput, jstring javaReplacement) {
UConverter* cnv = toUConverter(address);
if (cnv == NULL) {
return U_ILLEGAL_ARGUMENT_ERROR;
}
- UConverterToUCallback toUOldAction;
- const void* toUOldContext;
- ucnv_getToUCallBack(cnv, &toUOldAction, &toUOldContext);
+ UConverterToUCallback oldCallback;
+ const void* oldCallbackContext;
+ ucnv_getToUCallBack(cnv, &oldCallback, &oldCallbackContext);
- /* toUOldContext can only be DecodeCallbackContext since
- * the converter created is private data for the decoder
- * and callbacks can only be set via this method!
- */
- DecoderCallbackContext* toUNewContext = NULL;
- UConverterToUCallback toUNewAction = NULL;
- if (toUOldContext == NULL) {
- toUNewContext = new DecoderCallbackContext;
- toUNewAction = CHARSET_DECODER_CALLBACK;
- } else {
- toUNewContext = const_cast<DecoderCallbackContext*>(
- reinterpret_cast<const DecoderCallbackContext*>(toUOldContext));
- toUNewAction = toUOldAction;
- toUOldAction = NULL;
- toUOldContext = NULL;
+ DecoderCallbackContext* callbackContext = const_cast<DecoderCallbackContext*>(
+ reinterpret_cast<const DecoderCallbackContext*>(oldCallbackContext));
+ if (callbackContext == NULL) {
+ callbackContext = new DecoderCallbackContext;
}
- toUNewContext->onMalformedInput = getToUCallback(onMalformedInput);
- toUNewContext->onUnmappableInput = getToUCallback(onUnmappableInput);
- ScopedCharArrayRO sub(env, subChars);
- if (sub.get() == NULL) {
+
+ callbackContext->onMalformedInput = getToUCallback(onMalformedInput);
+ callbackContext->onUnmappableInput = getToUCallback(onUnmappableInput);
+
+ ScopedStringChars replacement(env, javaReplacement);
+ if (replacement.get() == NULL) {
return U_ILLEGAL_ARGUMENT_ERROR;
}
- toUNewContext->length = sub.size();
- u_strncpy(toUNewContext->subUChars, sub.get(), sub.size());
+ u_strncpy(callbackContext->replacementChars, replacement.get(), replacement.size());
+ callbackContext->replacementCharCount = replacement.size();
+
UErrorCode errorCode = U_ZERO_ERROR;
- ucnv_setToUCallBack(cnv, toUNewAction, toUNewContext, &toUOldAction, &toUOldContext,
- &errorCode);
+ ucnv_setToUCallBack(cnv, CHARSET_DECODER_CALLBACK, callbackContext, NULL, NULL, &errorCode);
return errorCode;
}
@@ -585,9 +506,9 @@
return NULL;
}
UErrorCode status = U_ZERO_ERROR;
- char subBytes[10];
- int8_t len = sizeof(subBytes);
- ucnv_getSubstChars(cnv, subBytes, &len, &status);
+ char replacementBytes[MAX_REPLACEMENT_LENGTH];
+ int8_t len = sizeof(replacementBytes);
+ ucnv_getSubstChars(cnv, replacementBytes, &len, &status);
if (!U_SUCCESS(status)) {
return env->NewByteArray(0);
}
@@ -595,7 +516,7 @@
if (result == NULL) {
return NULL;
}
- env->SetByteArrayRegion(result, 0, len, reinterpret_cast<jbyte*>(subBytes));
+ env->SetByteArrayRegion(result, 0, len, reinterpret_cast<jbyte*>(replacementBytes));
return result;
}
@@ -670,8 +591,6 @@
NATIVE_METHOD(NativeConverter, contains, "(Ljava/lang/String;Ljava/lang/String;)Z"),
NATIVE_METHOD(NativeConverter, decode, "(J[BI[CI[IZ)I"),
NATIVE_METHOD(NativeConverter, encode, "(J[CI[BI[IZ)I"),
- NATIVE_METHOD(NativeConverter, flushByteToChar, "(J[CI[I)I"),
- NATIVE_METHOD(NativeConverter, flushCharToByte, "(J[BI[I)I"),
NATIVE_METHOD(NativeConverter, getAvailableCharsetNames, "()[Ljava/lang/String;"),
NATIVE_METHOD(NativeConverter, getAveBytesPerChar, "(J)F"),
NATIVE_METHOD(NativeConverter, getAveCharsPerByte, "(J)F"),
@@ -681,7 +600,7 @@
NATIVE_METHOD(NativeConverter, openConverter, "(Ljava/lang/String;)J"),
NATIVE_METHOD(NativeConverter, resetByteToChar, "(J)V"),
NATIVE_METHOD(NativeConverter, resetCharToByte, "(J)V"),
- NATIVE_METHOD(NativeConverter, setCallbackDecode, "(JII[C)I"),
+ NATIVE_METHOD(NativeConverter, setCallbackDecode, "(JIILjava/lang/String;)I"),
NATIVE_METHOD(NativeConverter, setCallbackEncode, "(JII[B)I"),
};
int register_libcore_icu_NativeConverter(JNIEnv* env) {
diff --git a/luni/src/main/native/Register.cpp b/luni/src/main/native/Register.cpp
index a6e49dc..0cdf51d 100644
--- a/luni/src/main/native/Register.cpp
+++ b/luni/src/main/native/Register.cpp
@@ -21,10 +21,6 @@
#include <stdlib.h>
-namespace android {
- extern int register_dalvik_system_TouchDex(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);
@@ -109,16 +105,15 @@
register_libcore_icu_TimeZones(env) != -1 &&
register_libcore_io_IoUtils(env) != -1 &&
register_libcore_net_RawSocket(env) != -1 &&
+ register_org_apache_harmony_dalvik_NativeTestTarget(env) != -1 &&
register_org_apache_harmony_luni_platform_OSFileSystem(env) != -1 &&
register_org_apache_harmony_luni_platform_OSMemory(env) != -1 &&
register_org_apache_harmony_luni_platform_OSNetworkSystem(env) != -1 &&
register_org_apache_harmony_luni_util_fltparse(env) != -1 &&
register_org_apache_harmony_text_NativeBidi(env) != -1 &&
+ register_org_apache_harmony_xml_ExpatParser(env) != -1 &&
register_org_apache_harmony_xnet_provider_jsse_NativeCrypto(env) != -1 &&
- // Initialize the Android classes last, as they have dependencies on the "corer" core classes.
- android::register_dalvik_system_TouchDex(env) != -1 &&
- register_org_apache_harmony_dalvik_NativeTestTarget(env) != -1 &&
- register_org_apache_harmony_xml_ExpatParser(env) != -1;
+ true;
if (!result) {
LOGE("Failed to initialize the core libraries; aborting...");
diff --git a/luni/src/main/native/TimeZones.cpp b/luni/src/main/native/TimeZones.cpp
index dbe351f..6e31713 100644
--- a/luni/src/main/native/TimeZones.cpp
+++ b/luni/src/main/native/TimeZones.cpp
@@ -16,6 +16,9 @@
#define LOG_TAG "TimeZones"
+#include <map>
+#include <vector>
+
#include "ErrorCode.h"
#include "JNIHelp.h"
#include "JniConstants.h"
@@ -28,17 +31,6 @@
extern Locale getLocale(JNIEnv* env, jstring localeName);
-static jstring formatDate(JNIEnv* env, const SimpleDateFormat& fmt, const UDate& when) {
- UnicodeString str;
- fmt.format(when, str);
- return env->NewString(str.getBuffer(), str.length());
-}
-
-static TimeZone* timeZoneFromId(JNIEnv* env, jstring javaZoneId) {
- ScopedJavaUnicodeString zoneID(env, javaZoneId);
- return TimeZone::createTimeZone(zoneID.unicodeString());
-}
-
static jobjectArray TimeZones_forCountryCode(JNIEnv* env, jclass, jstring countryCode) {
ScopedUtfChars countryChars(env, countryCode);
if (countryChars.c_str() == NULL) {
@@ -69,85 +61,145 @@
return result;
}
-static jstring TimeZones_getDisplayNameImpl(JNIEnv* env, jclass, jstring zoneId, jboolean isDST, jint style, jstring localeId) {
- UniquePtr<TimeZone> zone(timeZoneFromId(env, zoneId));
- Locale locale = getLocale(env, localeId);
- // Try to get the display name of the TimeZone according to the Locale
- UnicodeString displayName;
- zone->getDisplayName((UBool)isDST, (style == 0 ? TimeZone::SHORT : TimeZone::LONG), locale, displayName);
- return env->NewString(displayName.getBuffer(), displayName.length());
+struct TimeZoneNames {
+ TimeZone* tz;
+
+ UnicodeString longStd;
+ UnicodeString shortStd;
+ UnicodeString longDst;
+ UnicodeString shortDst;
+
+ UDate standardDate;
+ UDate daylightSavingDate;
+};
+
+static void setStringArrayElement(JNIEnv* env, jobjectArray array, int i, const UnicodeString& s) {
+ ScopedLocalRef<jstring> javaString(env, env->NewString(s.getBuffer(), s.length()));
+ env->SetObjectArrayElement(array, i, javaString.get());
}
-static void TimeZones_getZoneStringsImpl(JNIEnv* env, jclass, jobjectArray outerArray, jstring localeName) {
+static jobjectArray TimeZones_getZoneStringsImpl(JNIEnv* env, jclass, jstring localeName, jobjectArray timeZoneIds) {
Locale locale = getLocale(env, localeName);
- // We could use TimeZone::getDisplayName, but that's way too slow.
- // The cost of this method goes from 0.5s to 4.5s on a Nexus One.
- // Much of the saving comes from caching SimpleDateFormat instances.
+ // We could use TimeZone::getDisplayName, but that's even slower
+ // because it creates a new SimpleDateFormat each time.
+ // We're better off using SimpleDateFormat directly.
+
+ // We can't use DateFormatSymbols::getZoneStrings because that
+ // uses its own set of time zone ids and contains empty strings
+ // instead of GMT offsets (a pity, because it's a bit faster than this code).
+
UErrorCode status = U_ZERO_ERROR;
- UnicodeString longPattern("zzzz", "");
+ UnicodeString longPattern("zzzz", 4, US_INV);
SimpleDateFormat longFormat(longPattern, locale, status);
- UnicodeString shortPattern("z", "");
- SimpleDateFormat shortFormat(shortPattern, locale, status);
+ // 'z' only uses "common" abbreviations. 'V' allows all known abbreviations.
+ // For example, "PST" is in common use in en_US, but "CET" isn't.
+ UnicodeString commonShortPattern("z", 1, US_INV);
+ SimpleDateFormat shortFormat(commonShortPattern, locale, status);
+ UnicodeString allShortPattern("V", 1, US_INV);
+ SimpleDateFormat allShortFormat(allShortPattern, locale, status);
- jobjectArray longStdArray = (jobjectArray) env->GetObjectArrayElement(outerArray, 1);
- jobjectArray shortStdArray = (jobjectArray) env->GetObjectArrayElement(outerArray, 2);
- jobjectArray longDstArray = (jobjectArray) env->GetObjectArrayElement(outerArray, 3);
- jobjectArray shortDstArray = (jobjectArray) env->GetObjectArrayElement(outerArray, 4);
-
+ // TODO: use of fixed dates prevents us from using the correct historical name when formatting dates.
+ // TODO: use of dates not in the current year could cause us to output obsoleted names.
// 15th January 2008
UDate date1 = 1203105600000.0;
// 15th July 2008
UDate date2 = 1218826800000.0;
- jobjectArray zoneIds = (jobjectArray) env->GetObjectArrayElement(outerArray, 0);
- int zoneIdCount = env->GetArrayLength(zoneIds);
- for (int i = 0; i < zoneIdCount; ++i) {
- ScopedLocalRef<jstring> id(env, reinterpret_cast<jstring>(env->GetObjectArrayElement(zoneIds, i)));
- UniquePtr<TimeZone> tz(timeZoneFromId(env, id.get()));
+ // In the first pass, we get the long names for the time zone.
+ // We also get any commonly-used abbreviations.
+ std::vector<TimeZoneNames> table;
+ typedef std::map<UnicodeString, UnicodeString*> AbbreviationMap;
+ AbbreviationMap usedAbbreviations;
+ size_t idCount = env->GetArrayLength(timeZoneIds);
+ for (size_t i = 0; i < idCount; ++i) {
+ ScopedLocalRef<jstring> javaZoneId(env,
+ reinterpret_cast<jstring>(env->GetObjectArrayElement(timeZoneIds, i)));
+ ScopedJavaUnicodeString zoneId(env, javaZoneId.get());
+ UnicodeString id(zoneId.unicodeString());
- longFormat.setTimeZone(*tz);
- shortFormat.setTimeZone(*tz);
+ TimeZoneNames row;
+ row.tz = TimeZone::createTimeZone(id);
+
+ longFormat.setTimeZone(*row.tz);
+ shortFormat.setTimeZone(*row.tz);
int32_t daylightOffset;
int32_t rawOffset;
- tz->getOffset(date1, false, rawOffset, daylightOffset, status);
- UDate standardDate;
- UDate daylightSavingDate;
+ row.tz->getOffset(date1, false, rawOffset, daylightOffset, status);
if (daylightOffset != 0) {
- // The Timezone is reporting that we are in daylight time
- // for the winter date. The dates are for the wrong hemisphere,
- // swap them.
- standardDate = date2;
- daylightSavingDate = date1;
+ // The TimeZone is reporting that we are in daylight time for the winter date.
+ // The dates are for the wrong hemisphere, so swap them.
+ row.standardDate = date2;
+ row.daylightSavingDate = date1;
} else {
- standardDate = date1;
- daylightSavingDate = date2;
+ row.standardDate = date1;
+ row.daylightSavingDate = date2;
}
- ScopedLocalRef<jstring> shortStd(env, formatDate(env, shortFormat, standardDate));
- env->SetObjectArrayElement(shortStdArray, i, shortStd.get());
-
- ScopedLocalRef<jstring> longStd(env, formatDate(env, longFormat, standardDate));
- env->SetObjectArrayElement(longStdArray, i, longStd.get());
-
- if (tz->useDaylightTime()) {
- ScopedLocalRef<jstring> shortDst(env, formatDate(env, shortFormat, daylightSavingDate));
- env->SetObjectArrayElement(shortDstArray, i, shortDst.get());
-
- ScopedLocalRef<jstring> longDst(env, formatDate(env, longFormat, daylightSavingDate));
- env->SetObjectArrayElement(longDstArray, i, longDst.get());
+ longFormat.format(row.standardDate, row.longStd);
+ shortFormat.format(row.standardDate, row.shortStd);
+ if (row.tz->useDaylightTime()) {
+ longFormat.format(row.daylightSavingDate, row.longDst);
+ shortFormat.format(row.daylightSavingDate, row.shortDst);
} else {
- env->SetObjectArrayElement(shortDstArray, i, shortStd.get());
- env->SetObjectArrayElement(longDstArray, i, longStd.get());
+ row.longDst = row.longStd;
+ row.shortDst = row.shortStd;
}
+
+ table.push_back(row);
+ usedAbbreviations[row.shortStd] = &row.longStd;
+ usedAbbreviations[row.shortDst] = &row.longDst;
}
+
+ // In the second pass, we create the Java String[][].
+ // We also look for any uncommon abbreviations that don't conflict with ones we've already seen.
+ jobjectArray result = env->NewObjectArray(idCount, JniConstants::stringArrayClass, NULL);
+ UnicodeString gmt("GMT", 3, US_INV);
+ for (size_t i = 0; i < table.size(); ++i) {
+ TimeZoneNames& row(table[i]);
+ // Did we get a GMT offset instead of an abbreviation?
+ if (row.shortStd.length() > 3 && row.shortStd.startsWith(gmt)) {
+ // See if we can do better...
+ UnicodeString uncommonStd, uncommonDst;
+ allShortFormat.setTimeZone(*row.tz);
+ allShortFormat.format(row.standardDate, uncommonStd);
+ if (row.tz->useDaylightTime()) {
+ allShortFormat.format(row.daylightSavingDate, uncommonDst);
+ } else {
+ uncommonDst = uncommonStd;
+ }
+
+ // If this abbreviation isn't already in use, we can use it.
+ AbbreviationMap::iterator it = usedAbbreviations.find(uncommonStd);
+ if (it == usedAbbreviations.end() || *(it->second) == row.longStd) {
+ row.shortStd = uncommonStd;
+ usedAbbreviations[row.shortStd] = &row.longStd;
+ }
+ it = usedAbbreviations.find(uncommonDst);
+ if (it == usedAbbreviations.end() || *(it->second) == row.longDst) {
+ row.shortDst = uncommonDst;
+ usedAbbreviations[row.shortDst] = &row.longDst;
+ }
+ }
+ // Fill in whatever we got.
+ ScopedLocalRef<jobjectArray> javaRow(env, env->NewObjectArray(5, JniConstants::stringClass, NULL));
+ ScopedLocalRef<jstring> id(env, reinterpret_cast<jstring>(env->GetObjectArrayElement(timeZoneIds, i)));
+ env->SetObjectArrayElement(javaRow.get(), 0, id.get());
+ setStringArrayElement(env, javaRow.get(), 1, row.longStd);
+ setStringArrayElement(env, javaRow.get(), 2, row.shortStd);
+ setStringArrayElement(env, javaRow.get(), 3, row.longDst);
+ setStringArrayElement(env, javaRow.get(), 4, row.shortDst);
+ env->SetObjectArrayElement(result, i, javaRow.get());
+ delete row.tz;
+ }
+
+ return result;
}
static JNINativeMethod gMethods[] = {
- NATIVE_METHOD(TimeZones, getDisplayNameImpl, "(Ljava/lang/String;ZILjava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(TimeZones, forCountryCode, "(Ljava/lang/String;)[Ljava/lang/String;"),
- NATIVE_METHOD(TimeZones, getZoneStringsImpl, "([[Ljava/lang/String;Ljava/lang/String;)V"),
+ NATIVE_METHOD(TimeZones, getZoneStringsImpl, "(Ljava/lang/String;[Ljava/lang/String;)[[Ljava/lang/String;"),
};
int register_libcore_icu_TimeZones(JNIEnv* env) {
return jniRegisterNativeMethods(env, "libcore/icu/TimeZones", gMethods, NELEM(gMethods));
diff --git a/luni/src/main/native/java_io_File.cpp b/luni/src/main/native/java_io_File.cpp
index 3004fc4..b3d7f0a 100644
--- a/luni/src/main/native/java_io_File.cpp
+++ b/luni/src/main/native/java_io_File.cpp
@@ -19,6 +19,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "JniException.h"
#include "LocalArray.h"
#include "ScopedFd.h"
#include "ScopedLocalRef.h"
@@ -339,7 +340,7 @@
while ((filename = dir.next()) != NULL) {
if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0) {
if (!entries.push_front(filename)) {
- jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+ jniThrowOutOfMemoryError(env, NULL);
return false;
}
}
diff --git a/luni/src/main/native/java_util_zip_Deflater.cpp b/luni/src/main/native/java_util_zip_Deflater.cpp
index 2f27f5c..82d081b 100644
--- a/luni/src/main/native/java_util_zip_Deflater.cpp
+++ b/luni/src/main/native/java_util_zip_Deflater.cpp
@@ -52,10 +52,8 @@
* that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
* plus a few kilobytes for small objects."
*/
- // TODO: should we just use DEF_WBITS (15) and DEF_MEM_LEVEL (8) now?
- int windowBits = noHeader ? -12 : 12; // Was 15, made it 12 to reduce memory consumption. Use MAX_WBITS for fastest.
- int memLevel = 5; // Was 9 (MAX_MEM_LEVEL), made it 5 to reduce memory consumption. Might result
- // in out-of-memory problems according to some web pages.
+ int windowBits = noHeader ? -DEF_WBITS : DEF_WBITS;
+ int memLevel = DEF_MEM_LEVEL;
int err = deflateInit2(&jstream->stream, level, Z_DEFLATED, windowBits, memLevel, strategy);
if (err != Z_OK) {
throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err);
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 4a9a6f0..d740599 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
@@ -164,7 +164,7 @@
jintArray jBuffers, jintArray jOffsets, jintArray jLengths, jint size) {
UniquePtr<iovec[]> vectors(new iovec[size]);
if (vectors.get() == NULL) {
- jniThrowException(env, "java/lang/OutOfMemoryError", "native heap");
+ jniThrowOutOfMemoryError(env, NULL);
return NULL;
}
ScopedIntArrayRO buffers(env, jBuffers);
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 1428a80..70a6d4b 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
@@ -20,6 +20,7 @@
#include <math.h>
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "JniException.h"
#include "ScopedUtfChars.h"
#include "cbigint.h"
@@ -510,7 +511,7 @@
free(y);
free(D);
free(D2);
- jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+ jniThrowOutOfMemoryError(env, NULL);
return z;
}
@@ -984,7 +985,7 @@
free(y);
free(D);
free(D2);
- jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
+ jniThrowOutOfMemoryError(env, NULL);
return z;
}
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 a5ee710..4ef4378 100644
--- a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
+++ b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp
@@ -18,6 +18,7 @@
#include "JNIHelp.h"
#include "JniConstants.h"
+#include "JniException.h"
#include "LocalArray.h"
#include "ScopedJavaUnicodeString.h"
#include "ScopedLocalRef.h"
@@ -34,10 +35,6 @@
#define BUCKET_COUNT 128
-static void throw_OutOfMemoryError(JNIEnv* env) {
- jniThrowException(env, "java/lang/OutOfMemoryError", "Out of memory.");
-}
-
/**
* Wrapper around an interned string.
*/
@@ -76,7 +73,7 @@
int newCapacity = capacity * 2;
jstring* newArray = new jstring[newCapacity];
if (newArray == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return;
}
memcpy(newArray, array, capacity * sizeof(jstring));
@@ -250,7 +247,7 @@
// Allocate a new wrapper.
UniquePtr<InternedString> wrapper(new InternedString);
if (wrapper.get() == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return NULL;
}
@@ -258,7 +255,7 @@
// TODO: sometimes we already know the length. Reuse it if so.
char* copy = new char[strlen(bytes) + 1];
if (copy == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return NULL;
}
strcpy(copy, bytes);
@@ -380,7 +377,7 @@
// Expand the bucket.
bucket = expandInternedStringBucket(bucket, internedString);
if (bucket == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return NULL;
}
@@ -395,7 +392,7 @@
// Create a new bucket with one entry.
bucket = newInternedStringBucket(internedString);
if (bucket == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return NULL;
}
@@ -847,7 +844,7 @@
XML_Parser parent = (XML_Parser) parentParser;
XML_Parser entityParser = XML_ExternalEntityParserCreate(parent, context.c_str(), NULL);
if (entityParser == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
}
return (jint) entityParser;
@@ -956,7 +953,7 @@
// Allocate parsing context.
UniquePtr<ParsingContext> context(new ParsingContext(object));
if (context.get() == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return 0;
}
@@ -992,7 +989,7 @@
XML_SetUnparsedEntityDeclHandler(parser, unparsedEntityDecl);
XML_SetUserData(parser, context.release());
} else {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return 0;
}
@@ -1278,7 +1275,7 @@
char* buffer = new char[totalSize];
if (buffer == NULL) {
- throw_OutOfMemoryError(env);
+ jniThrowOutOfMemoryError(env, NULL);
return 0;
}
diff --git a/luni/src/main/native/sub.mk b/luni/src/main/native/sub.mk
index 16059fe..4f94dd1 100644
--- a/luni/src/main/native/sub.mk
+++ b/luni/src/main/native/sub.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
# This file is included by the top-level libcore Android.mk.
# It's not a normal makefile, so we don't include CLEAR_VARS
# or BUILD_*_LIBRARY.
diff --git a/luni/src/test/java-internal/org/apache/harmony/archive/util/UtilTest.java b/luni/src/test/java-internal/org/apache/harmony/archive/util/UtilTest.java
deleted file mode 100644
index 7e1c4bd..0000000
--- a/luni/src/test/java-internal/org/apache/harmony/archive/util/UtilTest.java
+++ /dev/null
@@ -1,70 +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.util;
-
-import junit.framework.TestCase;
-
-public class UtilTest extends TestCase {
- private static final String ASCII_ALPHABET_LC = "abcdefghijklmnopqrstuvwxyz";
- private static final String ASCII_ALPHABET_UC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- private static final byte[] ASCII_ALPHABET_LC_BYTES;
- private static final byte[] ASCII_ALPHABET_UC_BYTES;
-
- static {
- ASCII_ALPHABET_LC_BYTES = new byte[ASCII_ALPHABET_LC.length()];
- for (int i = 0; i < ASCII_ALPHABET_LC_BYTES.length; i++) {
- final char c = ASCII_ALPHABET_LC.charAt(i);
- final byte b = (byte) c;
- assert ((char) b) == c;
- ASCII_ALPHABET_LC_BYTES[i] = b;
- }
-
- ASCII_ALPHABET_UC_BYTES = new byte[ASCII_ALPHABET_UC.length()];
- for (int i = 0; i < ASCII_ALPHABET_UC_BYTES.length; i++) {
- final char c = ASCII_ALPHABET_UC.charAt(i);
- final byte b = (byte) c;
- assert ((char) b) == c;
- ASCII_ALPHABET_UC_BYTES[i] = b;
- }
- }
-
- public void testasciiEndsWithIgnoreCase() {
- final String s1 = ASCII_ALPHABET_LC;
- final String s2 = ASCII_ALPHABET_UC;
- assertTrue(Util.asciiEndsWithIgnoreCase(s1, s2));
- assertTrue(Util.asciiEndsWithIgnoreCase(s2, s1));
- assertTrue(Util.asciiEndsWithIgnoreCase(s1, "wxyz"));
- }
-
- public void testasciiEqualsIgnoreCase() {
- final String s1 = ASCII_ALPHABET_LC;
- final String s2 = ASCII_ALPHABET_UC;
- assertTrue(Util.asciiEqualsIgnoreCase(s1, s2));
- assertTrue(Util.asciiEqualsIgnoreCase(s2, s1));
- }
-
- public void testEqualsIgnoreCaseByteArrayByteArray() {
- assertTrue(Util.asciiEqualsIgnoreCase(ASCII_ALPHABET_LC_BYTES,
- ASCII_ALPHABET_LC_BYTES));
- assertTrue(Util.asciiEqualsIgnoreCase(ASCII_ALPHABET_LC_BYTES,
- ASCII_ALPHABET_UC_BYTES));
- assertTrue(Util.asciiEqualsIgnoreCase(ASCII_ALPHABET_UC_BYTES,
- ASCII_ALPHABET_UC_BYTES));
- }
-
-}
diff --git a/luni/src/test/java/dalvik/system/DexClassLoaderTest.java b/luni/src/test/java/dalvik/system/DexClassLoaderTest.java
index c34b5cd..c7bfc80 100644
--- a/luni/src/test/java/dalvik/system/DexClassLoaderTest.java
+++ b/luni/src/test/java/dalvik/system/DexClassLoaderTest.java
@@ -74,10 +74,15 @@
}
/**
- * Copy a resource in the package directory to the indicated file.
+ * Copy a resource in the package directory to the indicated
+ * target file, but only if the target file doesn't exist.
*/
private static void copyResource(ClassLoader loader, String resourceName,
File destination) throws IOException {
+ if (destination.exists()) {
+ return;
+ }
+
InputStream in =
loader.getResourceAsStream(PACKAGE_PATH + resourceName);
FileOutputStream out = new FileOutputStream(destination);
diff --git a/luni/src/test/java/libcore/java/io/OutputStreamWriterTest.java b/luni/src/test/java/libcore/java/io/OutputStreamWriterTest.java
new file mode 100644
index 0000000..af9ec9b
--- /dev/null
+++ b/luni/src/test/java/libcore/java/io/OutputStreamWriterTest.java
@@ -0,0 +1,97 @@
+/*
+ * 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.*;
+import java.util.Arrays;
+import junit.framework.TestCase;
+
+public class OutputStreamWriterTest extends TestCase {
+ private class FlushCountingOutputStream extends OutputStream {
+ int flushCount;
+ public void write(int b) {
+ }
+ @Override public void flush() throws IOException {
+ ++flushCount;
+ }
+ }
+
+ public void testFlushCount() throws Exception {
+ FlushCountingOutputStream os = new FlushCountingOutputStream();
+ OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
+ char[] chars = new char[16*1024];
+ Arrays.fill(chars, 'x');
+ for (int i = 0; i < 10; ++i) {
+ writer.write(chars);
+ }
+ assertEquals(0, os.flushCount);
+ writer.flush();
+ assertEquals(1, os.flushCount);
+ writer.close();
+ assertEquals(1, os.flushCount);
+ }
+
+ private void testFlush(boolean includeSecondHalf) throws Exception {
+ // OutputStreamWriter has an internal 8KiB buffer.
+ // We write enough characters to fill that, but leave data in the encoder.
+ // (Specifically, half a surrogate pair.)
+ // On flush/close, the writer needs to admit defeat and write the replacement character.
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-32BE");
+ char[] cs = new char[8192/4 + 1];
+ Arrays.fill(cs, 'x');
+ cs[cs.length - 1] = '\ud842'; // One half of a surrogate pair (the other being U+df9f).
+ writer.write(cs, 0, cs.length);
+ writer.flush();
+ assertEquals(8192, baos.size()); // Just the 'x's so far.
+ if (includeSecondHalf) {
+ writer.write(0xdf9f);
+ }
+ writer.close();
+ // We should have 8192 32-bit big-endian 'x's...
+ byte[] bytes = baos.toByteArray();
+ assertEquals(8196, bytes.length);
+ int i = 0;
+ while (i < 8192) {
+ assertEquals((byte) 0, bytes[i++]);
+ assertEquals((byte) 0, bytes[i++]);
+ assertEquals((byte) 0, bytes[i++]);
+ assertEquals((byte) 'x', bytes[i++]);
+ }
+ if (includeSecondHalf) {
+ // ...followed by a 32-bit big-endian U+20b9f.
+ assertEquals((byte) 0x00, bytes[i++]);
+ assertEquals((byte) 0x02, bytes[i++]);
+ assertEquals((byte) 0x0b, bytes[i++]);
+ assertEquals((byte) 0x9f, bytes[i++]);
+ } else {
+ // ...followed by a 32-bit big-endian replacement character (U+fffd).
+ assertEquals((byte) 0, bytes[i++]);
+ assertEquals((byte) 0, bytes[i++]);
+ assertEquals((byte) 0xff, bytes[i++]);
+ assertEquals((byte) 0xfd, bytes[i++]);
+ }
+ }
+
+ public void testFlush_halfSurrogate() throws Exception {
+ testFlush(false);
+ }
+
+ public void testFlush_wholeSurrogate() throws Exception {
+ testFlush(true);
+ }
+}
diff --git a/luni/src/test/java/libcore/java/io/StreamTokenizerTest.java b/luni/src/test/java/libcore/java/io/StreamTokenizerTest.java
new file mode 100644
index 0000000..418d193
--- /dev/null
+++ b/luni/src/test/java/libcore/java/io/StreamTokenizerTest.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2011 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.StreamTokenizer;
+import java.io.StringReader;
+import java.util.Locale;
+import junit.framework.TestCase;
+
+public class StreamTokenizerTest extends TestCase {
+ public void testLowerCase() throws Exception {
+ Locale.setDefault(Locale.US);
+ StreamTokenizer st = new StreamTokenizer(new StringReader("aIb aIb"));
+ st.lowerCaseMode(true);
+ st.nextToken();
+ assertEquals("aib", st.sval);
+
+ Locale.setDefault(new Locale("tr", "TR"));
+ st.nextToken();
+ assertEquals("a\u0131b", st.sval);
+ }
+}
diff --git a/luni/src/test/java/libcore/java/lang/DoubleTest.java b/luni/src/test/java/libcore/java/lang/DoubleTest.java
index f92ae33..e4c7459 100644
--- a/luni/src/test/java/libcore/java/lang/DoubleTest.java
+++ b/luni/src/test/java/libcore/java/lang/DoubleTest.java
@@ -19,9 +19,110 @@
import junit.framework.TestCase;
public class DoubleTest extends TestCase {
- // http://b/3238333
- public void test3238333() throws Exception {
+ public void testDoubleToStringUnsignedDivide() throws Exception {
+ // http://b/3238333
assertEquals("0.008", Double.toString(0.008));
assertEquals("0.008366", Double.toString(0.008366));
+ // http://code.google.com/p/android/issues/detail?id=14033
+ assertEquals("0.009", Double.toString(0.009));
+ // http://code.google.com/p/android/issues/detail?id=14302
+ assertEquals("0.008567856012638986", Double.toString(0.008567856012638986));
+ assertEquals("0.010206713752229896", Double.toString(0.010206713752229896));
+ }
+
+ public void testNamedDoubles() throws Exception {
+ assertEquals(Double.NaN, Double.parseDouble("NaN"));
+ assertEquals(Double.NaN, Double.parseDouble("-NaN"));
+ assertEquals(Double.NaN, Double.parseDouble("+NaN"));
+ try {
+ Double.parseDouble("NNaN");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ try {
+ Double.parseDouble("NaNN");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+
+ assertEquals(Double.POSITIVE_INFINITY, Double.parseDouble("+Infinity"));
+ assertEquals(Double.POSITIVE_INFINITY, Double.parseDouble("Infinity"));
+ assertEquals(Double.NEGATIVE_INFINITY, Double.parseDouble("-Infinity"));
+ try {
+ Double.parseDouble("IInfinity");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ try {
+ Double.parseDouble("Infinityy");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ }
+
+ public void testSuffixParsing() throws Exception {
+ String[] badStrings = { "1ff", "1fd", "1df", "1dd" };
+ for (String string : badStrings) {
+ try {
+ Double.parseDouble(string);
+ fail(string);
+ } catch (NumberFormatException expected) {
+ }
+ }
+ assertEquals(1.0, Double.parseDouble("1f"));
+ assertEquals(1.0, Double.parseDouble("1d"));
+ assertEquals(1.0, Double.parseDouble("1F"));
+ assertEquals(1.0, Double.parseDouble("1D"));
+ assertEquals(1.0, Double.parseDouble("1.D"));
+ assertEquals(1.0, Double.parseDouble("1.E0D"));
+ assertEquals(1.0, Double.parseDouble(".1E1D"));
+ }
+
+ public void testExponentParsing() throws Exception {
+ String[] strings = {
+ // Exponents missing integer values.
+ "1.0e", "1.0e+", "1.0e-",
+ // Exponents with too many explicit signs.
+ "1.0e++1", "1.0e+-1", "1.0e-+1", "1.0e--1"
+ };
+ for (String string : strings) {
+ try {
+ Double.parseDouble(string);
+ fail(string);
+ } catch (NumberFormatException expected) {
+ }
+ }
+
+ assertEquals(1.0e-323, Double.parseDouble("1.0e-323"));
+ assertEquals(0.0, Double.parseDouble("1.0e-324"));
+ assertEquals(-1.0e-323, Double.parseDouble("-1.0e-323"));
+ assertEquals(-0.0, Double.parseDouble("-1.0e-324"));
+
+ assertEquals(1.0e+308, Double.parseDouble("1.0e+308"));
+ assertEquals(Double.POSITIVE_INFINITY, Double.parseDouble("1.0e+309"));
+ assertEquals(-1.0e+308, Double.parseDouble("-1.0e+308"));
+ assertEquals(Double.NEGATIVE_INFINITY, Double.parseDouble("-1.0e+309"));
+
+ assertEquals(Double.POSITIVE_INFINITY, Double.parseDouble("1.0e+9999999999"));
+ assertEquals(Double.NEGATIVE_INFINITY, Double.parseDouble("-1.0e+9999999999"));
+ assertEquals(0.0, Double.parseDouble("1.0e-9999999999"));
+ assertEquals(-0.0, Double.parseDouble("-1.0e-9999999999"));
+
+ assertEquals(Double.POSITIVE_INFINITY, Double.parseDouble("320.0e+2147483647"));
+ assertEquals(-0.0, Double.parseDouble("-1.4e-2147483314"));
+ }
+
+ /**
+ * This value has been known to cause javac and java to infinite loop.
+ * http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
+ */
+ public void testParseLargestSubnormalDoublePrecision() {
+ assertEquals(2.2250738585072014E-308, Double.parseDouble("2.2250738585072012e-308"));
+ assertEquals(2.2250738585072014E-308, Double.parseDouble("0.00022250738585072012e-304"));
+ assertEquals(2.2250738585072014E-308, Double.parseDouble("00000002.2250738585072012e-308"));
+ assertEquals(2.2250738585072014E-308, Double.parseDouble("2.225073858507201200000e-308"));
+ assertEquals(2.2250738585072014E-308, Double.parseDouble("2.2250738585072012e-00308"));
+ assertEquals(2.2250738585072014E-308, Double.parseDouble("2.22507385850720129978001e-308"));
+ assertEquals(-2.2250738585072014E-308, Double.parseDouble("-2.2250738585072012e-308"));
}
}
diff --git a/luni/src/test/java/libcore/java/lang/FloatTest.java b/luni/src/test/java/libcore/java/lang/FloatTest.java
index 3708d87..00e1597 100644
--- a/luni/src/test/java/libcore/java/lang/FloatTest.java
+++ b/luni/src/test/java/libcore/java/lang/FloatTest.java
@@ -22,9 +22,92 @@
// http://code.google.com/p/android/issues/detail?id=4185
assertEquals(2358.166016f, Float.valueOf("2358.166016"));
}
+
public void test_valueOf_String2() throws Exception {
// This threw OutOfMemoryException.
// http://code.google.com/p/android/issues/detail?id=3156
assertEquals(-2.14748365E9f, Float.valueOf(String.valueOf(Integer.MIN_VALUE)));
}
+
+ public void testNamedFloats() throws Exception {
+ assertEquals(Float.NaN, Float.parseFloat("NaN"));
+ assertEquals(Float.NaN, Float.parseFloat("-NaN"));
+ assertEquals(Float.NaN, Float.parseFloat("+NaN"));
+ try {
+ Float.parseFloat("NNaN");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ try {
+ Float.parseFloat("NaNN");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+
+ assertEquals(Float.POSITIVE_INFINITY, Float.parseFloat("+Infinity"));
+ assertEquals(Float.POSITIVE_INFINITY, Float.parseFloat("Infinity"));
+ assertEquals(Float.NEGATIVE_INFINITY, Float.parseFloat("-Infinity"));
+ try {
+ Float.parseFloat("IInfinity");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ try {
+ Float.parseFloat("Infinityy");
+ fail();
+ } catch (NumberFormatException expected) {
+ }
+ }
+
+ public void testSuffixParsing() throws Exception {
+ String[] badStrings = { "1ff", "1fd", "1df", "1dd" };
+ for (String string : badStrings) {
+ try {
+ Float.parseFloat(string);
+ fail(string);
+ } catch (NumberFormatException expected) {
+ }
+ }
+ assertEquals(1.0f, Float.parseFloat("1f"));
+ assertEquals(1.0f, Float.parseFloat("1d"));
+ assertEquals(1.0f, Float.parseFloat("1F"));
+ assertEquals(1.0f, Float.parseFloat("1D"));
+ assertEquals(1.0f, Float.parseFloat("1.D"));
+ assertEquals(1.0f, Float.parseFloat("1.E0D"));
+ assertEquals(1.0f, Float.parseFloat(".1E1D"));
+ }
+
+ public void testExponentParsing() throws Exception {
+ String[] strings = {
+ // Exponents missing integer values.
+ "1.0e", "1.0e+", "1.0e-",
+ // Exponents with too many explicit signs.
+ "1.0e++1", "1.0e+-1", "1.0e-+1", "1.0e--1"
+ };
+ for (String string : strings) {
+ try {
+ Float.parseFloat(string);
+ fail(string);
+ } catch (NumberFormatException expected) {
+ }
+ }
+
+ assertEquals(1.0e-45f, Float.parseFloat("1.0e-45"));
+ assertEquals(0.0f, Float.parseFloat("1.0e-46"));
+ assertEquals(-1.0e-45f, Float.parseFloat("-1.0e-45"));
+ assertEquals(-0.0f, Float.parseFloat("-1.0e-46"));
+
+ assertEquals(1.0e+38f, Float.parseFloat("1.0e+38"));
+ assertEquals(Float.POSITIVE_INFINITY, Float.parseFloat("1.0e+39"));
+ assertEquals(-1.0e+38f, Float.parseFloat("-1.0e+38"));
+ assertEquals(Float.NEGATIVE_INFINITY, Float.parseFloat("-1.0e+39"));
+
+ assertEquals(Float.POSITIVE_INFINITY, Float.parseFloat("1.0e+9999999999"));
+ assertEquals(Float.NEGATIVE_INFINITY, Float.parseFloat("-1.0e+9999999999"));
+ assertEquals(0.0f, Float.parseFloat("1.0e-9999999999"));
+ assertEquals(-0.0f, Float.parseFloat("-1.0e-9999999999"));
+
+ assertEquals(Float.POSITIVE_INFINITY, Float.parseFloat("320.0E+2147483647"));
+ assertEquals(-0.0f, Float.parseFloat("-1.4E-2147483314"));
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/OldStringBufferTest.java b/luni/src/test/java/libcore/java/lang/OldStringBufferTest.java
index 84828c4..f81ce5e 100644
--- a/luni/src/test/java/libcore/java/lang/OldStringBufferTest.java
+++ b/luni/src/test/java/libcore/java/lang/OldStringBufferTest.java
@@ -17,7 +17,9 @@
package libcore.java.lang;
-public class OldStringBufferTest extends junit.framework.TestCase {
+import junit.framework.TestCase;
+
+public class OldStringBufferTest extends TestCase {
StringBuffer testBuffer = new StringBuffer("This is a test buffer");
@@ -38,19 +40,9 @@
}
public void test_ensureCapacityI() {
- // Test for method void java.lang.StringBuffer.ensureCapacity(int)
StringBuffer sb = new StringBuffer(10);
-
sb.ensureCapacity(-2);
assertEquals("Failed to increase capacity.", 10, sb.capacity());
-
-
- try {
- sb.ensureCapacity(Integer.MAX_VALUE);
- fail("OutOfMemoryError should be thrown.");
- } catch(java.lang.OutOfMemoryError oome) {
- //expected
- }
}
public void test_getCharsII$CI() {
diff --git a/luni/src/test/java/libcore/java/lang/OldThreadGroupTest.java b/luni/src/test/java/libcore/java/lang/OldThreadGroupTest.java
index 5fe81a8..eda3bcf 100644
--- a/luni/src/test/java/libcore/java/lang/OldThreadGroupTest.java
+++ b/luni/src/test/java/libcore/java/lang/OldThreadGroupTest.java
@@ -17,7 +17,11 @@
package libcore.java.lang;
-import java.util.Vector;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import junit.framework.TestCase;
public class OldThreadGroupTest extends TestCase implements Thread.UncaughtExceptionHandler {
@@ -118,67 +122,43 @@
inListOfThreads(listOfThreads));
}
- public void test_enumerateLThreadArrayLZtest_enumerateLThreadArrayLZ() {
- int numThreads = initialThreadGroup.activeCount();
- Thread[] listOfThreads = new Thread[numThreads];
+ public void test_enumerateLThreadArrayLZtest_enumerateLThreadArrayLZ() throws Exception {
+ // capture the initial condition
+ int initialThreadCount = initialThreadGroup.activeCount();
+ Thread[] initialThreads = new Thread[initialThreadCount];
+ assertEquals(initialThreadCount, initialThreadGroup.enumerate(initialThreads, false));
+ assertEquals(initialThreadCount, initialThreadGroup.enumerate(initialThreads, true));
+ assertTrue(inListOfThreads(initialThreads));
- int countThread = initialThreadGroup.enumerate(listOfThreads, false);
- assertEquals(numThreads, countThread);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, true);
- assertEquals(numThreads, countThread);
- assertTrue("Current thread must be in enumeration of threads",
- inListOfThreads(listOfThreads));
-
- ThreadGroup subGroup = new ThreadGroup(initialThreadGroup, "Test Group 1");
- int subThreadsCount = 3;
- Vector<MyThread> subThreads = populateGroupsWithThreads(subGroup,
- subThreadsCount);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, true);
- assertEquals(numThreads, countThread);
- assertTrue("Current thread must be in enumeration of threads",
- inListOfThreads(listOfThreads));
-
- for(MyThread thr:subThreads) {
- thr.start();
+ // start some the threads and see how the count changes
+ ThreadGroup group = new ThreadGroup(initialThreadGroup, "enumerateThreadArray");
+ int groupSize = 3;
+ List<MyThread> newThreads = populateGroupsWithThreads(group, groupSize);
+ assertEquals(initialThreadCount, initialThreadGroup.enumerate(initialThreads, true));
+ assertTrue(inListOfThreads(initialThreads));
+ for(MyThread thread : newThreads) {
+ thread.start();
}
- // lets give them some time to start
- try {
- Thread.sleep(500);
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
+ Thread.sleep(500); // starting threads isn't instant!
+ int afterStartCount = initialThreadGroup.activeCount();
+ Set<Thread> initialPlusNew = new HashSet<Thread>();
+ initialPlusNew.addAll(Arrays.asList(initialThreads));
+ initialPlusNew.addAll(newThreads);
+ Thread[] afterStartThreads = new Thread[afterStartCount];
+ assertEquals(afterStartCount, initialThreadGroup.enumerate(afterStartThreads, true));
+ assertEquals(initialPlusNew, new HashSet<Thread>(Arrays.asList(afterStartThreads)));
+ assertTrue(inListOfThreads(afterStartThreads));
+
+ // kill the threads and count 'em again
+ for(MyThread thread : newThreads) {
+ thread.interrupt();
}
-
- int numThreads2 = initialThreadGroup.activeCount();
- listOfThreads = new Thread[numThreads2];
-
- assertEquals(numThreads + subThreadsCount, numThreads2);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, true);
- assertEquals(numThreads2, countThread);
- assertTrue("Current thread must be in enumeration of threads",
- inListOfThreads(listOfThreads));
-
- for(MyThread thr:subThreads) {
- thr.interrupt();
- }
- // lets give them some time to die
- try {
- Thread.sleep(500);
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
- }
-
- int numThreads3 = initialThreadGroup.activeCount();
- listOfThreads = new Thread[numThreads3];
-
- assertEquals(numThreads, numThreads3);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, false);
- assertEquals(numThreads3, countThread);
- assertTrue("Current thread must be in enumeration of threads",
- inListOfThreads(listOfThreads));
+ Thread.sleep(500); // killing threads isn't instant
+ int afterDeathCount = initialThreadGroup.activeCount();
+ Thread[] afterDeathThreads = new Thread[afterDeathCount];
+ assertEquals(afterDeathCount, initialThreadGroup.enumerate(afterDeathThreads, false));
+ assertEquals(Arrays.asList(initialThreads), Arrays.asList(afterDeathThreads));
+ assertTrue(inListOfThreads(afterDeathThreads));
}
public void test_enumerateLThreadGroupArray() {
@@ -204,7 +184,7 @@
public void test_enumerateLThreadGroupArrayLZ() {
ThreadGroup thrGroup = new ThreadGroup("Test Group 1");
- Vector<MyThread> subThreads = populateGroupsWithThreads(thrGroup, 3);
+ List<MyThread> subThreads = populateGroupsWithThreads(thrGroup, 3);
int numGroupThreads = thrGroup.activeGroupCount();
ThreadGroup[] listOfGroups = new ThreadGroup[numGroupThreads];
@@ -222,7 +202,7 @@
assertEquals(0, thrGroup.enumerate(listOfGroups, false));
ThreadGroup subGroup1 = new ThreadGroup(thrGroup, "Test Group 2");
- Vector<MyThread> subThreads1 = populateGroupsWithThreads(subGroup1, 3);
+ List<MyThread> subThreads1 = populateGroupsWithThreads(subGroup1, 3);
numGroupThreads = thrGroup.activeGroupCount();
listOfGroups = new ThreadGroup[numGroupThreads];
@@ -243,7 +223,7 @@
}
ThreadGroup subGroup2 = new ThreadGroup(subGroup1, "Test Group 3");
- Vector<MyThread> subThreads2 = populateGroupsWithThreads(subGroup2, 3);
+ List<MyThread> subThreads2 = populateGroupsWithThreads(subGroup2, 3);
numGroupThreads = thrGroup.activeGroupCount();
listOfGroups = new ThreadGroup[numGroupThreads];
@@ -356,7 +336,7 @@
}
private ThreadGroup[] groups(ThreadGroup parent) {
- // No API to get the count of immediate children only ?
+ // No API to get the count of immediate children only
int count = parent.activeGroupCount();
ThreadGroup[] all = new ThreadGroup[count];
parent.enumerate(all, false);
@@ -367,42 +347,24 @@
break;
}
}
- ThreadGroup[] result;
- if (actualSize == all.length) {
- result = all;
- } else {
- result = new ThreadGroup[actualSize];
- System.arraycopy(all, 0, result, 0, actualSize);
- }
-
- return result;
-
+ return Arrays.copyOfRange(all, 0, actualSize);
}
- private Vector<MyThread> populateGroupsWithThreads(final ThreadGroup aGroup,
- final int threadCount) {
- Vector<MyThread> result = new Vector<MyThread>();
- populateGroupsWithThreads(aGroup, threadCount, result);
+ private List<MyThread> populateGroupsWithThreads(ThreadGroup group, int threadCount) {
+ List<MyThread> result = new ArrayList<MyThread>();
+ populateGroupsWithThreads(group, threadCount, result);
return result;
-
}
- private void populateGroupsWithThreads(final ThreadGroup aGroup,
- final int threadCount, final Vector<MyThread> allCreated) {
+ private void populateGroupsWithThreads(ThreadGroup group, int threadCount, List<MyThread> out) {
for (int i = 0; i < threadCount; i++) {
- final int iClone = i;
- final String name = "(MyThread)N =" + iClone + "/" + threadCount
- + " ,Vector size at creation: " + allCreated.size();
-
- MyThread t = new MyThread(aGroup, name);
- allCreated.addElement(t);
+ out.add(new MyThread(group, "MyThread " + i + " of " + threadCount));
}
// Recursively for subgroups (if any)
- ThreadGroup[] children = groups(aGroup);
+ ThreadGroup[] children = groups(group);
for (ThreadGroup element : children) {
- populateGroupsWithThreads(element, threadCount, allCreated);
+ populateGroupsWithThreads(element, threadCount, out);
}
-
}
}
diff --git a/luni/src/test/java/libcore/java/lang/OldThreadTest.java b/luni/src/test/java/libcore/java/lang/OldThreadTest.java
index 1094d33..b2b2a13 100644
--- a/luni/src/test/java/libcore/java/lang/OldThreadTest.java
+++ b/luni/src/test/java/libcore/java/lang/OldThreadTest.java
@@ -116,7 +116,7 @@
try {
Thread.sleep(100);
LockSupport.unpark(parker);
- } catch (InterruptedException ignored) {
+ } catch (InterruptedException expected) {
}
}
}
diff --git a/luni/src/test/java/libcore/java/lang/StringTest.java b/luni/src/test/java/libcore/java/lang/StringTest.java
index 799e8db..5451a63 100644
--- a/luni/src/test/java/libcore/java/lang/StringTest.java
+++ b/luni/src/test/java/libcore/java/lang/StringTest.java
@@ -26,6 +26,7 @@
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.Arrays;
+import java.util.Locale;
import junit.framework.TestCase;
public class StringTest extends TestCase {
@@ -212,4 +213,96 @@
static class HasLiteral {
static String literal = "[5058, 9962, 1563, 5744]";
}
+
+ private static final String LATIN_CAPITAL_I = "I";
+ private static final String LATIN_CAPITAL_I_WITH_DOT_ABOVE = "\u0130";
+ private static final String LATIN_SMALL_I = "i";
+ private static final String LATIN_SMALL_DOTLESS_I = "\u0131";
+
+ private static final String[] LATIN_I_VARIANTS = {
+ LATIN_SMALL_I,
+ LATIN_SMALL_DOTLESS_I,
+ LATIN_CAPITAL_I,
+ LATIN_CAPITAL_I_WITH_DOT_ABOVE,
+ };
+
+ public void testCaseMapping_tr_TR() {
+ Locale trTR = new Locale("tr", "TR");
+ assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(trTR));
+ assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(trTR));
+ assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(trTR));
+
+ assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(trTR));
+ assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(trTR));
+ assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_SMALL_I.toUpperCase(trTR));
+
+ assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(trTR));
+ assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_CAPITAL_I.toLowerCase(trTR));
+ }
+
+ public void testCaseMapping_en_US() {
+ Locale enUs = new Locale("en", "US");
+ assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_I.toUpperCase(enUs));
+ assertEquals(LATIN_CAPITAL_I, LATIN_CAPITAL_I.toUpperCase(enUs));
+ assertEquals(LATIN_CAPITAL_I_WITH_DOT_ABOVE, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toUpperCase(enUs));
+
+ assertEquals(LATIN_SMALL_I, LATIN_SMALL_I.toLowerCase(enUs));
+ assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I.toLowerCase(enUs));
+ assertEquals(LATIN_SMALL_DOTLESS_I, LATIN_SMALL_DOTLESS_I.toLowerCase(enUs));
+
+ assertEquals(LATIN_CAPITAL_I, LATIN_SMALL_DOTLESS_I.toUpperCase(enUs));
+ // http://b/3325799: Android fails this with an extra combining "dot above".
+ assertEquals(LATIN_SMALL_I, LATIN_CAPITAL_I_WITH_DOT_ABOVE.toLowerCase(enUs));
+ }
+
+ public void testEqualsIgnoreCase_tr_TR() {
+ testEqualsIgnoreCase(new Locale("tr", "TR"));
+ }
+
+ public void testEqualsIgnoreCase_en_US() {
+ testEqualsIgnoreCase(new Locale("en", "US"));
+ }
+
+ /**
+ * String.equalsIgnoreCase should not depend on the locale.
+ */
+ private void testEqualsIgnoreCase(Locale locale) {
+ Locale defaultLocale = Locale.getDefault();
+ Locale.setDefault(locale);
+ try {
+ for (String a : LATIN_I_VARIANTS) {
+ for (String b : LATIN_I_VARIANTS) {
+ if (!a.equalsIgnoreCase(b)) {
+ fail("Expected " + a + " to equal " + b + " in " + locale);
+ }
+ }
+ }
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
+ public void testRegionMatches_ignoreCase_en_US() {
+ testRegionMatches_ignoreCase(new Locale("en", "US"));
+ }
+
+ public void testRegionMatches_ignoreCase_tr_TR() {
+ testRegionMatches_ignoreCase(new Locale("tr", "TR"));
+ }
+
+ private void testRegionMatches_ignoreCase(Locale locale) {
+ Locale defaultLocale = Locale.getDefault();
+ Locale.setDefault(locale);
+ try {
+ for (String a : LATIN_I_VARIANTS) {
+ for (String b : LATIN_I_VARIANTS) {
+ if (!a.regionMatches(true, 0, b, 0, b.length())) {
+ fail("Expected " + a + " to equal " + b + " in " + locale);
+ }
+ }
+ }
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java b/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java
index 21d9cc2..907b8eb 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/OldGenericReflectionCornerCases.java
@@ -17,10 +17,6 @@
package libcore.java.lang.reflect;
import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@@ -33,7 +29,6 @@
* type parameters, equality of type parameters, wildcard types, parameterized
* types and multiple bounds.
*/
-@TestTargetClass(Method.class)
public class OldGenericReflectionCornerCases extends GenericReflectionTestsBase {
static class Pair<T, S> {}
@@ -41,20 +36,6 @@
static class WildcardEquality<T> {
void wildcardEquality(Pair<? extends T, ? extends T> param) {}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
@SuppressWarnings("unchecked")
public void testWildcardEquality() throws Exception {
Class<? extends WildcardEquality> clazz = WildcardEquality.class;
@@ -98,20 +79,6 @@
static class WildcardUnEquality<T> {
void wildcardUnEquality(Pair<? extends T, ? super T> param) {}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
@SuppressWarnings("unchecked")
public void testWildcardUnEquality() throws Exception {
Class<? extends WildcardUnEquality> clazz = WildcardUnEquality.class;
@@ -154,20 +121,6 @@
static class MultipleBoundedWildcardUnEquality<T extends Object & Comparable<MultipleBoundedWildcardUnEquality<T>>> {
void multipleBoundedWildcardUnEquality(Pair<? extends T, ? super T> param) {}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
@SuppressWarnings("unchecked")
@KnownFailure("Fails in CTS but passes under run-core-tests")
public void testMultipleBoundedWildcardUnEquality() throws Exception {
@@ -224,20 +177,6 @@
static class MultipleBoundedWildcardEquality<T extends Object & Comparable<MultipleBoundedWildcardEquality<T>>> {
void multipleBoundedWildcardEquality(Pair<? extends T, ? extends T> param) {}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
@SuppressWarnings("unchecked")
@KnownFailure("Fails in CTS but passes under run-core-tests")
public void testMultipleBoundedWildcard() throws Exception {
diff --git a/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java b/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java
index aad08e1..f93b683 100644
--- a/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java
+++ b/luni/src/test/java/libcore/java/lang/reflect/OldGenericTypesTest.java
@@ -17,9 +17,6 @@
package libcore.java.lang.reflect;
import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
@@ -31,7 +28,6 @@
/**
* Tests type parameters declared on classes.
*/
-@TestTargetClass(Constructor.class)
public class OldGenericTypesTest extends GenericReflectionTestsBase {
static class GenericType<T>{
@@ -66,12 +62,6 @@
}
static interface InterfaceTest<T>{}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Check positive functionality.",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testConstructorGenericType() throws Exception {
Class<? extends ConstructorGenericType> clazz = ConstructorGenericType.class;
@@ -83,12 +73,6 @@
assertEquals(typeVariable, parameterType);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testStaticMethodGenericType() throws Exception {
Class<? extends GenericType> clazz = GenericType.class;
@@ -102,12 +86,6 @@
assertInstanceOf(TypeVariable.class, parameterType);
assertEquals(method, ((TypeVariable)parameterType).getGenericDeclaration());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testHidingMethodGenericType() throws Exception {
Class<? extends GenericType> clazz = GenericType.class;
@@ -127,12 +105,6 @@
void multipleGenericTypesS(S s){}
void multipleGenericTypesTS(T t, S s){}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testMultipleGenericTypes() throws Exception {
//Type parameters
@@ -170,12 +142,6 @@
assertEquals(typeVariableS, multipleGenericTypesTSTypeS);
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testMultipleBoundedGenericTypes() throws Exception {
//Type parameters
@@ -193,12 +159,6 @@
Type boundS = boundsS[0];
assertEquals(typeVariableT, boundS);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
@KnownFailure("Fails in CTS but passes under run-core-tests")
public void testSimpleInheritance() throws Exception {
@@ -221,12 +181,6 @@
TypeVariable actualSuperTypeVariable = (TypeVariable) actualTypeArguments[0];
assertEquals(subTypeVariable, actualSuperTypeVariable);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check exceptions.",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testInnerClassTest() throws Exception {
Class<? extends InnerClassTest> clazz =InnerClassTest.class;
@@ -257,12 +211,6 @@
TypeVariable<?> methodTypeVariable = (TypeVariable<?>) methodParameterTypes[0];
assertEquals(clazz, methodTypeVariable.getGenericDeclaration());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Exceptions are not verified.",
- method = "getGenericExceptionTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void testException() throws Exception {
Class<? extends ExceptionTest> clazz = ExceptionTest.class;
diff --git a/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
index 02d7c8e..de9caa9 100644
--- a/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
+++ b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
@@ -16,11 +16,6 @@
package libcore.java.net;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
import junit.framework.TestCase;
import java.net.FileNameMap;
@@ -43,4 +38,3 @@
}
}
}
-
diff --git a/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java b/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
index 71e2176..d292414 100644
--- a/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
+++ b/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
@@ -16,10 +16,6 @@
package libcore.java.net;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -43,43 +39,15 @@
import tests.support.Support_TestWebData;
import tests.support.Support_TestWebServer;
-@TestTargetClass(value = ResponseCache.class)
public class OldResponseCacheTest extends TestCase {
- /**
- * @tests java.net.ResponseCache#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
public void test_GetDefault() throws Exception {
assertNull(ResponseCache.getDefault());
}
- /**
- * @tests java.net.ResponseCache#setDefault(ResponseCache)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ResponseCache.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "ResponseCache",
- args = {}
- )
- })
- public void test_SetDefaultLjava_net_ResponseCache_Normal()
- throws Exception {
+ public void test_SetDefaultLjava_net_ResponseCache_Normal() throws Exception {
ResponseCache rc1 = new MockResponseCache();
ResponseCache rc2 = new MockResponseCache();
ResponseCache.setDefault(rc1);
@@ -90,12 +58,6 @@
assertNull(ResponseCache.getDefault());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {URI.class, String.class, Map.class}
- )
public void test_get() throws Exception {
String uri = "http://localhost/";
URL url = new URL(uri);
@@ -118,12 +80,6 @@
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {URI.class, URLConnection.class}
- )
public void test_put() throws Exception {
// Create test ResponseCache
TestResponseCache cache = new TestResponseCache(
diff --git a/luni/src/test/java/libcore/java/net/OldSocketTest.java b/luni/src/test/java/libcore/java/net/OldSocketTest.java
index 68105ce..6247719 100644
--- a/luni/src/test/java/libcore/java/net/OldSocketTest.java
+++ b/luni/src/test/java/libcore/java/net/OldSocketTest.java
@@ -747,12 +747,8 @@
int portNumber = Support_PortManager.getNextPort();
s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
InetAddress.getLocalHost(), portNumber);
- assertTrue("Returned incorrect string: " + s.toString()
- + " localHost: " + InetAddress.getLocalHost(), s.toString()
- .equals(
- "Socket[addr=" + InetAddress.getLocalHost() + ",port="
- + s.getPort() + ",localport="
- + s.getLocalPort() + "]"));
+ assertEquals("Socket[address=" + InetAddress.getLocalHost() + ",port=" + s.getPort()
+ + ",localPort=" + s.getLocalPort() + "]", s.toString());
}
// AndroidOnly: RI returns wrong value for EOF
diff --git a/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java b/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java
index 71fb962..35c7f7e 100644
--- a/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLClassLoaderTest.java
@@ -18,9 +18,6 @@
package libcore.java.net;
import dalvik.annotation.SideEffect;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -43,17 +40,6 @@
import tests.support.Support_TestWebServer;
import tests.support.resource.Support_Resources;
-@TestTargetClass(
- value = URLClassLoader.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "findClass uses defineClass which is not implemented",
- method = "findClass",
- args = {java.lang.String.class}
- )
- }
-)
public class OldURLClassLoaderTest extends junit.framework.TestCase {
URLClassLoader ucl;
@@ -142,12 +128,6 @@
assertEquals("Incorrect number of resources returned", 2, i);
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addURL",
- args = { URL.class }
- )
public void test_addURLLjava_net_URL() throws MalformedURLException {
URL[] u = new URL[0];
@@ -243,15 +223,6 @@
}
}
- /**
- * @tests java.net.URLClassLoader#findResource(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "findResource",
- args = {java.lang.String.class}
- )
@SideEffect("Support_TestWebServer requires isolation.")
public void test_findResourceLjava_lang_String() throws Exception {
int port = Support_PortManager.getNextPort();
@@ -278,12 +249,6 @@
/**
* Regression for Harmony-2237
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test",
- method = "findResource",
- args = {java.lang.String.class}
- )
@SideEffect("Support_TestWebServer requires isolation.")
public void test_findResource_String() throws Exception {
File tempFile1 = File.createTempFile("textFile", ".txt");
diff --git a/luni/src/test/java/libcore/java/net/OldURLDecoderTest.java b/luni/src/test/java/libcore/java/net/OldURLDecoderTest.java
deleted file mode 100644
index 86a2961..0000000
--- a/luni/src/test/java/libcore/java/net/OldURLDecoderTest.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 libcore.java.net;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import junit.framework.TestCase;
-import tests.support.Support_Configuration;
-
-public class OldURLDecoderTest extends TestCase {
-
- public void test_decodeLjava_lang_String_Ljava_lang_String() {
- String enc = "UTF-8";
-
- String [] urls = { "http://" + Support_Configuration.HomeAddress +
- "/test?hl=en&q=te+st",
- "file://a+b/c/d.e-f*g_+l",
- "jar:file://a.jar+!/b.c/",
- "ftp://test:pwd@localhost:2121/%D0%9C",
- "%D0%A2%D0%B5%D1%81%D1%82+URL+for+test"};
-
- String [] expected = {"http://" + Support_Configuration.HomeAddress +
- "/test?hl=en&q=te st",
- "file://a b/c/d.e-f*g_ l",
- "jar:file://a.jar !/b.c/"};
-
- for(int i = 0; i < urls.length - 2; i++) {
- try {
- assertEquals(expected[i], URLDecoder.decode(urls[i], enc));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
- }
-
- try {
- URLDecoder.decode(urls[urls.length - 2], enc);
- URLDecoder.decode(urls[urls.length - 1], enc);
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/net/OldURLEncoderTest.java b/luni/src/test/java/libcore/java/net/OldURLEncoderTest.java
deleted file mode 100644
index 8616e2c..0000000
--- a/luni/src/test/java/libcore/java/net/OldURLEncoderTest.java
+++ /dev/null
@@ -1,67 +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 libcore.java.net;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import junit.framework.TestCase;
-import tests.support.Support_Configuration;
-
-public class OldURLEncoderTest extends TestCase {
-
- public void test_encodeLjava_lang_StringLjava_lang_String() {
-
- String enc = "UTF-8";
-
- String [] urls = {"http://" + Support_Configuration.HomeAddress +
- "/test?hl=en&q=te st",
- "file://a b/c/d.e-f*g_ l",
- "jar:file://a.jar !/b.c/\u1052",
- "ftp://test:pwd@localhost:2121/%D0%9C"};
-
- String [] expected = { "http%3A%2F%2Fjcltest.apache.org%2Ftest%3Fhl%" +
- "3Den%26q%3Dte+st",
- "file%3A%2F%2Fa+b%2Fc%2Fd.e-f*g_+l",
- "jar%3Afile%3A%2F%2Fa.jar+%21%2Fb.c%2F%E1%81%92"};
-
- for(int i = 0; i < urls.length-1; i++) {
- try {
- String encodedString = URLEncoder.encode(urls[i], enc);
- assertEquals(expected[i], encodedString);
- assertEquals(urls[i], URLDecoder.decode(encodedString, enc));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
- }
-
- try {
- String encodedString = URLEncoder.encode(urls[urls.length - 1], enc);
- assertEquals(urls[urls.length - 1], URLDecoder.decode(encodedString, enc));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
-
- try {
- URLDecoder.decode("", "");
- fail("UnsupportedEncodingException expected");
- } catch (UnsupportedEncodingException e) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java b/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
index 51d6001..a47d833 100644
--- a/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
@@ -78,10 +78,8 @@
}
public void test_hostsEqualLjava_net_URLLjava_net_URL() throws Exception {
- String loopback = getLoopbackAddressAsHost();
-
URL url1 = new URL("ftp://localhost:21/*test");
- URL url2 = new URL("http://" + loopback + "/_test");
+ URL url2 = new URL("http://localhost/_test");
assertTrue(handler.hostsEqual(url1, url2));
URL url3 = new URL("http://foo/_test_goo");
@@ -118,13 +116,11 @@
}
public void test_sameFile() throws Exception {
- String loopback = getLoopbackAddressAsHost();
-
URL url1 = new URL("http://test:pwd@localhost:80/foo/foo1.c");
- URL url2 = new URL("http://test:pwd@" + loopback + ":80/foo/foo1.c");
- URL url3 = new URL("http://test:pwd@" + loopback + ":80/foo/foo2.c");
- URL url4 = new URL("ftp://test:pwd@" + loopback + ":21/foo/foo2.c");
- URL url5 = new URL("ftp://test:pwd@" + loopback + ":21/foo/foo1/foo2.c");
+ URL url2 = new URL("http://test:pwd@localhost:80/foo/foo1.c");
+ URL url3 = new URL("http://test:pwd@localhost:80/foo/foo2.c");
+ URL url4 = new URL("ftp://test:pwd@localhost:21/foo/foo2.c");
+ URL url5 = new URL("ftp://test:pwd@localhost:21/foo/foo1/foo2.c");
URL url6 = new URL("http://test/foo/foo1.c");
assertTrue("Test case 1", handler.sameFile(url1, url2));
@@ -175,53 +171,45 @@
handler = new MockURLStreamHandler();
}
- private String getLoopbackAddressAsHost() throws UnknownHostException {
- InetAddress localhost = InetAddress.getByName("localhost");
- return localhost instanceof Inet6Address
- ? "[" + localhost.getHostAddress() + "]"
- : localhost.getHostAddress();
- }
-
class MockURLStreamHandler extends URLStreamHandler {
- @Override
- protected URLConnection openConnection(URL arg0) throws IOException {
+ @Override protected URLConnection openConnection(URL arg0) throws IOException {
return null;
}
- public boolean equals(URL u1, URL u2) {
- return super.equals(u1, u2);
+ @Override public boolean equals(URL a, URL b) {
+ return super.equals(a, b);
}
- public int getDefaultPort() {
+ @Override public int getDefaultPort() {
return super.getDefaultPort();
}
- public InetAddress getHostAddress(URL u) {
+ @Override public InetAddress getHostAddress(URL u) {
return super.getHostAddress(u);
}
- public int hashCode(URL u) {
+ @Override public int hashCode(URL u) {
return super.hashCode(u);
}
- public boolean hostsEqual(URL u1, URL u2) {
- return super.hostsEqual(u1, u2);
+ @Override public boolean hostsEqual(URL a, URL b) {
+ return super.hostsEqual(a, b);
}
- public URLConnection openConnection(URL u, Proxy p) throws IOException {
+ @Override public URLConnection openConnection(URL u, Proxy p) throws IOException {
return super.openConnection(u, p);
}
- public void parseURL(URL u, String spec, int start, int limit) {
+ @Override public void parseURL(URL u, String spec, int start, int limit) {
super.parseURL(u, spec, start, limit);
}
- public boolean sameFile(URL u1, URL u2) {
- return super.sameFile(u1, u2);
+ @Override public boolean sameFile(URL a, URL b) {
+ return super.sameFile(a, b);
}
- public void setURL(URL u,
+ @Override public void setURL(URL u,
String protocol,
String host,
int port,
@@ -230,7 +218,7 @@
super.setURL(u, protocol, host, port, file, ref);
}
- public void setURL(URL u,
+ @Override public void setURL(URL u,
String protocol,
String host,
int port,
@@ -243,7 +231,7 @@
userInfo, path, query, ref);
}
- public String toExternalForm(URL u) {
+ @Override public String toExternalForm(URL u) {
return super.toExternalForm(u);
}
}
diff --git a/luni/src/test/java/libcore/java/net/OldURLTest.java b/luni/src/test/java/libcore/java/net/OldURLTest.java
index 07a03af..58caf2e 100644
--- a/luni/src/test/java/libcore/java/net/OldURLTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLTest.java
@@ -16,9 +16,6 @@
package libcore.java.net;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
@@ -43,7 +40,6 @@
import java.util.List;
import junit.framework.TestCase;
-@TestTargetClass(URL.class)
public class OldURLTest extends TestCase {
private static final String helloWorldString = "Hello World";
@@ -56,15 +52,6 @@
super.tearDown();
}
- /**
- * @tests java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class}
- )
public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_String()
throws MalformedURLException {
// Regression for HARMONY-83
@@ -77,16 +64,6 @@
}
}
- /**
- * @tests java.net.URL#URL(java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() throws MalformedURLException {
// Strange behavior in reference, the hostname contains a ':' so it gets wrapped in '[', ']'
URL testURL = new URL("http", "www.apache.org:8082", "test.html#anch");
@@ -104,16 +81,6 @@
}
}
- /**
- * @tests java.net.URL#URL(String, String, String)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test.",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_java_protocol_handler_pkgs_prop() throws MalformedURLException {
// Regression test for Harmony-3094
final String HANDLER_PKGS = "java.protocol.handler.pkgs";
@@ -126,15 +93,6 @@
}
}
- /**
- * Test method for {@link java.net.URL#hashCode()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
public void testHashCode() throws MalformedURLException {
URL testURL1 = new URL("http", "www.apache.org:8080", "test.html#anch");
URL testURL2 = new URL("http", "www.apache.org:8080", "test.html#anch");
@@ -146,15 +104,6 @@
.hashCode() == changedURL.hashCode());
}
- /**
- * Test method for {@link java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "cannot test since no sophisticated StreamHandlerFactory available.",
- method = "setURLStreamHandlerFactory",
- args = {java.net.URLStreamHandlerFactory.class}
- )
public void testSetURLStreamHandlerFactory() throws MalformedURLException, IOException, IllegalArgumentException, IllegalAccessException {
URLStreamHandlerFactory factory = new MyURLStreamHandlerFactory();
Field streamHandlerFactoryField = null;
@@ -199,15 +148,6 @@
}
- /**
- * Test method for {@link java.net.URL#URL(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URL",
- args = {java.lang.String.class}
- )
public void testURLString() throws MalformedURLException {
URL testURL = new URL("ftp://myname@host.dom/etc/motd");
@@ -227,15 +167,6 @@
}
- /**
- * Test method for {@link java.net.URL#URL(java.net.URL, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URL",
- args = {java.net.URL.class, java.lang.String.class}
- )
public void testURLURLString() throws MalformedURLException {
URL gamelan = new URL("http://www.gamelan.com/pages/");
@@ -282,15 +213,6 @@
}
}
- /**
- * Test method for {@link java.net.URL#equals(java.lang.Object)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
public void testEqualsObject() throws MalformedURLException {
URL testURL1 = new URL("http", "www.apache.org", 8080, "test.html");
URL wrongProto = new URL("ftp", "www.apache.org", 8080, "test.html");
@@ -310,15 +232,6 @@
assertTrue("Assert 4: error in equals: same", testURL3.equals(testURL4));
}
- /**
- * Test method for {@link java.net.URL#sameFile(java.net.URL)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "non trivial reference test fails",
- method = "sameFile",
- args = {java.net.URL.class}
- )
public void testSameFile() throws MalformedURLException {
URL gamelan = new URL("file:///pages/index.html");
URL gamelanFalse = new URL("file:///pages/out/index.html");
@@ -335,15 +248,6 @@
assertFalse(url.sameFile(url1));
}
- /**
- * Test method for {@link java.net.URL#getContent()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "image and sound content not testable: mime types",
- method = "getContent",
- args = {}
- )
public void testGetContent() throws MalformedURLException {
File sampleFile = createTempHelloWorldFile();
@@ -371,15 +275,6 @@
}
- /**
- * Test method for {@link java.net.URL#openStream()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openStream",
- args = {}
- )
public void testOpenStream() throws MalformedURLException, IOException {
File sampleFile = createTempHelloWorldFile();
@@ -422,15 +317,6 @@
}
}
- /**
- * Test method for {@link java.net.URL#openConnection()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openConnection",
- args = {}
- )
public void testOpenConnection() throws MalformedURLException, IOException {
File sampleFile = createTempHelloWorldFile();
@@ -458,15 +344,6 @@
}
}
- /**
- * Test method for {@link java.net.URL#toURI()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toURI",
- args = {}
- )
public void testToURI() throws MalformedURLException, URISyntaxException {
String testHTTPURLString = "http://www.gamelan.com/pages/";
String testFTPURLString = "ftp://myname@host.dom/etc/motd";
@@ -517,15 +394,6 @@
}
}
- /**
- * Test method for {@link java.net.URL#toString()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
public void testToString() throws MalformedURLException {
URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
@@ -536,15 +404,6 @@
assertEquals("http://www.gamelan.com/pages/", testHTTPURL.toString());
}
- /**
- * Test method for {@link java.net.URL#toExternalForm()}.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "simple tests",
- method = "toExternalForm",
- args = {}
- )
public void testToExternalForm() throws MalformedURLException {
URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
@@ -555,15 +414,6 @@
assertEquals("http://www.gamelan.com/pages/", testHTTPURL.toExternalForm());
}
- /**
- * Test method for {@link java.net.URL#getFile()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFile",
- args = {}
- )
public void testGetFile() throws MalformedURLException {
File sampleFile = createTempHelloWorldFile();
@@ -574,15 +424,6 @@
assertEquals(sampleFile.getPath(),fileURL.getFile());
}
- /**
- * Test method for {@link java.net.URL#getPort()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
public void testGetPort() throws MalformedURLException {
URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
@@ -595,15 +436,6 @@
}
- /**
- * Test method for {@link java.net.URL#getProtocol()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProtocol",
- args = {}
- )
public void testGetProtocol() throws MalformedURLException {
URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
URL testHTTPSURL = new URL("https://www.gamelan.com/pages/");
@@ -619,15 +451,6 @@
}
- /**
- * Test method for {@link java.net.URL#getRef()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRef",
- args = {}
- )
public void testGetRef() throws MalformedURLException {
URL gamelan = new URL("http://www.gamelan.com/pages/");
@@ -644,15 +467,6 @@
}
- /**
- * Test method for {@link java.net.URL#getQuery()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getQuery",
- args = {}
- )
public void testGetQuery() throws MalformedURLException {
URL urlQuery = new URL(
"http://www.example.com/index.html?attrib1=value1&attrib2=value&attrib3#anchor");
@@ -665,15 +479,6 @@
assertTrue(output == null || "".equals(output));
}
- /**
- * Test method for {@link java.net.URL#getPath()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPath",
- args = {}
- )
public void testGetPath() throws MalformedURLException {
URL url = new URL("http://www.example.com");
String output = url.getPath();
@@ -684,15 +489,6 @@
assertEquals("/foo/index.html",url2.getPath());
}
- /**
- * Test method for {@link java.net.URL#getUserInfo()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUserInfo",
- args = {}
- )
public void testGetUserInfo() throws MalformedURLException {
URL urlNoUserInfo = new URL("http://www.java2s.com:8080");
URL url = new URL("ftp://myUser:password@host.dom/etc/motd");
@@ -702,15 +498,6 @@
assertTrue("".equals(userInfo) || null == userInfo);
}
- /**
- * Test method for {@link java.net.URL#getAuthority()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAuthority",
- args = {}
- )
public void testGetAuthority() throws MalformedURLException, URISyntaxException {
// legal authority information userInfo (user,password),domain,port
@@ -727,15 +514,6 @@
assertTrue("".equals(output) || null == output);
}
- /**
- * Test method for {@link java.net.URL#getDefaultPort()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultPort",
- args = {}
- )
public void testGetDefaultPort() throws MalformedURLException {
URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
@@ -873,15 +651,6 @@
}
}
- /**
- * Test method for {@link java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String, java.net.URLStreamHandler)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch. No meaningful MalformedURLException foundwhich doesn't end as a NullPointerException.",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.net.URLStreamHandler.class}
- )
public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
throws Exception {
u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", null);
@@ -918,15 +687,6 @@
}
- /**
- * Test method for {@link java.net.URL#getContent(java.lang.Class[])}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "throws unexpected exception: NullPointerException in first execution",
- method = "getContent",
- args = {java.lang.Class[].class}
- )
public void test_getContent_LJavaLangClass() throws Exception {
File sampleFile = createTempHelloWorldFile();
@@ -965,15 +725,6 @@
}
- /**
- * Test method for {@link java.net.URL#URL(java.net.URL, java.lang.String, java.net.URLStreamHandler)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch",
- method = "URL",
- args = {java.net.URL.class, java.lang.String.class, java.net.URLStreamHandler.class}
- )
public void testURLURLStringURLStreamHandler() throws MalformedURLException {
u = new URL("http://www.yahoo.com");
// basic ones
@@ -1030,15 +781,6 @@
}
- /**
- * Test method for {@link java.net.URL#toExternalForm()}.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "From harmony branch",
- method = "toExternalForm",
- args = {}
- )
public void test_toExternalForm_Relative() throws MalformedURLException {
String strURL = "http://a/b/c/d;p?q";
String ref = "?y";
@@ -1046,12 +788,6 @@
assertEquals("http://a/b/c/?y", url.toExternalForm());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "From harmony branch",
- method = "toExternalForm",
- args = {}
- )
public void test_toExternalForm_Absolute() throws MalformedURLException {
String strURL = "http://localhost?name=value";
URL url = new URL(strURL);
diff --git a/luni/src/test/java/libcore/java/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
index 81f23f0..9bc00bc 100644
--- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java
+++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
@@ -39,6 +39,7 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
+import java.net.URLEncoder;
import java.security.Principal;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
@@ -417,7 +418,7 @@
if (responseCode != 401) {
readAscii(conn.getInputStream(), Integer.MAX_VALUE);
}
- } catch (IOException ignored) {
+ } catch (IOException expected) {
}
Set<URI> expectedCachedUris = shouldPut
@@ -1819,6 +1820,8 @@
// beyond ascii
testUrlToUriMapping("\u0080", "%C2%80", "%C2%80", "%C2%80", "%C2%80");
testUrlToUriMapping("\u20ac", "\u20ac", "\u20ac", "\u20ac", "\u20ac");
+ testUrlToUriMapping("\ud842\udf9f",
+ "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f", "\ud842\udf9f");
}
public void testLenientUrlToUriNul() throws Exception {
diff --git a/luni/src/test/java/libcore/java/net/URLTest.java b/luni/src/test/java/libcore/java/net/URLTest.java
index f5091bb..a074705 100644
--- a/luni/src/test/java/libcore/java/net/URLTest.java
+++ b/luni/src/test/java/libcore/java/net/URLTest.java
@@ -16,6 +16,8 @@
package libcore.java.net;
+import java.net.Inet6Address;
+import java.net.InetAddress;
import java.net.URL;
import junit.framework.TestCase;
@@ -40,4 +42,35 @@
assertEquals("foo:bar/baz", url.getRef());
assertEquals(-1, url.getPort());
}
+
+ /**
+ * Android's URL.equals() works as if the network is down. This is different
+ * from the RI, which does potentially slow and inconsistent DNS lookups in
+ * URL.equals.
+ */
+ public void testEqualsDoesNotDoHostnameResolution() throws Exception {
+ for (InetAddress inetAddress : InetAddress.getAllByName("localhost")) {
+ String address = inetAddress.getHostAddress();
+ if (inetAddress instanceof Inet6Address) {
+ address = "[" + address + "]";
+ }
+ URL urlByHostName = new URL("http://localhost/foo?bar=baz#quux");
+ URL urlByAddress = new URL("http://" + address + "/foo?bar=baz#quux");
+ assertFalse("Expected " + urlByHostName + " to not equal " + urlByAddress,
+ urlByHostName.equals(urlByAddress));
+ }
+ }
+
+ public void testEqualsCaseMapping() throws Exception {
+ assertEquals(new URL("HTTP://localhost/foo?bar=baz#quux"),
+ new URL("HTTP://localhost/foo?bar=baz#quux"));
+ assertTrue(new URL("http://localhost/foo?bar=baz#quux").equals(
+ new URL("http://LOCALHOST/foo?bar=baz#quux")));
+ assertFalse(new URL("http://localhost/foo?bar=baz#quux").equals(
+ new URL("http://localhost/FOO?bar=baz#quux")));
+ assertFalse(new URL("http://localhost/foo?bar=baz#quux").equals(
+ new URL("http://localhost/foo?BAR=BAZ#quux")));
+ assertFalse(new URL("http://localhost/foo?bar=baz#quux").equals(
+ new URL("http://localhost/foo?bar=baz#QUUX")));
+ }
}
diff --git a/luni/src/test/java/libcore/java/net/UrlEncodingTest.java b/luni/src/test/java/libcore/java/net/UrlEncodingTest.java
new file mode 100644
index 0000000..6318836
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/UrlEncodingTest.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright (C) 2011 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 java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.IllegalCharsetNameException;
+import java.nio.charset.UnsupportedCharsetException;
+import junit.framework.TestCase;
+
+public final class UrlEncodingTest extends TestCase {
+
+ public void testUriRetainsOriginalEncoding() throws Exception {
+ assertEquals("%61", new URI("http://foo#%61").getRawFragment());
+ }
+
+ /**
+ * URLDecoder and URI disagree on what '+' should decode to.
+ */
+ public void testDecodingPlus() throws Exception {
+ assertEquals("a b", URLDecoder.decode("a+b"));
+ assertEquals("a b", URLDecoder.decode("a+b", "UTF-8"));
+ assertEquals("a+b", new URI("http://foo#a+b").getFragment());
+ }
+
+ public void testEncodingPlus() throws Exception {
+ assertEquals("a%2Bb", URLEncoder.encode("a+b"));
+ assertEquals("a%2Bb", URLEncoder.encode("a+b", "UTF-8"));
+ assertEquals("a+b", new URI("http", "foo", "/", "a+b").getRawFragment());
+ }
+
+ public void testDecodingSpace() throws Exception {
+ assertEquals("a b", URLDecoder.decode("a b"));
+ assertEquals("a b", URLDecoder.decode("a b", "UTF-8"));
+ try {
+ new URI("http://foo#a b");
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ }
+
+ public void testEncodingSpace() throws Exception {
+ assertEquals("a+b", URLEncoder.encode("a b"));
+ assertEquals("a+b", URLEncoder.encode("a b", "UTF-8"));
+ assertEquals("a%20b", new URI("http", "foo", "/", "a b").getRawFragment());
+ }
+
+ public void testUriDecodingPartial() throws Exception {
+ try {
+ new URI("http://foo#%");
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ try {
+ new URI("http://foo#%0");
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ }
+
+ public void testUrlDecoderDecodingPartial() throws Exception {
+ try {
+ URLDecoder.decode("%");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ URLDecoder.decode("%0");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testUriDecodingInvalid() {
+ try {
+ new URI("http://foo#%0g");
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ }
+
+ public void testUrlDecoderDecodingInvalid() {
+ try {
+ URLDecoder.decode("%0g");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void testUrlDecoderFailsOnNullCharset() throws Exception {
+ try {
+ URLDecoder.decode("ab", null);
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testUrlDecoderFailsOnEmptyCharset() {
+ try {
+ URLDecoder.decode("ab", "");
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ } catch (UnsupportedEncodingException expected) {
+ }
+ }
+
+ public void testUrlEncoderFailsOnNullCharset() throws Exception {
+ try {
+ URLEncoder.encode("ab", null);
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testUrlEncoderFailsOnEmptyCharset() {
+ try {
+ URLEncoder.encode("ab", "");
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ } catch (UnsupportedEncodingException expected) {
+ }
+ }
+
+ /**
+ * The RI looks up the charset lazily; Android looks it up eagerly. Either
+ * behavior is acceptable.
+ */
+ public void testUrlDecoderIgnoresUnnecessaryCharset() throws Exception {
+ try {
+ assertEquals("ab", URLDecoder.decode("ab", "no-such-charset"));
+ // no fail()
+ } catch (UnsupportedCharsetException expected) {
+ }
+ }
+
+ public void testUrlEncoderFailsOnInvalidCharset() throws Exception {
+ try {
+ URLEncoder.encode("ab", "no-such-charset");
+ fail();
+ } catch (UnsupportedCharsetException expected) {
+ } catch (UnsupportedEncodingException expected) {
+ }
+ }
+
+ public void testDecoding() throws Exception {
+ assertDecoded("a\u0000b", "a%00b");
+ assertDecoded("a b", "a%20b");
+ assertDecoded("a+b", "a%2bb");
+ assertDecoded("a%b", "a%25b");
+ assertDecoded("a\u007fb", "a%7fb");
+ }
+
+ public void testEncoding() throws Exception {
+ assertEncoded("a%25b", "a%b");
+ assertEncoded("a%7Fb", "a\u007fb");
+ }
+
+ public void testDecodingLiterals() throws Exception {
+ assertDecoded("\ud842\udf9f", "\ud842\udf9f");
+ }
+
+ public void testDecodingBrokenUtf8SequenceYieldsReplacementCharacter() throws Exception {
+ assertDecoded("a\ufffdb", "a%ffb");
+ }
+
+ public void testDecodingUtf8Octets() throws Exception {
+ assertDecoded("\u20AC", "%e2%82%ac");
+ assertDecoded("\ud842\udf9f", "%f0%a0%ae%9f");
+ }
+
+ public void testDecodingNonUsDigits() throws Exception {
+ try {
+ new URI("http://foo#" + "%\u0664\u0661");
+ fail();
+ } catch (URISyntaxException expected) {
+ }
+ try {
+ URLDecoder.decode("%\u0664\u0661");
+ fail(); // RI fails this test returning "A"
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * Android's URLEncoder.encode() failed for surrogate pairs, encoding them
+ * as two replacement characters ("??"). http://b/3436051
+ */
+ public void testUrlEncoderEncodesNonPrintableNonAsciiCharacters() throws Exception {
+ assertEquals("%00", URLEncoder.encode("\u0000", "UTF-8"));
+ assertEquals("%00", URLEncoder.encode("\u0000"));
+ assertEquals("%E2%82%AC", URLEncoder.encode("\u20AC", "UTF-8"));
+ assertEquals("%E2%82%AC", URLEncoder.encode("\u20AC"));
+ assertEquals("%F0%A0%AE%9F", URLEncoder.encode("\ud842\udf9f", "UTF-8"));
+ assertEquals("%F0%A0%AE%9F", URLEncoder.encode("\ud842\udf9f"));
+ }
+
+ public void testUriDoesNotEncodeNonPrintableNonAsciiCharacters() throws Exception {
+ assertEquals("\u20AC", new URI("http", "foo", "/", "\u20AC").getRawFragment());
+ assertEquals("\ud842\udf9f", new URI("http", "foo", "/", "\ud842\udf9f").getRawFragment());
+ }
+
+ public void testUriEncodesControlCharacters() throws Exception {
+ assertEquals("%01", new URI("http", "foo", "/", "\u0001").getRawFragment());
+
+ // The RI fails this, encoding \u0001 but not \u0000
+ assertEquals("%00", new URI("http", "foo", "/", "\u0000").getRawFragment());
+ }
+
+ public void testEncodeAndDecode() throws Exception {
+ assertRoundTrip("http://jcltest.apache.org/test?hl=en&q=te st",
+ "http%3A%2F%2Fjcltest.apache.org%2Ftest%3Fhl%3Den%26q%3Dte+st");
+ assertRoundTrip ("file://a b/c/d.e-f*g_ l",
+ "file%3A%2F%2Fa+b%2Fc%2Fd.e-f*g_+l");
+ assertRoundTrip("jar:file://a.jar !/b.c/\u1052",
+ "jar%3Afile%3A%2F%2Fa.jar+%21%2Fb.c%2F%E1%81%92");
+ assertRoundTrip("ftp://test:pwd@localhost:2121/%D0%9C",
+ "ftp%3A%2F%2Ftest%3Apwd%40localhost%3A2121%2F%25D0%259C");
+ }
+
+ /**
+ * Asserts that {@code original} decodes to {@code decoded} using both URI
+ * and UrlDecoder.
+ */
+ private void assertDecoded(String decoded, String original) throws Exception {
+ assertEquals(decoded, new URI("http://foo#" + original).getFragment());
+ assertEquals(decoded, URLDecoder.decode(original));
+ assertEquals(decoded, URLDecoder.decode(original, "UTF-8"));
+ }
+
+ /**
+ * Asserts that {@code original} encodes to {@code encoded} using both URI
+ * and URLEncoder.
+ */
+ private void assertEncoded(String encoded, String original) throws Exception {
+ assertEquals(encoded, URLEncoder.encode(original, "UTF-8"));
+ assertEquals(encoded, URLEncoder.encode(original));
+ assertEquals(encoded, new URI("http", "foo", "/", original).getRawFragment());
+ }
+
+ private void assertRoundTrip(String original, String encoded) throws Exception {
+ assertEquals(encoded, URLEncoder.encode(original, "UTF-8"));
+ assertEquals(original, URLDecoder.decode(encoded, "UTF-8"));
+ }
+}
diff --git a/luni/src/test/java/libcore/java/nio/BufferTest.java b/luni/src/test/java/libcore/java/nio/BufferTest.java
index ec85235..fd9c0ed 100644
--- a/luni/src/test/java/libcore/java/nio/BufferTest.java
+++ b/luni/src/test/java/libcore/java/nio/BufferTest.java
@@ -416,4 +416,39 @@
b.putShort((short) 0);
assertEquals(2, b.position());
}
+
+ // This test will fail on the RI. Our direct buffers are cooler than theirs.
+ // http://b/3384431
+ public void testDirectByteBufferHasArray() throws Exception {
+ ByteBuffer b = ByteBuffer.allocateDirect(10);
+ assertTrue(b.isDirect());
+ // Check the buffer has an array of the right size.
+ assertTrue(b.hasArray());
+ assertEquals(0, b.arrayOffset());
+ byte[] array = b.array();
+ assertEquals(10, array.length);
+ // Check that writes to the array show up in the buffer.
+ assertEquals(0, b.get(0));
+ array[0] = 1;
+ assertEquals(1, b.get(0));
+ // Check that writes to the buffer show up in the array.
+ assertEquals(1, array[0]);
+ b.put(0, (byte) 0);
+ assertEquals(0, array[0]);
+ }
+
+ public void testSliceOffset() throws Exception {
+ // Slicing changes the array offset.
+ ByteBuffer buffer = ByteBuffer.allocate(10);
+ buffer.get();
+ ByteBuffer slice = buffer.slice();
+ assertEquals(0, buffer.arrayOffset());
+ assertEquals(1, slice.arrayOffset());
+
+ ByteBuffer directBuffer = ByteBuffer.allocateDirect(10);
+ directBuffer.get();
+ ByteBuffer directSlice = directBuffer.slice();
+ assertEquals(0, directBuffer.arrayOffset());
+ assertEquals(1, directSlice.arrayOffset());
+ }
}
diff --git a/luni/src/test/java/libcore/java/nio/NoArrayTest.java b/luni/src/test/java/libcore/java/nio/NoArrayTest.java
index 04d9af1..7654604 100644
--- a/luni/src/test/java/libcore/java/nio/NoArrayTest.java
+++ b/luni/src/test/java/libcore/java/nio/NoArrayTest.java
@@ -21,22 +21,17 @@
import junit.framework.TestCase;
public final class NoArrayTest extends TestCase {
-
- public void testWrappedReadOnly() {
+ public void testReadOnly() {
+ // A read-only buffer must not expose its array.
assertNoArray(ByteBuffer.wrap(new byte[32]).asReadOnlyBuffer());
- }
-
- public void testAllocatedReadOnly() {
assertNoArray(ByteBuffer.allocate(32).asReadOnlyBuffer());
- }
-
- public void testAllocatedDirect() {
- assertNoArray(ByteBuffer.allocateDirect(32));
+ assertNoArray(ByteBuffer.allocateDirect(32).asReadOnlyBuffer());
}
private void assertNoArray(ByteBuffer buf) {
+ assertFalse(buf.hasArray());
try {
- buf.asReadOnlyBuffer().array();
+ buf.array();
fail();
} catch (ReadOnlyBufferException expected) {
} catch (UnsupportedOperationException expected) {
diff --git a/luni/src/test/java/libcore/java/nio/channels/OldFileChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/OldFileChannelTest.java
index 363dbd6..9388888 100644
--- a/luni/src/test/java/libcore/java/nio/channels/OldFileChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/OldFileChannelTest.java
@@ -16,10 +16,6 @@
package libcore.java.nio.channels;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -40,17 +36,6 @@
import java.util.Arrays;
import junit.framework.TestCase;
-@TestTargetClass(
- value = FileChannel.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "empty protected constructor",
- method = "FileChannel",
- args = {}
- )
- }
-)
public final class OldFileChannelTest extends TestCase {
private static final int CAPACITY = 100;
@@ -159,15 +144,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#force(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "force",
- args = {boolean.class}
- )
public void test_forceZ() throws Exception {
ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
writeOnlyFileChannel.write(writeBuffer);
@@ -226,15 +202,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "tryLock",
- args = {long.class, long.class, boolean.class}
- )
public void test_tryLockJJZ_IllegalArgument() throws Exception {
try {
writeOnlyFileChannel.tryLock(0, -1, false);
@@ -287,15 +254,6 @@
lockOne.release();
}
- /**
- * @tests java.nio.channels.FileChannel#read(ByteBuffer, long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "read",
- args = {java.nio.ByteBuffer.class, long.class}
- )
public void test_readLByteBufferJ_Null() throws Exception {
ByteBuffer readBuffer = null;
@@ -391,15 +349,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#read(ByteBuffer, long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "read",
- args = {java.nio.ByteBuffer.class, long.class}
- )
public void test_readLByteBufferJ_IllegalArgument() throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
@@ -451,15 +400,6 @@
}
- /**
- * @tests java.nio.channels.FileChannel#read(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
public void test_read$LByteBuffer() throws Exception {
FileChannel mockChannel = new MockFileChannel();
ByteBuffer[] buffers = new ByteBuffer[2];
@@ -469,15 +409,6 @@
assertTrue(((MockFileChannel)mockChannel).isReadCalled);
}
- /**
- * @tests java.nio.channels.FileChannel#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_Null() throws Exception {
try {
@@ -711,15 +642,7 @@
// expected
}
}
- /**
- * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
+
public void test_read$LByteBufferII_IndexOutOfBound() throws Exception {
ByteBuffer[] readBuffers = new ByteBuffer[2];
readBuffers[0] = ByteBuffer.allocate(CAPACITY);
@@ -785,15 +708,6 @@
doTestForIOOBException(writeOnlyFileChannel, readBuffersNull);
}
- /**
- * @tests java.nio.channels.FileChannel#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_EmptyFile() throws Exception {
ByteBuffer[] readBuffers = new ByteBuffer[2];
readBuffers[0] = ByteBuffer.allocate(CAPACITY);
@@ -804,15 +718,6 @@
assertEquals(0, readBuffers[1].position());
}
- /**
- * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "read",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
public void test_read$LByteBufferII_EmptyBuffers() throws Exception {
ByteBuffer[] readBuffers = new ByteBuffer[2];
readBuffers[0] = ByteBuffer.allocate(CAPACITY);
@@ -835,24 +740,6 @@
assertEquals(CONTENT_AS_BYTES_LENGTH, result);
}
- /**
- * @tests java.nio.channels.FileChannel#isOpen()
- * @tests java.nio.channels.FileChannel#close()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- })
public void test_isOpen() throws Exception {
// Regression for HARMONY-40
File logFile = File.createTempFile("out", "tmp");
@@ -865,15 +752,6 @@
assertFalse("Assert 0: Channel is still open", channel.isOpen());
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException.",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
public void test_writeLByteBuffer_Closed() throws Exception {
ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
@@ -925,15 +803,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer, long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer.class, long.class}
- )
public void test_writeLByteBufferJ_Null() throws Exception {
ByteBuffer writeBuffer = null;
@@ -1029,15 +898,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#read(ByteBuffer,long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IOException.",
- method = "read",
- args = {java.nio.ByteBuffer.class, long.class}
- )
public void test_writeLByteBufferJ_Postion_As_Long() throws Exception {
ByteBuffer writeBuffer = ByteBuffer.wrap(TEST_BYTES);
try {
@@ -1047,15 +907,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer, long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "write",
- args = {java.nio.ByteBuffer.class, long.class}
- )
public void test_writeLByteBufferJ_IllegalArgument() throws Exception {
ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
@@ -1106,15 +957,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class, long.class}
- )
public void test_writeLByteBufferJ_NonZeroPosition() throws Exception {
final int pos = 5;
ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
@@ -1135,15 +977,6 @@
assertTrue(Arrays.equals(test.getBytes(), inputBuffer));
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedChannelException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
public void test_write$LByteBuffer_Closed() throws Exception {
ByteBuffer[] writeBuffers = new ByteBuffer[2];
writeBuffers[0] = ByteBuffer.allocate(CAPACITY);
@@ -1174,15 +1007,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NonWritableChannelException",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
public void test_write$LByteBuffer_ReadOnly() throws Exception {
ByteBuffer[] writeBuffers = new ByteBuffer[2];
writeBuffers[0] = ByteBuffer.allocate(CAPACITY);
@@ -1196,15 +1020,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
public void test_write$LByteBuffer_EmptyBuffers() throws Exception {
ByteBuffer[] writeBuffers = new ByteBuffer[2];
writeBuffers[0] = ByteBuffer.allocate(this.CONTENT_LENGTH);
@@ -1223,15 +1038,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer[].class}
- )
public void test_write$LByteBuffer() throws Exception {
ByteBuffer[] writeBuffers = new ByteBuffer[2];
writeBuffers[0] = ByteBuffer.wrap(CONTENT_AS_BYTES);
@@ -1257,15 +1063,6 @@
assertTrue(Arrays.equals(CONTENT_AS_BYTES, inputBuffer));
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
public void test_write$LByteBufferII_Null() throws Exception {
ByteBuffer[] writeBuffers = null;
@@ -1315,15 +1112,7 @@
// expected
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
+
public void test_write$LByteBufferII_IndexOutOfBound() throws Exception {
ByteBuffer[] writeBuffers = new ByteBuffer[2];
writeBuffers[0] = ByteBuffer.allocate(this.CONTENT_LENGTH);
@@ -1441,15 +1230,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "write",
- args = {java.nio.ByteBuffer[].class, int.class, int.class}
- )
public void test_write$LByteBufferII_EmptyBuffers() throws Exception {
ByteBuffer[] writeBuffers = new ByteBuffer[2];
writeBuffers[0] = ByteBuffer.allocate(this.CONTENT_LENGTH);
@@ -1468,15 +1248,6 @@
}
}
- /**
- * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "transferTo",
- args = {long.class, long.class, java.nio.channels.WritableByteChannel.class}
- )
public void test_transferToJJLWritableByteChannel_IllegalArgument()
throws Exception {
WritableByteChannel writableByteChannel = DatagramChannel.open();
diff --git a/luni/src/test/java/libcore/java/nio/channels/OldServerSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/OldServerSocketChannelTest.java
index 7bc8780..fb63512 100644
--- a/luni/src/test/java/libcore/java/nio/channels/OldServerSocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/OldServerSocketChannelTest.java
@@ -17,9 +17,6 @@
package libcore.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;
@@ -33,7 +30,6 @@
/*
* test for ServerSocketChannel
*/
-@TestTargetClass(ServerSocketChannel.class)
public class OldServerSocketChannelTest extends TestCase {
private static final int TIME_UNIT = 200;
@@ -75,15 +71,6 @@
// -------------------------------------------------------------------
// Test for methods in abstract class.
// -------------------------------------------------------------------
- /*
- * Test method for 'java.nio.channels.ServerSocketChannel()'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ServerSocketChannel",
- args = {java.nio.channels.spi.SelectorProvider.class}
- )
public void testConstructor() throws IOException {
ServerSocketChannel channel =
SelectorProvider.provider().openServerSocketChannel();
@@ -91,24 +78,12 @@
assertSame(SelectorProvider.provider(),channel.provider());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isOpen",
- args = {}
- )
public void testIsOpen() throws Exception {
assertTrue(this.serverChannel.isOpen());
this.serverChannel.close();
assertFalse(this.serverChannel.isOpen());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClosedByInterruptException.",
- method = "accept",
- args = {}
- )
public void test_accept_Block_NoConnect_interrupt() throws IOException {
assertTrue(this.serverChannel.isBlocking());
ServerSocket gotSocket = this.serverChannel.socket();
diff --git a/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java
index 2f81918..f182375 100644
--- a/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/OldSocketChannelTest.java
@@ -18,9 +18,6 @@
package libcore.java.nio.channels;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@@ -40,7 +37,6 @@
import junit.framework.TestCase;
import tests.support.Support_PortManager;
-@TestTargetClass(SocketChannel.class)
/**
* Tests for SocketChannel and its default implementation.
*/
@@ -247,15 +243,6 @@
return connected;
}
- /**
- * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {java.nio.ByteBuffer.class}
- )
@BrokenTest("Occasionally fail in CTS, but works in CoreTestRunner")
public void test_writeLjava_nio_ByteBuffer_Nonblocking_HugeData() throws IOException {
// initialize write content
@@ -299,16 +286,6 @@
}
}
- /**
- * @throws IOException
- * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {java.nio.ByteBuffer[].class}
- )
public void test_socketChannel_read_DirectByteBuffer() throws InterruptedException, IOException {
ServerThread server = new ServerThread();
diff --git a/luni/src/test/java/libcore/java/nio/charset/OldCharsetDecoderTest.java b/luni/src/test/java/libcore/java/nio/charset/CharsetDecoderTest.java
similarity index 65%
rename from luni/src/test/java/libcore/java/nio/charset/OldCharsetDecoderTest.java
rename to luni/src/test/java/libcore/java/nio/charset/CharsetDecoderTest.java
index 8f37f63..e874a1b 100644
--- a/luni/src/test/java/libcore/java/nio/charset/OldCharsetDecoderTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/CharsetDecoderTest.java
@@ -25,11 +25,7 @@
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
-public class OldCharsetDecoderTest extends junit.framework.TestCase {
- private static final String CHARSET = "UTF-16";
-
- private static final String SAMPLE_STRING = "Android";
-
+public class CharsetDecoderTest extends junit.framework.TestCase {
// None of the harmony or jtreg tests actually check that replaceWith does the right thing!
public void test_replaceWith() throws Exception {
CharsetDecoder d = Charset.forName("UTF-16").newDecoder();
@@ -42,8 +38,8 @@
// http://code.google.com/p/android/issues/detail?id=4237
public void test_ByteArray_decode_no_offset() throws Exception {
- CharsetDecoder decoder = getCharsetDecoderUnderTest();
- byte[] arr = getEncodedByteArrayFixture();
+ CharsetDecoder decoder = Charset.forName("UTF-16").newDecoder();
+ byte[] arr = encode("UTF-16", "Android");
ByteBuffer inBuffer = ByteBuffer.wrap(arr, 0, arr.length).slice();
CharBuffer outBuffer = CharBuffer.allocate(arr.length);
decoder.reset();
@@ -51,13 +47,13 @@
assertFalse(coderResult.toString(), coderResult.isError());
decoder.flush(outBuffer);
outBuffer.flip();
- assertEquals(SAMPLE_STRING, outBuffer.toString().trim());
+ assertEquals("Android", outBuffer.toString().trim());
}
// http://code.google.com/p/android/issues/detail?id=4237
public void test_ByteArray_decode_with_offset() throws Exception {
- CharsetDecoder decoder = getCharsetDecoderUnderTest();
- byte[] arr = getEncodedByteArrayFixture();
+ CharsetDecoder decoder = Charset.forName("UTF-16").newDecoder();
+ byte[] arr = encode("UTF-16", "Android");
arr = prependByteToByteArray(arr, new Integer(1).byteValue());
int offset = 1;
ByteBuffer inBuffer = ByteBuffer.wrap(arr, offset, arr.length - offset).slice();
@@ -67,17 +63,17 @@
assertFalse(coderResult.toString(), coderResult.isError());
decoder.flush(outBuffer);
outBuffer.flip();
- assertEquals(SAMPLE_STRING, outBuffer.toString().trim());
+ assertEquals("Android", outBuffer.toString().trim());
}
// http://code.google.com/p/android/issues/detail?id=4237
public void test_ByteArray_decode_with_offset_using_facade_method() throws Exception {
- CharsetDecoder decoder = getCharsetDecoderUnderTest();
- byte[] arr = getEncodedByteArrayFixture();
+ CharsetDecoder decoder = Charset.forName("UTF-16").newDecoder();
+ byte[] arr = encode("UTF-16", "Android");
arr = prependByteToByteArray(arr, new Integer(1).byteValue());
int offset = 1;
CharBuffer outBuffer = decoder.decode(ByteBuffer.wrap(arr, offset, arr.length - offset));
- assertEquals(SAMPLE_STRING, outBuffer.toString().trim());
+ assertEquals("Android", outBuffer.toString().trim());
}
private static byte[] prependByteToByteArray(byte[] arr, byte b) {
@@ -87,12 +83,26 @@
return result;
}
- private static CharsetDecoder getCharsetDecoderUnderTest() {
- return Charset.forName(CHARSET).newDecoder();
+ private static byte[] encode(String charsetName, String s) throws Exception {
+ CharsetEncoder encoder = Charset.forName(charsetName).newEncoder();
+ return encoder.encode(CharBuffer.wrap(s)).array();
}
- private byte[] getEncodedByteArrayFixture() throws CharacterCodingException {
- CharsetEncoder encoder = Charset.forName(CHARSET).newEncoder();
- return encoder.encode(CharBuffer.wrap(SAMPLE_STRING)).array();
+ public void testUtf8BytesSplitAcrossMultipleWrites() throws Exception {
+ CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
+ CharBuffer cb = CharBuffer.allocate(128);
+ CoderResult cr;
+ cr = decoder.decode(ByteBuffer.wrap(new byte[] { (byte) 0xe2 }), cb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ cr = decoder.decode(ByteBuffer.wrap(new byte[] { (byte) 0x98 }), cb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ cr = decoder.decode(ByteBuffer.wrap(new byte[] { (byte) 0x83 }), cb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ cr = decoder.decode(ByteBuffer.wrap(new byte[0]), cb, true);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ cr = decoder.flush(cb);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(1, cb.position());
+ assertEquals('\u2603', cb.get(0));
}
}
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 87e7306..d733a9f 100644
--- a/luni/src/test/java/libcore/java/nio/charset/CharsetEncoderTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/CharsetEncoderTest.java
@@ -16,9 +16,11 @@
package libcore.java.nio.charset;
+import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.Arrays;
@@ -59,4 +61,147 @@
public void test_defaultReplacementBytesUtf_8() throws Exception {
assertReplacementBytesForEncoder("UTF-8", new byte[] { (byte) '?' });
}
+
+ public void testSurrogatePairAllAtOnce() throws Exception {
+ // okay: surrogate pair seen all at once is decoded to U+20b9f.
+ Charset cs = Charset.forName("UTF-32BE");
+ CharsetEncoder e = cs.newEncoder();
+ ByteBuffer bb = ByteBuffer.allocate(128);
+ CoderResult cr = e.encode(CharBuffer.wrap(new char[] { '\ud842', '\udf9f' }), bb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(4, bb.position());
+ assertEquals((byte) 0x00, bb.get(0));
+ assertEquals((byte) 0x02, bb.get(1));
+ assertEquals((byte) 0x0b, bb.get(2));
+ assertEquals((byte) 0x9f, bb.get(3));
+ }
+
+ public void testMalformedSurrogatePair() throws Exception {
+ // malformed: low surrogate first is detected as an error.
+ Charset cs = Charset.forName("UTF-32BE");
+ CharsetEncoder e = cs.newEncoder();
+ ByteBuffer bb = ByteBuffer.allocate(128);
+ CoderResult cr = e.encode(CharBuffer.wrap(new char[] { '\udf9f' }), bb, false);
+ assertTrue(cr.toString(), cr.isMalformed());
+ assertEquals(1, cr.length());
+ }
+
+ public void testCharsetEncoderSurrogatesBrokenByDesign_IGNORE_RI() throws Exception {
+ testCharsetEncoderSurrogatesBrokenByDesign_RI(CodingErrorAction.IGNORE);
+ }
+
+ public void testCharsetEncoderSurrogatesBrokenByDesign_REPORT_RI() throws Exception {
+ testCharsetEncoderSurrogatesBrokenByDesign_RI(CodingErrorAction.REPORT);
+ }
+
+ public void testCharsetEncoderSurrogatesBrokenByDesign_REPLACE_RI() throws Exception {
+ testCharsetEncoderSurrogatesBrokenByDesign_RI(CodingErrorAction.REPLACE);
+ }
+
+ private void testCharsetEncoderSurrogatesBrokenByDesign_RI(CodingErrorAction cea) throws Exception {
+ // stupid: on the RI, writing the two halves of the surrogate pair in separate writes
+ // is an error because the CharsetEncoder doesn't remember it's half-way through a
+ // surrogate pair across the two calls!
+
+ // IGNORE just ignores both characters, REPORT complains that the second is
+ // invalid (because it doesn't remember seeing the first), and REPLACE inserts a
+ // replacement character U+fffd when it sees the second character (because it too
+ // doesn't remember seeing the first).
+
+ Charset cs = Charset.forName("UTF-32BE");
+ CharsetEncoder e = cs.newEncoder();
+ e.onMalformedInput(cea);
+ e.onUnmappableCharacter(cea);
+ ByteBuffer bb = ByteBuffer.allocate(128);
+ CoderResult cr = e.encode(CharBuffer.wrap(new char[] { '\ud842' }), bb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(0, bb.position());
+ cr = e.encode(CharBuffer.wrap(new char[] { '\udf9f' }), bb, false);
+ if (cea == CodingErrorAction.REPORT) {
+ assertTrue(cr.toString(), cr.isMalformed());
+ assertEquals(1, cr.length());
+ return;
+ }
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ int expectedPosition = 0;
+ if (cea == CodingErrorAction.REPLACE) {
+ expectedPosition = 4;
+ assertEquals(expectedPosition, bb.position());
+ System.err.println(Arrays.toString(Arrays.copyOfRange(bb.array(), 0, bb.position())));
+ assertEquals((byte) 0x00, bb.get(0));
+ assertEquals((byte) 0x00, bb.get(1));
+ assertEquals((byte) 0xff, bb.get(2));
+ assertEquals((byte) 0xfd, bb.get(3));
+ }
+ assertEquals(expectedPosition, bb.position());
+ cr = e.encode(CharBuffer.wrap(new char[] { }), bb, true);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(expectedPosition, bb.position());
+ cr = e.flush(bb);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(expectedPosition, bb.position());
+ }
+
+ public void testCharsetEncoderSurrogatesBrokenByDesign_IGNORE() throws Exception {
+ testCharsetEncoderSurrogatesBrokenByDesign(CodingErrorAction.IGNORE);
+ }
+
+ public void testCharsetEncoderSurrogatesBrokenByDesign_REPORT() throws Exception {
+ testCharsetEncoderSurrogatesBrokenByDesign(CodingErrorAction.REPORT);
+ }
+
+ public void testCharsetEncoderSurrogatesBrokenByDesign_REPLACE() throws Exception {
+ testCharsetEncoderSurrogatesBrokenByDesign(CodingErrorAction.REPLACE);
+ }
+
+ private void testCharsetEncoderSurrogatesBrokenByDesign(CodingErrorAction cea) throws Exception {
+ // Writing the two halves of the surrogate pair in separate writes works just fine.
+ // This is true of Android and ICU, but not of the RI.
+ Charset cs = Charset.forName("UTF-32BE");
+ CharsetEncoder e = cs.newEncoder();
+ e.onMalformedInput(cea);
+ e.onUnmappableCharacter(cea);
+ ByteBuffer bb = ByteBuffer.allocate(128);
+ CoderResult cr = e.encode(CharBuffer.wrap(new char[] { '\ud842' }), bb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(0, bb.position());
+ cr = e.encode(CharBuffer.wrap(new char[] { '\udf9f' }), bb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ int expectedPosition = 4;
+ assertEquals(expectedPosition, bb.position());
+ System.err.println(Arrays.toString(Arrays.copyOfRange(bb.array(), 0, bb.position())));
+ assertEquals((byte) 0x00, bb.get(0));
+ assertEquals((byte) 0x02, bb.get(1));
+ assertEquals((byte) 0x0b, bb.get(2));
+ assertEquals((byte) 0x9f, bb.get(3));
+ cr = e.encode(CharBuffer.wrap(new char[] { }), bb, true);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(expectedPosition, bb.position());
+ cr = e.flush(bb);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(expectedPosition, bb.position());
+ }
+
+ public void testFlushWithoutEndOfInput() throws Exception {
+ Charset cs = Charset.forName("UTF-32BE");
+ CharsetEncoder e = cs.newEncoder();
+ ByteBuffer bb = ByteBuffer.allocate(128);
+ CoderResult cr = e.encode(CharBuffer.wrap(new char[] { 'x' }), bb, false);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(4, bb.position());
+ try {
+ cr = e.flush(bb);
+ } catch (IllegalStateException expected) {
+ // you must call encode with endOfInput true before you can flush.
+ }
+
+ // We had a bug where we wouldn't reset inEnd before calling encode in implFlush.
+ // That would result in flush outputting garbage.
+ cr = e.encode(CharBuffer.wrap(new char[] { 'x' }), bb, true);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(8, bb.position());
+ cr = e.flush(bb);
+ assertEquals(CoderResult.UNDERFLOW, cr);
+ assertEquals(8, bb.position());
+ }
}
diff --git a/luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java b/luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java
index 583cb47..6465d9e 100644
--- a/luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java
+++ b/luni/src/test/java/libcore/java/nio/charset/OldCharsetEncoderDecoderBufferTest.java
@@ -24,7 +24,7 @@
import junit.framework.TestCase;
-/* See bug 1844104.
+/* See bug http://b/1844104.
* Checks for ICU encoder/decoder buffer corruption.
*/
public class OldCharsetEncoderDecoderBufferTest extends TestCase {
@@ -77,8 +77,8 @@
assertEquals('a', inArray[0]);
assertEquals('b', inArray[1]);
- ByteBuffer inWithoutArray = ByteBuffer.allocateDirect(1);
- inWithoutArray.put(0, (byte)'x');
+ // A read-only ByteBuffer must not expose its array.
+ ByteBuffer inWithoutArray = ByteBuffer.wrap(new byte[] { (byte) 'x' }).asReadOnlyBuffer();
assertFalse(inWithoutArray.hasArray());
decoder.decode(inWithoutArray, out, true);
@@ -106,7 +106,11 @@
assertEquals(0, buffer[2]);
out = ByteBuffer.allocateDirect(10);
- assertFalse(out.hasArray());
+ // It's no longer possible to get a byte buffer without a backing byte[] on Android.
+ // This test is useless on Android, unless that changes again. (You can't even
+ // subclass ByteBuffer because -- although it's non-final -- both the RI and Android
+ // have [different] package-private abstract methods you'd need to implement but can't.)
+ //assertFalse(out.hasArray());
encoder.encode(CharBuffer.wrap("x"), out, true);
// check whether the second decode corrupted the first buffer
diff --git a/luni/src/test/java/libcore/java/security/AccessControllerTest.java b/luni/src/test/java/libcore/java/security/AccessControllerTest.java
index 0848c5c..1f7da91 100644
--- a/luni/src/test/java/libcore/java/security/AccessControllerTest.java
+++ b/luni/src/test/java/libcore/java/security/AccessControllerTest.java
@@ -17,27 +17,27 @@
package libcore.java.security;
import java.security.AccessControlContext;
-import java.security.AccessControlException;
import java.security.AccessController;
import java.security.DomainCombiner;
import java.security.Permission;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
+import java.util.concurrent.atomic.AtomicInteger;
+import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
+/**
+ * Android doesn't fully support access controller. This tests that actions are
+ * passed through without permission enforcement.
+ */
public final class AccessControllerTest extends TestCase {
public void testDoPrivilegedWithCombiner() {
final Permission permission = new RuntimePermission("do stuff");
final DomainCombiner union = new DomainCombiner() {
public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
- a = (a == null) ? new ProtectionDomain[0] : a;
- b = (b == null) ? new ProtectionDomain[0] : b;
- ProtectionDomain[] union = new ProtectionDomain[a.length + b.length];
- System.arraycopy(a, 0, union, 0, a.length);
- System.arraycopy(b, 0, union, a.length, b.length);
- return union;
+ throw new AssertionFailedError("Expected combiner to be unused");
}
};
@@ -45,26 +45,19 @@
AccessControlContext accessControlContext = new AccessControlContext(
new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
+ final AtomicInteger actionCount = new AtomicInteger();
+
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
- // in this block we lack our requested permission
- assertSame(union, AccessController.getContext().getDomainCombiner());
- assertPermission(false, permission);
+ assertEquals(null, AccessController.getContext().getDomainCombiner());
+ AccessController.getContext().checkPermission(permission);
+ // Calling doPrivileged again would have exercised the combiner
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
- // nest doPrivileged to get it back.
- assertNull(AccessController.getContext().getDomainCombiner());
- assertPermission(true, permission);
- return null;
- }
- });
-
- AccessController.doPrivilegedWithCombiner(new PrivilegedAction<Void>() {
- public Void run() {
- // nest doPrivilegedWithCombiner() to get it back and keep the combiner.
- assertSame(union, AccessController.getContext().getDomainCombiner());
- assertPermission(true, permission);
+ actionCount.incrementAndGet();
+ assertEquals(null, AccessController.getContext().getDomainCombiner());
+ AccessController.getContext().checkPermission(permission);
return null;
}
});
@@ -72,17 +65,7 @@
return null;
}
}, accessControlContext);
- }
- private void assertPermission(boolean granted, Permission permission) {
- if (granted) {
- AccessController.getContext().checkPermission(permission);
- } else {
- try {
- AccessController.getContext().checkPermission(permission);
- fail("Had unexpected permission: " + permission);
- } catch (AccessControlException expected) {
- }
- }
+ assertEquals(1, actionCount.get());
}
}
diff --git a/luni/src/test/java/libcore/java/security/KeyStoreTest.java b/luni/src/test/java/libcore/java/security/KeyStoreTest.java
index 17d35de..0c61020 100644
--- a/luni/src/test/java/libcore/java/security/KeyStoreTest.java
+++ b/luni/src/test/java/libcore/java/security/KeyStoreTest.java
@@ -53,10 +53,17 @@
public class KeyStoreTest extends TestCase {
- private static final PrivateKeyEntry PRIVATE_KEY
- = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
- private static final PrivateKeyEntry PRIVATE_KEY_2
- = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
+ private static final PrivateKeyEntry PRIVATE_KEY;
+ private static final PrivateKeyEntry PRIVATE_KEY_2;
+ static {
+ try {
+ PRIVATE_KEY = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
+ PRIVATE_KEY_2 = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
private static final SecretKey SECRET_KEY = generateSecretKey();
private static final SecretKey SECRET_KEY_2 = generateSecretKey();
diff --git a/luni/src/test/java/libcore/java/security/OldAlgorithmParameterGeneratorTest.java b/luni/src/test/java/libcore/java/security/OldAlgorithmParameterGeneratorTest.java
index 5985403..968bd53 100644
--- a/luni/src/test/java/libcore/java/security/OldAlgorithmParameterGeneratorTest.java
+++ b/luni/src/test/java/libcore/java/security/OldAlgorithmParameterGeneratorTest.java
@@ -17,11 +17,9 @@
package libcore.java.security;
-import dalvik.annotation.TestTargetClass;
import java.security.AlgorithmParameterGenerator;
import java.security.SecureRandom;
-@TestTargetClass(AlgorithmParameterGenerator.class)
public class OldAlgorithmParameterGeneratorTest extends junit.framework.TestCase {
public void test_initI() throws Exception {
diff --git a/luni/src/test/java/libcore/java/security/OldDHTest.java b/luni/src/test/java/libcore/java/security/OldDHTest.java
index 95cdfe5..421d153 100644
--- a/luni/src/test/java/libcore/java/security/OldDHTest.java
+++ b/luni/src/test/java/libcore/java/security/OldDHTest.java
@@ -16,8 +16,6 @@
package libcore.java.security;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.KeyPair;
@@ -29,11 +27,6 @@
public class OldDHTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "method",
- args = {}
- )
@BrokenTest("Suffers from DH slowness, disabling for now")
public void testDHGen() throws Exception {
KeyPairGenerator gen = null;
diff --git a/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java b/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java
index 5a308e3..d69e0e2 100644
--- a/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java
+++ b/luni/src/test/java/libcore/java/security/cert/OldPKIXParametersTest.java
@@ -23,9 +23,6 @@
package libcore.java.security.cert;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.io.ByteArrayInputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
@@ -43,18 +40,8 @@
/**
* Tests for <code>PKIXParameters</code> fields and methods
*/
-@TestTargetClass(PKIXParameters.class)
public class OldPKIXParametersTest extends TestCase {
- /**
- * Test for <code>clone()</code> method<br>
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
public final void testClone() throws InvalidAlgorithmParameterException {
Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet();
if (taSet == null) {
@@ -112,12 +99,6 @@
*
* @throws InvalidAlgorithmParameterException
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isPolicyMappingInhibited",
- args = {}
- )
public final void testIsPolicyMappingInhibited() throws Exception {
Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet();
if (taSet == null) {
@@ -146,12 +127,6 @@
*
* @throws InvalidAlgorithmParameterException
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isRevocationEnabled",
- args = {}
- )
public final void testIsRevocationEnabled() throws Exception {
Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet();
if (taSet == null) {
@@ -176,12 +151,6 @@
/**
* Test for <code>toString</code> method<br>
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
public final void testToString() throws Exception {
Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet();
if (taSet == null) {
@@ -207,12 +176,6 @@
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies everything except null argument",
- method = "PKIXParameters",
- args = {java.security.KeyStore.class}
- )
@BrokenTest("Fails in CTS environment, but passes in CoreTestRunner")
public final void testPKIXParametersKeyStore04() throws Exception {
diff --git a/luni/src/test/java/libcore/java/security/cert/SubjectAlternativeNameTest.java b/luni/src/test/java/libcore/java/security/cert/SubjectAlternativeNameTest.java
new file mode 100644
index 0000000..88d5011
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/cert/SubjectAlternativeNameTest.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2011 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.security.cert;
+
+import com.android.org.bouncycastle.asn1.x509.GeneralName;
+import java.io.ByteArrayInputStream;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Collection;
+import java.util.List;
+import junit.framework.TestCase;
+import libcore.java.security.TestKeyStore;
+
+public final class SubjectAlternativeNameTest extends TestCase {
+
+ /**
+ * The spec doesn't cover this, but we require that IP addresses are
+ * formatted consistently with InetAddress.getHostAddress().
+ */
+ public void testFormatIpv4Address() throws Exception {
+ assertEquals("127.0.0.1", formatIpAddress(new byte[]{127, 0, 0, 1}));
+ }
+
+ public void testFormatIpv4MappedAddress() throws Exception {
+ byte[] mappedAddress = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 127, 0, 0, 1 };
+ assertEquals("127.0.0.1", formatIpAddress(mappedAddress));
+ }
+
+ public void testFormatIpv6Address() throws Exception {
+ byte[] ipAddress = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+ String decoded = formatIpAddress(ipAddress);
+ assertTrue(decoded, decoded.equals("::1") || decoded.equals("0:0:0:0:0:0:0:1"));
+ }
+
+ private String formatIpAddress(byte[] ipAddress) throws Exception {
+ Certificate root = new TestKeyStore.Builder()
+ .addSubjectAltNameIpAddress(ipAddress)
+ .build()
+ .getRootCertificate("RSA");
+ X509Certificate javaCertificate = bouncycastleToJava(root);
+ Collection<List<?>> subjectAlternativeNames = javaCertificate.getSubjectAlternativeNames();
+ assertEquals(1, subjectAlternativeNames.size());
+ List<?> subjectAlternativeName = subjectAlternativeNames.iterator().next();
+ assertEquals(2, subjectAlternativeName.size());
+ assertEquals(GeneralName.iPAddress, subjectAlternativeName.get(0));
+ return (String) subjectAlternativeName.get(1);
+ }
+
+ private X509Certificate bouncycastleToJava(Certificate certificate) throws Exception {
+ byte[] encoded = certificate.getEncoded();
+ CertificateFactory factory = CertificateFactory.getInstance("X.509");
+ return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(encoded));
+ }
+}
diff --git a/luni/src/test/java/libcore/java/security/cert/X509CertSelectorTest.java b/luni/src/test/java/libcore/java/security/cert/X509CertSelectorTest.java
new file mode 100644
index 0000000..4a5658c
--- /dev/null
+++ b/luni/src/test/java/libcore/java/security/cert/X509CertSelectorTest.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2011 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.security.cert;
+
+import com.android.org.bouncycastle.asn1.x509.GeneralName;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509CertSelector;
+import java.security.cert.X509Certificate;
+import junit.framework.TestCase;
+import libcore.java.security.TestKeyStore;
+
+public final class X509CertSelectorTest extends TestCase {
+
+ public void testMatchIpv4SubjectAlternativeName() throws Exception {
+ X509CertSelector certSelector = new X509CertSelector();
+ certSelector.addSubjectAlternativeName(GeneralName.iPAddress, "127.0.0.1");
+
+ byte[] match = { 127, 0, 0, 1 };
+ assertTrue(certSelector.match(newCertWithSubjectAltNameIpAddress(match)));
+
+ byte[] noMatch = { 127, 0, 0, 2 };
+ assertFalse(certSelector.match(newCertWithSubjectAltNameIpAddress(noMatch)));
+ }
+
+ public void testMatchIpv4MappedSubjectAlternativeName() throws Exception {
+ X509CertSelector certSelector = new X509CertSelector();
+ certSelector.addSubjectAlternativeName(GeneralName.iPAddress, "::ffff:127.0.0.1");
+
+ byte[] match = { 127, 0, 0, 1 };
+ assertTrue(certSelector.match(newCertWithSubjectAltNameIpAddress(match)));
+
+ byte[] noMatch = { 127, 0, 0, 2 };
+ assertFalse(certSelector.match(newCertWithSubjectAltNameIpAddress(noMatch)));
+ }
+
+ public void testMatchIpv6SubjectAlternativeName() throws Exception {
+ X509CertSelector certSelector = new X509CertSelector();
+ certSelector.setMatchAllSubjectAltNames(false);
+ certSelector.addSubjectAlternativeName(GeneralName.iPAddress, "::1");
+
+ byte[] match = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
+ assertTrue(certSelector.match(newCertWithSubjectAltNameIpAddress(match)));
+
+ byte[] noMatch = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2 };
+ assertFalse(certSelector.match(newCertWithSubjectAltNameIpAddress(noMatch)));
+ }
+
+ public void testMatchMaskedIpv4NameConstraint() throws Exception {
+ byte[] excluded = { (byte) 192, (byte) 168, 0, 1 };
+ X509CertSelector certSelector = new X509CertSelector();
+ certSelector.addPathToName(GeneralName.iPAddress, "127.0.0.1");
+
+ byte[] directMatch = { 127, 0, 0, 1, -1, -1, -1, -1 };
+ assertTrue(certSelector.match(newCertWithNameConstraint(directMatch, excluded)));
+
+ byte[] noMatch = { 127, 0, 0, 2, -1, -1, -1, 127 };
+ assertFalse(certSelector.match(newCertWithNameConstraint(noMatch, excluded)));
+
+ // TODO: test that requires mask to match
+ }
+
+ public void testMatchMaskedIpv6NameConstraint() throws Exception {
+ byte[] excluded = {
+ 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0
+ };
+ X509CertSelector certSelector = new X509CertSelector();
+ certSelector.addPathToName(GeneralName.iPAddress, "1::1");
+
+ byte[] directMatch = {
+ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 127
+ };
+ assertTrue(certSelector.match(newCertWithNameConstraint(directMatch, excluded)));
+
+ byte[] noMatch = {
+ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 127
+ };
+ assertFalse(certSelector.match(newCertWithNameConstraint(noMatch, excluded)));
+
+ // TODO: test that requires mask to match
+ }
+
+ public void testMatchMalformedSubjectAlternativeName() throws Exception {
+ X509CertSelector certSelector = new X509CertSelector();
+ try {
+ certSelector.addSubjectAlternativeName(GeneralName.iPAddress, "1::x");
+ fail();
+ } catch (IOException expected) {
+ }
+ try {
+ certSelector.addSubjectAlternativeName(GeneralName.iPAddress, "127.0.0.x");
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ private X509Certificate newCertWithSubjectAltNameIpAddress(byte[] ipAddress) throws Exception {
+ TestKeyStore testKeyStore = new TestKeyStore.Builder()
+ .addSubjectAltNameIpAddress(ipAddress)
+ .build();
+ return bouncycastleToJava(testKeyStore.getRootCertificate("RSA"));
+ }
+
+ private X509Certificate newCertWithNameConstraint(byte[] permitted, byte[] excluded)
+ throws Exception {
+ TestKeyStore testKeyStore = new TestKeyStore.Builder()
+ .addNameConstraint(true, permitted)
+ .addNameConstraint(false, excluded)
+ .ca(true)
+ .build();
+ return bouncycastleToJava(testKeyStore.getRootCertificate("RSA"));
+ }
+
+ private X509Certificate bouncycastleToJava(Certificate certificate) throws Exception {
+ byte[] encoded = certificate.getEncoded();
+ CertificateFactory factory = CertificateFactory.getInstance("X.509");
+ return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(encoded));
+ }
+}
diff --git a/luni/src/test/java/tests/sql/ConnectionTest.java b/luni/src/test/java/libcore/java/sql/OldConnectionTest.java
similarity index 72%
rename from luni/src/test/java/tests/sql/ConnectionTest.java
rename to luni/src/test/java/libcore/java/sql/OldConnectionTest.java
index efa8aa4..0edee1c 100755
--- a/luni/src/test/java/tests/sql/ConnectionTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldConnectionTest.java
@@ -14,57 +14,28 @@
* limitations under the License.
*/
-package tests.sql;
+package libcore.java.sql;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
+import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
-import java.sql.SQLWarning;
-import java.sql.Savepoint;
-import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Savepoint;
+import java.sql.Statement;
-import java.sql.CallableStatement;
-import java.util.Map;
+public final class OldConnectionTest extends OldSQLTest {
-import junit.framework.Test;
-
-@TestTargetClass(Connection.class)
-public class ConnectionTest extends SQLTest {
-
- /**
- * @test {@link java.sql.Connection#createStatement()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createStatement",
- args = {}
- )
- public void testCreateStatement() {
-
- Statement statement = null;
- try {
- statement = conn.createStatement();
- assertNotNull(statement);
- //check default values
- assertEquals(ResultSet.FETCH_UNKNOWN, statement.getFetchDirection());
- assertNull(statement.getWarnings());
- assertTrue(statement.getQueryTimeout() > 0);
- } catch (SQLException sqle) {
- fail("SQL Exception was thrown: " + sqle.getMessage());
- } catch (Exception e) {
- fail("Unexpected Exception " + e.getMessage());
- }
+ public void testCreateStatement() throws SQLException {
+ Statement statement = conn.createStatement();
+ assertNotNull(statement);
+ //check default values
+ assertEquals(ResultSet.FETCH_UNKNOWN, statement.getFetchDirection());
+ assertNull(statement.getWarnings());
+ assertTrue(statement.getQueryTimeout() > 0);
try {
conn.close();
statement.executeQuery("select * from zoo");
@@ -74,17 +45,7 @@
}
}
- /**
- * @test {@link java.sql.Connection#createStatement(int resultSetType, int
- * resultSetConcurrency)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exception tests fail.",
- method = "createStatement",
- args = {int.class, int.class}
- )
- @KnownFailure("Scrolling on a forward only RS not allowed. conn.close() does not wrap up")
+ // Scrolling on a forward only RS not allowed. conn.close() does not wrap up
public void testCreateStatement_int_int() throws SQLException {
Statement st = null;
ResultSet rs = null;
@@ -101,9 +62,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -125,9 +83,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -136,7 +91,7 @@
}
}
- // test forward only
+ // test forward only
try {
st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
@@ -149,9 +104,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -177,9 +129,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -203,9 +152,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -217,7 +163,7 @@
conn.close();
try {
- // exception is not specified for this case
+ // exception is not specified for this case
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, -1);
fail("Illigal arguments: should return exception.");
} catch (SQLException sqle) {
@@ -225,7 +171,7 @@
}
try {
- // exception is not specified for this case
+ // exception is not specified for this case
conn.createStatement(Integer.MIN_VALUE, ResultSet.CONCUR_READ_ONLY);
fail("Illigal arguments: should return exception.");
} catch (SQLException sqle) {
@@ -233,17 +179,7 @@
}
}
- /**
- * @test java.sql.Connection#createStatement(int resultSetType, int
- * resultSetConcurrency, int resultSetHoldability)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "ResultSet.HOLD_CURSORS_AT_COMMIT",
- method = "createStatement",
- args = {int.class, int.class, int.class}
- )
- public void testCreateStatement_int_int_int() {
+ public void testCreateStatement_int_int_int() throws SQLException {
Statement st = null;
try {
assertNotNull(conn);
@@ -257,13 +193,7 @@
int pos = rs.getRow();
conn.commit();
assertEquals("ResultSet cursor position has changed",pos, rs.getRow());
- try {
- rs.close();
- } catch (SQLException sqle) {
- fail("Unexpected exception was thrown during closing ResultSet");
- }
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
+ rs.close();
} finally {
try {
if (st != null) st.close();
@@ -278,17 +208,10 @@
} catch (SQLException sqle) {
//ok
}
-
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "ResultSet.CLOSE_CURSORS_AT_COMMIT as argument is not supported",
- method = "createStatement",
- args = {int.class, int.class, int.class}
- )
- @KnownFailure("not supported")
- public void testCreateStatementIntIntIntNotSupported() {
+ // known failure: not supported
+ public void testCreateStatementIntIntIntNotSupported() throws SQLException {
Statement st = null;
try {
st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
@@ -304,37 +227,21 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
if (st != null) {
- try {
- st.close();
- } catch (SQLException ee) {
- }
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
}
}
}
- /**
- * @test java.sql.Connection#getMetaData()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "getMetaData",
- args = {}
- )
- @KnownFailure("conn.close() does not wrap up")
- public void testGetMetaData() throws SQLException{
- try {
- DatabaseMetaData md = conn.getMetaData();
- Connection con = md.getConnection();
- assertEquals(conn, con);
- } catch (SQLException e) {
- fail("SQLException is thrown");
- }
+ // conn.close() does not wrap up
+ public void testGetMetaData() throws SQLException {
+ DatabaseMetaData md = conn.getMetaData();
+ Connection con = md.getConnection();
+ assertEquals(conn, con);
conn.close();
try {
@@ -345,28 +252,10 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#clearWarnings()
- *
- * TODO clearWarnings is not supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "test fails. not supported. always returns null.",
- method = "clearWarnings",
- args = {}
- )
- @KnownFailure("not supported")
- public void testClearWarnings() throws SQLException {
-
- try {
- SQLWarning w = conn.getWarnings();
- assertNull(w);
- } catch (Exception e) {
- fail("Unexpected Exception: " + e.getMessage());
- }
-
+ // TODO clearWarnings is not supported
+ public void testClearWarnings() throws Exception {
+ SQLWarning w = conn.getWarnings();
+ assertNull(w);
Statement st = null;
try {
@@ -382,13 +271,9 @@
}
}
- try {
- conn.clearWarnings();
- SQLWarning w = conn.getWarnings();
- assertNull(w);
- } catch (Exception e) {
- fail("Unexpected Exception: " + e.getMessage());
- }
+ conn.clearWarnings();
+ w = conn.getWarnings();
+ assertNull(w);
try {
st = conn.createStatement();
@@ -404,12 +289,8 @@
}
//Test for correct functionality
- try {
- SQLWarning w = conn.getWarnings();
- assertNotNull(w);
- } catch (Exception e) {
- fail("Unexpected Exception: " + e.getMessage());
- }
+ w = conn.getWarnings();
+ assertNotNull(w);
conn.close();
try {
@@ -422,20 +303,8 @@
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#getWarnings()
- *
- * TODO GetWarnings is not supported: returns null
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported. always returns null. SQLException test fails",
- method = "getWarnings",
- args = {}
- )
- @KnownFailure("not supported")
- public void testGetWarnings() throws SQLException {
+ // TODO GetWarnings is not supported: returns null
+ public void testGetWarnings() throws Exception {
Statement st = null;
int errorCode1 = -1;
int errorCode2 = -1;
@@ -449,12 +318,8 @@
errorCode1 = e.getErrorCode();
}
- try {
- SQLWarning wrs = conn.getWarnings();
- assertNull(wrs);
- } catch (Exception e) {
- fail("Change test implementation: get warnings is supported now");
- }
+ SQLWarning wrs = conn.getWarnings();
+ assertNull(wrs);
// tests implementation: but errorcodes need to change too -> change impl.
/*
@@ -511,49 +376,24 @@
}
}
- /**
- * @test java.sql.Connection#getAutoCommit()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException checking missed",
- method = "getAutoCommit",
- args = {}
- )
- public void testGetAutoCommit() {
- try {
- conn.setAutoCommit(true);
- assertTrue(conn.getAutoCommit());
- conn.setAutoCommit(false);
- assertFalse(conn.getAutoCommit());
- conn.setAutoCommit(true);
- assertTrue(conn.getAutoCommit());
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- }
+ public void testGetAutoCommit() throws SQLException {
+ conn.setAutoCommit(true);
+ assertTrue(conn.getAutoCommit());
+ conn.setAutoCommit(false);
+ assertFalse(conn.getAutoCommit());
+ conn.setAutoCommit(true);
+ assertTrue(conn.getAutoCommit());
}
- /**
- * @test java.sql.Connection#setAutoCommit(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test throws exception",
- method = "setAutoCommit",
- args = {boolean.class}
- )
- @KnownFailure("conn.close() does not wrap up")
+ // conn.close() does not wrap up
public void testSetAutoCommit() throws SQLException {
-
Statement st = null;
ResultSet rs = null;
ResultSet rs1 = null;
try {
conn.setAutoCommit(true);
st = conn.createStatement();
- st
- .execute("insert into zoo (id, name, family) values (3, 'Chichichi', 'monkey');");
+ st.execute("insert into zoo (id, name, family) values (3, 'Chichichi', 'monkey');");
conn.commit();
} catch (SQLException e) {
//ok
@@ -569,8 +409,6 @@
st.execute("select * from zoo");
rs = st.getResultSet();
assertEquals(3, getCount(rs));
- } catch (SQLException e) {
- fail("Unexpected Exception thrown");
} finally {
try {
st.close();
@@ -582,8 +420,7 @@
try {
conn.setAutoCommit(false);
st = conn.createStatement();
- st
- .execute("insert into zoo (id, name, family) values (4, 'Burenka', 'cow');");
+ st.execute("insert into zoo (id, name, family) values (4, 'Burenka', 'cow');");
st.execute("select * from zoo");
rs = st.getResultSet();
assertEquals(4, getCount(rs));
@@ -591,9 +428,6 @@
// Check cursors closed after commit
rs1 = st.getResultSet();
assertEquals(0, getCount(rs1));
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -613,26 +447,12 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#isReadOnly()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Instead of SQLException nullpointer exception is thrown.",
- method = "isReadOnly",
- args = {}
- )
- @KnownFailure("conn.close() does not wrap up")
+ // conn.close() does not wrap up
public void testIsReadOnly() throws SQLException {
- try {
- conn.setReadOnly(true);
- assertTrue(conn.isReadOnly());
- conn.setReadOnly(false);
- assertFalse(conn.isReadOnly());
- } catch (SQLException sqle) {
- fail("SQLException was thrown: " + sqle.getMessage());
- }
+ conn.setReadOnly(true);
+ assertTrue(conn.isReadOnly());
+ conn.setReadOnly(false);
+ assertFalse(conn.isReadOnly());
conn.close();
try {
@@ -643,17 +463,7 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#setReadOnly(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Not supported. test fails",
- method = "setReadOnly",
- args = {boolean.class}
- )
- @KnownFailure("not supported")
+ // not supported
public void testSetReadOnly() throws SQLException {
// Pseudo test: not supported test
@@ -663,8 +473,6 @@
st = conn.createStatement();
st.execute("insert into zoo (id, name, family) values (3, 'ChiChiChi', 'monkey');");
// fail("SQLException is not thrown");
- } catch (SQLException sqle) {
- fail("Set readonly is actually implemented: activate correct test");
} finally {
try {
st.close();
@@ -706,8 +514,6 @@
conn.setReadOnly(false);
st = conn.createStatement();
st.execute("insert into zoo (id, name, family) values (4, 'ChiChiChi', 'monkey');");
- } catch (SQLException sqle) {
- fail("SQLException was thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -724,27 +530,10 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#getHoldability()
- *
- * TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "+option ResultSet.CLOSE_CURSORS_AT_COMMIT not supported. SQLException test fails.",
- method = "getHoldability",
- args = {}
- )
- @KnownFailure("not supported")
+ // TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
public void testGetHoldability() throws SQLException {
- try {
- conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
- assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn
- .getHoldability());
- } catch (SQLException sqle) {
- fail("SQLException was thrown: " + sqle.getMessage());
- }
+ conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
+ assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability());
try {
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
@@ -754,7 +543,7 @@
assertEquals("not supported", e.getMessage());
}
- // Exception checking
+ // Exception checking
conn.close();
@@ -766,19 +555,8 @@
}
}
- /**
- * @test java.sql.Connection#setHoldability(int)
- *
- * TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported",
- method = "setHoldability",
- args = {int.class}
- )
- @KnownFailure("not supported")
- public void testSetHoldability() {
+ // TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
+ public void testSetHoldability() throws SQLException {
Statement st = null;
try {
conn.setAutoCommit(false);
@@ -801,13 +579,7 @@
st.execute("insert into zoo (id, name, family) values (4, 'ChiChiChi', 'monkey');");
rs = st.getResultSet();
conn.commit();
- try {
- rs.next();
- } catch (SQLException sqle) {
- fail("SQLException was thrown: " + sqle.getMessage());
- }
- } catch (SQLException sqle) {
- fail("SQLException was thrown: " + sqle.getMessage());
+ rs.next();
} finally {
try {
st.close();
@@ -823,40 +595,22 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#getTransactionIsolation()
- *
- * TODO only Connection.TRANSACTION_SERIALIZABLE is supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SQLException testing throws exception. Connection.TRANSACTION_SERIALIZABLE.",
- method = "getTransactionIsolation",
- args = {}
- )
- @KnownFailure("not supported")
+ // TODO only Connection.TRANSACTION_SERIALIZABLE is supported
public void testGetTransactionIsolation() throws SQLException {
- try {
- conn
- .setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
- assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn
- .getTransactionIsolation());
- conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
- assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn
- .getTransactionIsolation());
- conn
- .setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
- assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn
- .getTransactionIsolation());
- conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn
- .getTransactionIsolation());
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
+ conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
+ assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn
+ .getTransactionIsolation());
+ conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+ assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn
+ .getTransactionIsolation());
+ conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
+ assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn
+ .getTransactionIsolation());
+ conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
+ assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn
+ .getTransactionIsolation());
- // Exception checking
+ // Exception checking
conn.close();
@@ -868,18 +622,7 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#getTransactionIsolation()
- *
- * TODO only Connection.TRANSACTION_SERIALIZABLE is supported
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "not supported options",
- method = "getTransactionIsolation",
- args = {}
- )
+ // TODO only Connection.TRANSACTION_SERIALIZABLE is supported
public void testGetTransactionIsolationNotSupported() throws SQLException {
/*
try {
@@ -900,19 +643,8 @@
*/
}
- /**
- * @test java.sql.Connection#setTransactionIsolation(int)
- *
- * TODO only Connection.TRANSACTION_SERIALIZABLE is supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not fully supported",
- method = "setTransactionIsolation",
- args = {int.class}
- )
- public void testSetTransactionIsolation() {
- try {
+ // TODO only Connection.TRANSACTION_SERIALIZABLE is supported
+ public void testSetTransactionIsolation() throws SQLException {
// conn
// .setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
// assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn
@@ -924,12 +656,8 @@
// .setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
// assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn
// .getTransactionIsolation());
- conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
- assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn
- .getTransactionIsolation());
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
+ conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
+ assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn.getTransactionIsolation());
try {
conn.setTransactionIsolation(0);
@@ -939,19 +667,8 @@
}
}
- /**
- * @test java.sql.Connection#setCatalog(String catalog)
- *
- * TODO setCatalog method does nothing: Hint default catalog sqlite_master.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setCatalog",
- args = {java.lang.String.class}
- )
- public void testSetCatalog() {
-
+ // TODO setCatalog method does nothing: Hint default catalog sqlite_master.
+ public void testSetCatalog() throws SQLException {
String[] catalogs = { "test", "test1", "test" };
Statement st = null;
try {
@@ -964,8 +681,6 @@
st.equals("drop table test_table;");
}
- } catch (SQLException sqle) {
- fail("SQLException is thrown");
} finally {
try {
st.close();
@@ -1032,45 +747,19 @@
*/
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#getCatalog()
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported. test fails",
- method = "getCatalog",
- args = {}
- )
- @KnownFailure("not supported")
- public void testGetCatalog() throws SQLException {
-
-
+ // not supported
+ public void testGetCatalog() throws SQLException {
// test default catalog
- try {
- assertEquals("sqlite_master", conn.getCatalog());
- } catch (SQLException sqle) {
- fail("SQL Exception " + sqle.getMessage());
- } catch (Exception e) {
- fail("Unexpected Exception " + e.getMessage());
- }
-
+ assertEquals("sqlite_master", conn.getCatalog());
String[] catalogs = { "sqlite_test", "sqlite_test1", "sqlite_test" };
Statement st = null;
- try {
- for (int i = 0; i < catalogs.length; i++) {
- conn.setCatalog(catalogs[i]);
- assertNull(conn.getCatalog());
- }
- } catch (SQLException sqle) {
- fail("SQL Exception " + sqle.getMessage());
- } catch (Exception e) {
- fail("Reeimplement tests now that the method is implemented");
+ for (int i = 0; i < catalogs.length; i++) {
+ conn.setCatalog(catalogs[i]);
+ assertNull(conn.getCatalog());
}
- // Exception checking
+ // Exception checking
conn.close();
@@ -1082,17 +771,7 @@
}
}
- /**
- * @test java.sql.Connection#setTypeMap(Map<String,Class<?>> map)
- *
- * TODO setTypeMap is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setTypeMap",
- args = {java.util.Map.class}
- )
+ // TODO setTypeMap is not supported
public void testSetTypeMap() {
/*
try {
@@ -1118,18 +797,7 @@
*/
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#getTypeMap()
- *
- * TODO getTypeMap is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "getTypeMap",
- args = {}
- )
+ // TODO getTypeMap is not supported
public void testGetTypeMap() throws SQLException {
/*
try {
@@ -1159,17 +827,7 @@
*/
}
- /**
- * @test java.sql.Connection#nativeSQL(String sql)
- *
- * TODO nativeSQL is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "nativeSQL",
- args = {java.lang.String.class}
- )
+ // TODO nativeSQL is not supported
public void testNativeSQL() throws SQLException{
String[] queries = {
"select * from zoo;",
@@ -1192,8 +850,6 @@
}
} catch (SQLException sqle) {
//ok
- } catch (Exception e) {
- fail("Unexpected Exception " + e.getMessage());
} finally {
try {
st.close();
@@ -1221,20 +877,9 @@
} catch (SQLException e) {
//ok
}
-
}
- /**
- * @test java.sql.Connection#prepareCall(String sql)
- *
- * TODO prepareCall is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "prepareCall",
- args = {java.lang.String.class}
- )
+ // TODO prepareCall is not supported
public void testPrepareCall() throws SQLException {
CallableStatement cstmt = null;
ResultSet rs = null;
@@ -1252,7 +897,6 @@
st1.execute("select * from zoo");
rs1 = st1.getResultSet();
assertEquals(3, getCount(rs1));
-
} catch (SQLException e) {
//ok not supported
} finally {
@@ -1281,7 +925,7 @@
// expected
}
- // Exception checking
+ // Exception checking
conn.close();
@@ -1294,18 +938,7 @@
}
- /**
- * @test java.sql.Connection#prepareCall(String sql, int resultSetType, int
- * resultSetConcurrency)
- *
- * TODO prepareCall is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "prepareCall",
- args = {java.lang.String.class, int.class, int.class}
- )
+ // TODO prepareCall is not supported
public void testPrepareCall_String_int_int() {
CallableStatement cstmt = null;
ResultSet rs = null;
@@ -1418,18 +1051,7 @@
*/
}
- /**
- * @test java.sql.Connection#prepareCall(String sql, int resultSetType, int
- * resultSetConcurrency, int resultSetHoldability)
- *
- * TODO prepareCall is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "prepareCall",
- args = {java.lang.String.class, int.class, int.class, int.class}
- )
+ // TODO prepareCall is not supported
public void testPrepareCall_String_int_int_int() {
CallableStatement cstmt = null;
ResultSet rs = null;
@@ -1498,16 +1120,7 @@
}
- /**
- * @test java.sql.Connection#prepareStatement(String sql)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "prepareStatement",
- args = {java.lang.String.class}
- )
- public void testPrepareStatement() {
+ public void testPrepareStatement() throws SQLException {
PreparedStatement prst = null;
Statement st = null;
ResultSet rs = null;
@@ -1525,8 +1138,6 @@
st.execute("select * from zoo where family = 'cat'");
rs1 = st.getResultSet();
assertEquals(1, getCount(rs1));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -1551,24 +1162,10 @@
} catch (Exception e) {
//ok
}
-
-
}
-
- /**
- * @test { @link java.sql.Connection#prepareStatement(String sql, int
- * autoGeneratedKeys) }
- */
-// TODO Crashes VM. Fix later.
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Statment.Return_generated_keys/getGeneratedKeys is not supported",
- method = "prepareStatement",
- args = {java.lang.String.class, int.class}
- )
- @KnownFailure("not supported")
- public void testPrepareStatement_String_int() {
+ // TODO Crashes VM. Fix later.
+ public void testPrepareStatement_String_int() throws SQLException {
PreparedStatement prst = null;
PreparedStatement prst1 = null;
Statement st = null;
@@ -1587,7 +1184,6 @@
//ok not supported
}
-
try {
String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
@@ -1608,8 +1204,6 @@
rs4 = prst.getGeneratedKeys();
assertEquals(0, getCount(rs4));
-
-
prst1 = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
prst1.setInt(1, 5);
prst1.setString(2, "Layka");
@@ -1617,13 +1211,8 @@
prst1.execute();
-
-
rs5 = prst1.getGeneratedKeys();
assertEquals(0, getCount(rs5));
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -1633,20 +1222,9 @@
} catch (Exception ee) {
}
}
-
-
}
- /**
- * @test java.sql.Connection#commit()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "commit",
- args = {}
- )
- public void testCommit() {
+ public void testCommit() throws SQLException {
Statement st = null;
Statement st1 = null;
Statement st2 = null;
@@ -1660,10 +1238,8 @@
conn.setAutoCommit(false);
st = conn.createStatement();
- st
- .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
- st
- .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+ st.execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st.execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
st1 = conn.createStatement();
st1.execute("select * from zoo");
@@ -1675,8 +1251,6 @@
st2.execute("select * from zoo");
rs2 = st2.getResultSet();
assertEquals(4, getCount(rs2));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.toString());
} finally {
try {
rs2.close();
@@ -1693,8 +1267,6 @@
rs3 = st3.getResultSet();
conn.commit();
assertEquals(4, getCount(rs3));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.toString());
} finally {
try {
if (rs3 != null) rs3.close();
@@ -1702,8 +1274,6 @@
} catch (SQLException ee) {
}
}
- } catch (SQLException sqle) {
- fail("SQLException was thrown: " + sqle.toString());
} finally {
try {
rs1.close();
@@ -1712,20 +1282,8 @@
} catch (Exception ee) {
}
}
-
-
}
- /**
- * @throws SQLException
- * @test java.sql.Connection#rollback()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rollback",
- args = {}
- )
public void testRollback() throws SQLException {
Statement st = null;
Statement st1 = null;
@@ -1736,18 +1294,13 @@
try {
conn.setAutoCommit(false);
st = conn.createStatement();
- st
- .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
- st
- .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+ st.execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st.execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
conn.rollback();
st1 = conn.createStatement();
st1.execute("select * from zoo");
rs1 = st1.getResultSet();
assertEquals("Rollback was ineffective",2, getCount(rs1));
-
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
} finally {
conn.setAutoCommit(true);
try {
@@ -1759,12 +1312,9 @@
}
try {
conn.setAutoCommit(false);
-
st = conn.createStatement();
- st
- .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
- st
- .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+ st.execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st.execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
if (!conn.getAutoCommit()) {
st1 = conn.createStatement();
@@ -1785,8 +1335,6 @@
st3.execute("select * from zoo");
rs3 = st3.getResultSet();
assertEquals(4, getCount(rs3));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.toString());
} finally {
conn.setAutoCommit(true);
try {
@@ -1800,8 +1348,6 @@
} else {
fail("Error in test setup: cannot turn autocommit off.");
}
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
} finally {
try {
st.close();
@@ -1820,29 +1366,14 @@
}
}
- /**
- * @test java.sql.Connection#setSavepoint()
- *
- * TODO setSavepoint is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setSavepoint",
- args = {}
- )
- public void testSetSavepoint() {
+ // TODO setSavepoint is not supported
+ public void testSetSavepoint() throws SQLException {
+ conn.setAutoCommit(false);
try {
- conn.setAutoCommit(false);
-
- try {
- Savepoint sp = conn.setSavepoint();
- } catch (SQLException e) {
- // ok not supported
- }
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
+ Savepoint sp = conn.setSavepoint();
+ } catch (SQLException e) {
+ // ok not supported
}
@@ -1959,31 +1490,15 @@
*/
}
- /**
- * @test java.sql.Connection#setSavepoint(String name)
- *
- * TODO setSavepoint is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setSavepoint",
- args = {java.lang.String.class}
- )
- public void testSetSavepoint_String() {
-
+ // TODO setSavepoint is not supported
+ public void testSetSavepoint_String() throws SQLException {
String testSavepoint = "testSavepoint";
+ conn.setAutoCommit(false);
try {
- conn.setAutoCommit(false);
-
- try {
- Savepoint sp = conn.setSavepoint(testSavepoint);
- } catch (SQLException e) {
- // ok not supported
- }
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
+ Savepoint sp = conn.setSavepoint(testSavepoint);
+ } catch (SQLException e) {
+ // ok not supported
}
/*
@@ -2097,29 +1612,15 @@
*/
}
- /**
- * @test java.sql.Connection#rollback(Savepoint savepoint)
- *
- * TODO Savepoint is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "rollback",
- args = {java.sql.Savepoint.class}
- )
- public void testRollback_Savepoint() {
+ // TODO Savepoint is not supported
+ public void testRollback_Savepoint() throws SQLException {
Savepoint sp = new DummySavePoint();
- try {
- conn.setAutoCommit(false);
+ conn.setAutoCommit(false);
- try {
- conn.rollback(sp);
- } catch (SQLException e) {
- //ok
- }
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
+ try {
+ conn.rollback(sp);
+ } catch (SQLException e) {
+ //ok
}
/*
Statement st = null;
@@ -2232,29 +1733,15 @@
*/
}
- /**
- * @test java.sql.Connection#releaseSavepoint(Savepoint savepoint)
- *
- * TODO Savepoint is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "releaseSavepoint",
- args = {java.sql.Savepoint.class}
- )
- public void testReleaseSavepoint_Savepoint() {
+ // TODO Savepoint is not supported
+ public void testReleaseSavepoint_Savepoint() throws SQLException {
Savepoint sp = new DummySavePoint();
- try {
- conn.setAutoCommit(false);
+ conn.setAutoCommit(false);
- try {
- conn.releaseSavepoint(sp);
- } catch (SQLException e) {
- //ok
- }
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
+ try {
+ conn.releaseSavepoint(sp);
+ } catch (SQLException e) {
+ //ok
}
/*
@@ -2364,19 +1851,7 @@
*/
}
- /**
- * @test java.sql.Connection#prepareStatement(String sql, int[]
- * columnIndexes)
- *
- * TODO prepareStatement(String sql, int[] columnIndexes) is not
- * supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "prepareStatement",
- args = {java.lang.String.class, int[].class}
- )
+ // TODO prepareStatement(String sql, int[] columnIndexes) is not supported
public void testPrepareStatement_String_intArray() {
PreparedStatement prst = null;
try {
@@ -2459,17 +1934,7 @@
*/
}
- /**
- * @test java.sql.Connection#prepareStatement(String sql, int resultSetType,
- * int resultSetConcurrency)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "not fully supported",
- method = "prepareStatement",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void testPrepareStatement_String_int_int() {
+ public void testPrepareStatement_String_int_int() throws SQLException {
String query = "insert into zoo (id, name, family) values (?, ?, ?);";
PreparedStatement st = null;
ResultSet rs = null;
@@ -2485,9 +1950,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
@@ -2510,9 +1972,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
} finally {
try {
rs.close();
@@ -2535,15 +1994,8 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "not supported options: ResultSet.TYPE_SCROLL_INSENSITIVE," +
- "ResultSet.CONCUR_UPDATABLE",
- method = "prepareStatement",
- args = {java.lang.String.class, int.class, int.class}
- )
- @KnownFailure("not supported")
- public void testPrepareStatementNotSupported() {
+ // not supported
+ public void testPrepareStatementNotSupported() throws SQLException {
String query = "insert into zoo (id, name, family) values (?, ?, ?);";
PreparedStatement st = null;
ResultSet rs = null;
@@ -2553,18 +2005,11 @@
ResultSet.CONCUR_UPDATABLE);
st.execute("select name, family from zoo");
rs = st.getResultSet();
- try {
- rs.insertRow();
- rs.updateObject("family", "bird");
- rs.next();
- rs.previous();
- assertEquals("parrot", (rs.getString(1)));
- } catch (SQLException sqle) {
- fail("Got Exception "+sqle.getMessage());
- }
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("parrot", (rs.getString(1)));
} finally {
try {
if (rs != null) rs.close();
@@ -2572,23 +2017,10 @@
} catch (SQLException ee) {
}
}
-
}
-
-
- /**
- * @test java.sql.Connection#prepareStatement(String sql, int resultSetType,
- * int resultSetConcurrency, int resultSetHoldability)
- */
// TODO Crashes VM. Fix later.
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Not fully implemented: ResultSet.CLOSE_CURSORS_AT_COMMIT not supported",
- method = "prepareStatement",
- args = {java.lang.String.class, int.class, int.class, int.class}
- )
- public void testPrepareStatement_String_int_int_int() {
+ public void testPrepareStatement_String_int_int_int() throws SQLException {
String query = "insert into zoo (id, name, family) values (?, ?, ?);";
PreparedStatement st = null;
ResultSet rs = null;
@@ -2601,13 +2033,7 @@
st.setString(3, "Cock");
st.execute("select id, name from zoo");
rs = st.getResultSet();
- try {
- rs.close();
- } catch (SQLException sqle) {
- fail("Unexpected exception was thrown during closing ResultSet");
- }
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
+ rs.close();
} finally {
try {
if (rs != null) rs.close();
@@ -2650,19 +2076,7 @@
}
- /**
- * @test java.sql.Connection#prepareStatement(String sql, String[]
- * columnNames)
- *
- * TODO prepareStatement(String sql, String[] columnNames) method is
- * not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "prepareStatement",
- args = {java.lang.String.class, java.lang.String[].class}
- )
+ // TODO prepareStatement(String sql, String[] columnNames) method is not supported
public void testPrepareStatement_String_StringArray() {
PreparedStatement prst = null;
PreparedStatement prst1 = null;
@@ -2742,44 +2156,21 @@
}
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported: it should release all resources but it doesn't",
- method = "close",
- args = {}
- )
- public void testClose() {
- try {
-
-
-
- if (! conn.isClosed()) {
- conn.close();
- }
- assertTrue(conn.isClosed());
-
- try {
- conn.prepareCall("select * from zoo");
- fail("Should not be able to prepare query closed connection");
- } catch (SQLException e) {
- //ok
- }
- } catch (SQLException e) {
- fail("Error in implementation");
- e.printStackTrace();
+ public void testClose() throws SQLException {
+ if (! conn.isClosed()) {
+ conn.close();
}
+ assertTrue(conn.isClosed());
+ try {
+ conn.prepareCall("select * from zoo");
+ fail("Should not be able to prepare query closed connection");
+ } catch (SQLException e) {
+ //ok
+ }
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "isClosed",
- args = {}
- )
public void testIsClosed() throws Exception {
-
assertFalse(conn.isClosed());
conn.close();
assertTrue(conn.isClosed());
@@ -2790,18 +2181,13 @@
st.execute("select * from zoo");
}
-
private static class DummySavePoint implements Savepoint{
-
public int getSavepointId() {
- // TODO Auto-generated method stub
return 0;
}
public String getSavepointName() {
- // TODO Auto-generated method stub
return "NoName";
}
-
}
}
diff --git a/luni/src/test/java/libcore/java/sql/OldDriverPropertyInfoTest.java b/luni/src/test/java/libcore/java/sql/OldDriverPropertyInfoTest.java
index 7f7cc66..6ff9fd5 100644
--- a/luni/src/test/java/libcore/java/sql/OldDriverPropertyInfoTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldDriverPropertyInfoTest.java
@@ -23,7 +23,7 @@
import java.util.Properties;
import junit.framework.TestCase;
-public class OldDriverPropertyInfoTest extends TestCase {
+public final class OldDriverPropertyInfoTest extends TestCase {
static final String validName = "testname";
static final String validValue = "testvalue";
diff --git a/luni/src/test/java/tests/sql/PreparedStatementTest.java b/luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java
similarity index 65%
rename from luni/src/test/java/tests/sql/PreparedStatementTest.java
rename to luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java
index f69e374..8fd8665 100755
--- a/luni/src/test/java/tests/sql/PreparedStatementTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldPreparedStatementTest.java
@@ -14,15 +14,8 @@
* limitations under the License.
*/
-package tests.sql;
+package libcore.java.sql;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
@@ -34,7 +27,6 @@
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
-import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
@@ -44,15 +36,13 @@
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
-import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
-@TestTargetClass(PreparedStatement.class)
-public class PreparedStatementTest extends SQLTest {
+public final class OldPreparedStatementTest extends OldSQLTest {
String queryAllSelect = "select * from type";
@@ -97,8 +87,6 @@
for (int i = 0; i < queries.length; i++) {
st.execute(queries[i]);
}
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.toString());
} finally {
try {
st.close();
@@ -107,13 +95,11 @@
}
}
- public void tearDown() {
+ public void tearDown() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
st.execute("drop table if exists type");
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
st.close();
@@ -123,15 +109,6 @@
super.tearDown();
}
- /**
- * @test java.sql.PreparedStatement#addBatch()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addBatch",
- args = {}
- )
public void testAddBatch() throws SQLException {
PreparedStatement ps = null;
try {
@@ -160,8 +137,6 @@
} catch (SQLException ee) {
}
}
- } catch (SQLException e) {
- fail("SQLException is thrown "+e.getMessage());
} finally {
try {
ps.close();
@@ -197,17 +172,8 @@
}
- /**
- * @test java.sql.PreparedStatement#execute()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "execute",
- args = {}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update.")
- public void testExecute() {
+ // preparedStatement.execute() does not return false on update.
+ public void testExecute() throws SQLException {
Statement st = null;
PreparedStatement ps = null;
try {
@@ -223,8 +189,6 @@
ps = conn.prepareStatement("select * from zoo");
assertTrue(ps.execute());
assertEquals(3, getCount(ps.getResultSet()));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
ps.close();
@@ -244,8 +208,6 @@
ResultSet rs = st.getResultSet();
rs.next();
assertEquals("cat", rs.getString(1));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
ps.close();
@@ -260,8 +222,6 @@
ps = conn.prepareStatement(query);
assertFalse(ps.execute());
assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
ps.close();
@@ -274,8 +234,6 @@
ps = conn.prepareStatement(query);
ps.setInt(1, 1);
assertTrue(ps.execute());
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
ps.close();
@@ -287,8 +245,6 @@
String query = "select name, family from zoo where id = ?";
ps = conn.prepareStatement(query);
ps.execute();
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
ps.close();
@@ -312,18 +268,7 @@
}
}
-
- /**
- * @test java.sql.PreparedStatement#executeQuery()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "executeQuery",
- args = {}
- )
- public void testExecuteQuery() {
-
+ public void testExecuteQuery() throws SQLException {
String[] queries2 = {
"update zoo set name='Masha', family='cat' where id=;",
"insert into hutch (id, animal_id, address) values (1, ?,'Birds-house, 1');",
@@ -356,8 +301,6 @@
assertEquals(1, rs.getInt(1));
assertEquals("Kesha", rs.getString(2));
assertEquals("parrot", rs.getString(3));
- } catch (SQLException e) {
- fail("SQLException is thrown for query");
} finally {
try {
ps.close();
@@ -371,8 +314,6 @@
ResultSet rs = ps.executeQuery();
assertNotNull(rs);
assertFalse(rs.next());
- } catch (SQLException e) {
- fail("SQLException is thrown for query");
} finally {
try {
ps.close();
@@ -381,17 +322,8 @@
}
}
- // TODO Crashes VM. Fix later.
- /**
- * @test {@link java.sql.PreparedStatement#executeUpdate()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "executeUpdate",
- args = {}
- )
- public void testExecuteUpdate() {
+ // TODO Crashes VM. Fix later.
+ public void testExecuteUpdate() throws SQLException {
String[] queries1 = { "insert into hutch (id, animal_id, address) values (1, ?, 'Birds-house, 1');",
"insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');",
"create view address as select address from hutch where animal_id=2" };
@@ -421,8 +353,6 @@
ps.setInt(1, 1);
int updateCount1 = ps.executeUpdate();
assertEquals(1, updateCount1);
- } catch (SQLException e) {
- fail("SQLException is thrown for query");
} finally {
try {
ps.close();
@@ -431,23 +361,10 @@
}
/**
- * @test java.sql.PreparedStatement#getMetaData()
- *
- * Test Fails:
- * TODO Doesn't pass. according to Java docs:
- * it is possible to invoke the method getMetaData on a
- * PreparedStatement object before it is executed.
+ * TODO Doesn't pass. according to spec, it is possible to invoke the
+ * method getMetaData on a PreparedStatement object before it is executed.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMetaData",
- args = {}
- )
- @KnownFailure("it is not possible to invoke the method getMetaData on a " +
- "PreparedStatement object before it is executed: got NullPointerException."+
- "Test passes on RI.")
- public void testGetMetaData() {
+ public void testGetMetaData() throws SQLException {
PreparedStatement ps = null;
// Specification testing
@@ -458,12 +375,6 @@
assertNotNull(ps);
ResultSetMetaData meta = ps.getMetaData();
assertNotNull(meta);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- sqle.printStackTrace();
- } catch (Exception e) {
- fail("Unspecified Exception: " + e.toString());
- e.printStackTrace();
} finally {
try {
ps.close();
@@ -478,8 +389,6 @@
assertNotNull(rsmd);
assertEquals(3, rsmd.getColumnCount());
assertEquals("id", rsmd.getColumnName(1));
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
ps.close();
@@ -496,23 +405,14 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.PreparedStatement#getParameterMetaData()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getParameterMetaData",
- args = {}
- )
public void testGetParameterMetaData() throws SQLException {
PreparedStatement ps = null;
String query = "select * from zoo where id = ?";
ps = conn.prepareStatement(query);
try {
- ParameterMetaData rsmd = ps.getParameterMetaData();
+ ps.getParameterMetaData();
+ fail();
} catch (SQLException e) {
assertEquals("not supported",e.getMessage());
} finally {
@@ -534,17 +434,9 @@
/**
- * @test java.sql.PreparedStatement#clearParameters()
* Test fails: clearparameters should be implemented with Stmt.reset()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test fails: clearparameters should be implemented with Stmt.reset()",
- method = "clearParameters",
- args = {}
- )
- @KnownFailure("First Exception test fails: parameters not cleared.")
- public void testClearParameters() {
+ public void testClearParameters() throws SQLException {
PreparedStatement ps = null;
try {
String query = "select * from zoo where id = ? and family=?";
@@ -554,7 +446,6 @@
ps.execute();
fail("SQLException is not thrown during execute method after calling clearParameters()");
} catch (SQLException sql) {
-
}
ps.setInt(1, 2);
ps.setString(2, "dog");
@@ -581,27 +472,15 @@
} catch (SQLException sqle) {
fail("SQLException is thrown during execute method after calling clearParameters() twice");
}
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
ps.close();
} catch (SQLException ee) {
}
}
-
}
- /**
- * @test java.sql.PreparedStatement#setInt(int parameterIndex, int x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInt",
- args = {int.class, int.class}
- )
- @KnownFailure("exception test fails")
+ // exception test fails
public void testSetInt() throws SQLException {
PreparedStatement ps = null;
@@ -617,8 +496,6 @@
+ Integer.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -635,8 +512,6 @@
+ Integer.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -652,9 +527,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
@@ -664,17 +536,8 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setLong(int parameterIndex, long x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLong",
- args = {int.class, long.class}
- )
- @KnownFailure("exception test fails")
- public void testSetLong() {
+ // exception test fails
+ public void testSetLong() throws SQLException {
PreparedStatement ps = null;
try {
@@ -685,13 +548,9 @@
ps.setLong(1, Long.MAX_VALUE);
ps.execute();
st = conn.createStatement();
- st
- .execute("select * from type where LongVal="
- + Long.MAX_VALUE);
+ st.execute("select * from type where LongVal=" + Long.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -703,13 +562,9 @@
ps.setLong(1, Long.MIN_VALUE);
ps.execute();
st = conn.createStatement();
- st
- .execute("select * from type where LongVal="
- + Long.MAX_VALUE);
+ st.execute("select * from type where LongVal=" + Long.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -724,12 +579,8 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (SQLException ee) {
}
@@ -737,17 +588,7 @@
}
- /**
- * @throws SQLException
- * @test java.sql.PreparedStatement#setFloat(int parameterIndex, float x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFloat",
- args = {int.class, float.class}
- )
- @KnownFailure("exception test fails")
+ // exception test fails
public void testSetFloat() throws SQLException {
float value1 = 12345678.12345689f;
float value2 = -12345678.12345689f;
@@ -766,8 +607,6 @@
st.execute("select * from type where FloatVal=" + value1);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -782,8 +621,6 @@
st.execute("select * from type where FloatVal=" + value2);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -798,9 +635,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
@@ -810,19 +644,8 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.PreparedStatement#setDouble(int parameterIndex, double x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDouble",
- args = {int.class, double.class}
- )
- @KnownFailure("exception test fails")
+ // exception test fails
public void testSetDouble() throws SQLException {
-
PreparedStatement ps = null;
String query = "insert into type (DoubleVal) values (?);";
ps = conn.prepareStatement(query);
@@ -838,8 +661,6 @@
+ Double.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -855,8 +676,6 @@
+ Double.MIN_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -871,9 +690,6 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
@@ -881,23 +697,11 @@
} catch (SQLException ee) {
}
}
-
}
- /**
- * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setString",
- args = {int.class, java.lang.String.class}
- )
- @KnownFailure("exception test fails")
- public void testSetString_charField() {
-
+ // exception test fails
+ public void testSetString_charField() throws SQLException {
PreparedStatement ps = null;
-
try {
String query = "insert into type (charStr) values (?);";
ps = conn.prepareStatement(query);
@@ -911,8 +715,6 @@
st.execute("select * from type where charStr='" + str + "'");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -927,8 +729,6 @@
st.execute("select * from type where charStr=''");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -940,12 +740,9 @@
ps.setString(1, " ");
ps.execute();
st = conn.createStatement();
- st
- .execute("select * from type where charStr=' '");
+ st.execute("select * from type where charStr=' '");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -953,20 +750,10 @@
}
}
- try {
- ps.setString(1, " test & text * test % text * test ^ text ");
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown");
- }
-
- try {
- ps.setString(1, null);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
+ ps.setString(1, " test & text * test % text * test ^ text ");
+ ps.execute();
+ ps.setString(1, null);
+ ps.execute();
ps.close();
try {
@@ -975,30 +762,16 @@
} catch (SQLException sqle) {
// expected
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (SQLException ee) {
}
}
}
- /**
- * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setString",
- args = {int.class, java.lang.String.class}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testSetString_tinyTextField() {
-
+ // statment.close() does not wrap up
+ public void testSetString_tinyTextField() throws SQLException {
PreparedStatement ps = null;
try {
String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
@@ -1012,8 +785,6 @@
st.execute("select * from type where TText='" + str + "'");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1028,8 +799,6 @@
st.execute("select * from type where TText=''");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1041,12 +810,9 @@
ps.setString(1, " ");
ps.execute();
st = conn.createStatement();
- st
- .execute("select * from type where TText=' '");
+ st.execute("select * from type where TText=' '");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1055,9 +821,8 @@
}
try {
- ps.setString(
- 1,
- "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test*test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test-test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test+test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test?test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test#test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test ");
+ ps.setString(1,
+ "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test*test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test-test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test+test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test?test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test#test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test ");
ps.execute();
} catch (SQLException sqle) {
fail("SQLException is thrown");
@@ -1078,30 +843,15 @@
} catch (SQLException sqle) {
// expected
}
-
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (SQLException ee) {
}
}
}
- /**
- * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setString",
- args = {int.class, java.lang.String.class}
- )
- public void testSetString_textField() {
-
+ public void testSetString_textField() throws SQLException {
PreparedStatement ps = null;
try {
String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
@@ -1115,8 +865,6 @@
st.execute("select * from type where TextVal='" + str + "'");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1131,8 +879,6 @@
st.execute("select * from type where TextVal=''");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1144,12 +890,9 @@
ps.setString(1, " ");
ps.execute();
st = conn.createStatement();
- st
- .execute("select * from type where TextVal=' '");
+ st.execute("select * from type where TextVal=' '");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1157,25 +900,15 @@
}
}
-
- try {
- String longString = " test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/";
- for (int i = 0; i < 10; i++) {
- longString += longString;
- }
- ps.setString(1, longString);
- ps.execute();
-
- } catch (SQLException sqle) {
- fail("SQLException is thrown");
+ String longString = " test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/";
+ for (int i = 0; i < 10; i++) {
+ longString += longString;
}
+ ps.setString(1, longString);
+ ps.execute();
- try {
- ps.setString(1, null);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
+ ps.setString(1, null);
+ ps.execute();
ps.close();
@@ -1185,28 +918,15 @@
} catch (SQLException sqle) {
// expected
}
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (SQLException ee) {
}
}
}
- /**
- * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setString",
- args = {int.class, java.lang.String.class}
- )
- public void testSetString_mediumTextField() {
-
+ public void testSetString_mediumTextField() throws SQLException {
PreparedStatement ps = null;
try {
String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
@@ -1220,8 +940,6 @@
st.execute("select * from type where MText='" + str + "'");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1236,8 +954,6 @@
st.execute("select * from type where MText=''");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1253,8 +969,6 @@
.execute("select * from type where MText=' '");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1262,13 +976,8 @@
}
}
- try {
- ps.setString(1, null);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
+ ps.setString(1, null);
+ ps.execute();
ps.close();
try {
@@ -1277,32 +986,16 @@
} catch (SQLException sqle) {
// expected
}
-
-
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (Exception ee) {
}
}
}
- /**
- * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setString",
- args = {int.class, java.lang.String.class}
- )
- @KnownFailure("exception test fails")
- public void testSetString_longTextField() {
-
+ // exception test fails
+ public void testSetString_longTextField() throws SQLException {
PreparedStatement ps = null;
try {
String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
@@ -1316,8 +1009,6 @@
st.execute("select * from type where LText='" + str + "'");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1332,8 +1023,6 @@
st.execute("select * from type where LText=''");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1345,12 +1034,9 @@
ps.setString(1, " ");
ps.execute();
st = conn.createStatement();
- st
- .execute("select * from type where LText=' '");
+ st.execute("select * from type where LText=' '");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1358,13 +1044,8 @@
}
}
- try {
- ps.setString(1, null);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
+ ps.setString(1, null);
+ ps.execute();
ps.close();
try {
@@ -1373,31 +1054,16 @@
} catch (SQLException sqle) {
// expected
}
-
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (Exception ee) {
}
}
}
- /**
- * @test java.sql.PreparedStatement#setShort(int parameterIndex, short x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setShort",
- args = {int.class, short.class}
- )
- @KnownFailure("exception test fails")
- public void testSetShort() {
-
+ // exception test fails
+ public void testSetShort() throws SQLException {
PreparedStatement ps = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
@@ -1412,8 +1078,6 @@
st.execute("select * from type where Sint=" + Short.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1428,8 +1092,6 @@
st.execute("select * from type where Sint=" + Short.MIN_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1448,28 +1110,16 @@
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
- try {
- ps1.setShort(1, Short.MAX_VALUE);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: "+sqle.getMessage());
- }
+ ps1.setShort(1, Short.MAX_VALUE);
String query2 = "insert into type (IntVal) values (?);";
ps2 = conn.prepareStatement(query2);
- try {
- ps2.setShort(1, Short.MAX_VALUE);
- ps2.execute();
- st = conn.createStatement();
- st
- .execute("select * from type where IntVal="
- + Short.MAX_VALUE);
- ResultSet rs = st.getResultSet();
- assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps2.setShort(1, Short.MAX_VALUE);
+ ps2.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where IntVal=" + Short.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
} finally {
try {
@@ -1481,19 +1131,8 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setBoolean(int parameterIndex, boolean
- * x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setBoolean",
- args = {int.class, boolean.class}
- )
- @KnownFailure("exception test fails")
- public void testSetBoolean() {
-
+ // exception test fails
+ public void testSetBoolean() throws SQLException {
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -1507,8 +1146,6 @@
st.execute("select * from type where BoolVal = 0");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1523,8 +1160,6 @@
st.execute("select * from type where BoolVal= 1");
ResultSet rs = st.getResultSet();
assertEquals(2, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1543,15 +1178,8 @@
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
- try {
- ps1.setBoolean(1, true);
- ps1.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setBoolean(1, true);
+ ps1.execute();
} finally {
try {
@@ -1562,18 +1190,8 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setByte(int parameterIndex, byte x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setByte",
- args = {int.class, byte.class}
- )
- @KnownFailure("exception test fails")
- public void testSetByte() {
-
+ // exception test fails
+ public void testSetByte() throws SQLException {
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -1587,8 +1205,6 @@
st.execute("select * from type where Tint=" + Byte.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1603,8 +1219,6 @@
st.execute("select * from type where Tint=" + Byte.MIN_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -1630,15 +1244,8 @@
String query1 = "insert into type (IntVal) values (?);";
ps1 = conn.prepareStatement(query1);
- try {
- ps1.setByte(1, Byte.MAX_VALUE);
- ps1.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setByte(1, Byte.MAX_VALUE);
+ ps1.execute();
} finally {
try {
@@ -1649,20 +1256,9 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setBytes(int parameterIndex, byte[] x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setBytes",
- args = {int.class, byte[].class}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update.")
- public void testSetBytes() {
-
+ // preparedStatement.execute() does not return false on update.
+ public void testSetBytes() throws SQLException {
byte[] bytesArray = {1, 0};
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -1695,16 +1291,9 @@
String query1 = "insert into type (TBlob) values (?);";
ps1 = conn.prepareStatement(query1);
- try {
- ps.setBytes(1, bytesArray);
- assertFalse(ps.execute());
- assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps.setBytes(1, bytesArray);
+ assertFalse(ps.execute());
+ assertTrue(ps.getUpdateCount() > 0);
} finally {
try {
@@ -1715,35 +1304,18 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setBigDecimal(int parameterIndex,
- * BigDecimal x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setBigDecimal",
- args = {int.class, java.math.BigDecimal.class}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update.")
- public void testSetBigDecimal() {
-
+ // preparedStatement.execute() does not return false on update.
+ public void testSetBigDecimal() throws SQLException {
BigDecimal bd = new BigDecimal("50");
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
String query = "insert into type (DecVal) values (?);";
ps = conn.prepareStatement(query);
Statement st = null;
- try {
- ps.setBigDecimal(1, bd);
- assertFalse(ps.execute());
- assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
-
+ ps.setBigDecimal(1, bd);
+ assertFalse(ps.execute());
+ assertTrue(ps.getUpdateCount() > 0);
try {
ps.setBigDecimal(2, bd);
@@ -1763,16 +1335,9 @@
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
- try {
- ps1.setBigDecimal(1, bd);
- } catch (SQLException sqle) {
- fail("SQLException is thrown");
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setBigDecimal(1, bd);
} finally {
try {
-
if (ps != null) ps.close();
if (ps1 != null) ps1.close();
} catch (SQLException ee) {
@@ -1781,25 +1346,15 @@
}
/**
- * @test java.sql.PreparedStatement#setDate(int parameterIndex, Date x)
+ * preparedStatement.execute() does not return false on update. Setting a
+ * data for a declared INTEGER should throw Exception
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "First exception test fails: integer and date are incompatible"
- +" by spec.",
- method = "setDate",
- args = {int.class, java.sql.Date.class}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update. "+
- "Setting a data for a declared INTEGER should throw Exception")
- public void testSetDate_int_Date() {
+ public void testSetDate_int_Date() throws SQLException {
Calendar cal = new GregorianCalendar(1799, 5, 26);
-
Date[] dates = {
new Date(cal.getTimeInMillis()), new Date(Integer.MAX_VALUE),
new Date(123456789)};
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -1807,13 +1362,9 @@
ps = conn.prepareStatement(query);
for (int i = 0; i < dates.length; i++) {
- try {
- ps.setDate(1, dates[i]);
- assertFalse(ps.execute());
- assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
+ ps.setDate(1, dates[i]);
+ assertFalse(ps.execute());
+ assertTrue(ps.getUpdateCount() > 0);
}
try {
@@ -1843,11 +1394,8 @@
assertEquals("SQLite.Exception: error in prepare", sqle
.getMessage());
}
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
if (ps != null) ps.close();
if (ps1 != null) ps1.close();
} catch (SQLException ee) {
@@ -1855,19 +1403,8 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setDate(int parameterIndex, Date x,
- * Calendar cal)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDate",
- args = {int.class, java.sql.Date.class, java.util.Calendar.class}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update.")
- public void testSetDate_int_Date_Calendar() {
-
+ // preparedStatement.execute() does not return false on update.
+ public void testSetDate_int_Date_Calendar() throws SQLException {
Calendar[] cals = { Calendar.getInstance(),
Calendar.getInstance(Locale.GERMANY),
Calendar.getInstance(TimeZone.getDefault()) };
@@ -1876,7 +1413,6 @@
Date[] dates = { new Date(cal.getTimeInMillis()), new Date(Integer.MAX_VALUE),
new Date(123456789) };
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -1884,14 +1420,9 @@
ps = conn.prepareStatement(query);
for (int i = 0; i < dates.length; i++) {
-
- try {
- ps.setDate(1, dates[i], cals[i]);
- assertFalse(ps.execute());
- assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
+ ps.setDate(1, dates[i], cals[i]);
+ assertFalse(ps.execute());
+ assertTrue(ps.getUpdateCount() > 0);
}
try {
@@ -1913,18 +1444,10 @@
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
- try {
- ps1.setDate(1, dates[0], cals[2]);
- ps1.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown");
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setDate(1, dates[0], cals[2]);
+ ps1.execute();
} finally {
try {
-
if (ps != null) ps.close();
if (ps1 != null) ps1.close();
} catch (SQLException ee) {
@@ -1933,18 +1456,9 @@
}
/**
- * @test java.sql.PreparedStatement#setNull(int parameterIndex, int sqlType)
- *
- * this test doesn't passed on RI
+ * This test doesn't pass on RI
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setNull",
- args = {int.class, int.class}
- )
- public void testSetNull_int_int() {
-
+ public void testSetNull_int_int() throws SQLException {
PreparedStatement ps = null;
try {
String query = "insert into type (BoolVal, IntVal) values ('true', ?);";
@@ -1953,8 +1467,6 @@
try {
ps.setNull(1, Types.INTEGER);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -1968,8 +1480,6 @@
try {
ps.setNull(1, Types.BIGINT);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -1983,8 +1493,6 @@
try {
ps.setNull(1, Types.DECIMAL);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -1998,8 +1506,6 @@
try {
ps.setNull(1, Types.DATE);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -2013,8 +1519,6 @@
try {
ps.setNull(1, Types.BLOB);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
ps.close();
@@ -2024,18 +1528,10 @@
query = "insert into type (BoolVal, TextVal) values ('true', ?);";
ps = conn.prepareStatement(query);
-
- try {
- ps.setNull(1, Types.CHAR);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps.setNull(1, Types.CHAR);
+ ps.execute();
} finally {
try {
-
ps.close();
} catch (Exception ee) {
}
@@ -2043,20 +1539,12 @@
}
/**
- * @test {@link java.sql.PreparedStatement#setNull(int, int, String)}
- *
* UDTs and Ref types not supported in SQLite v 3
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setNull",
- args = {int.class, int.class, java.lang.String.class}
- )
- public void testSetNullIntintString() {
+ public void testSetNullIntintString() throws SQLException {
// test UDT
String typeCreationStmtUDT = "CREATE TYPE addressType AS "
- +"( street INTEGER, zip TEXT);";
+ + "( street INTEGER, zip TEXT);";
String personTableCreateUDT = "CREATE TABLE person (name TEXT, address addressType);";
Statement st = null;
PreparedStatement ps = null;
@@ -2079,10 +1567,9 @@
} catch (Exception ee) {
}
}
-
} catch (SQLException e) {
- // UDTs or Ref types not supported
- // ok
+ // UDTs or Ref types not supported
+ // ok
} finally {
try {
st.execute("drop table if exists person");
@@ -2093,86 +1580,61 @@
// test non UDT REF type Exception checking
String personTableCreate = "create table person (name TEXT, Address TEXT)";
+ try {
+ st = conn.createStatement();
+ st.execute(personTableCreate);
+ String insert
+ = "insert into person (name, address) values (?, '1600 Amphitheatre Mountain View');";
+ ps = conn.prepareStatement(insert);
try {
-
- st = conn.createStatement();
- st.execute(personTableCreate);
- String insert = "insert into person (name, address) values (?, '1600 Amphitheatre Mountain View');";
- ps = conn.prepareStatement(insert);
- try {
- ps.setNull(1,1, "");
- ps.execute();
- } catch (SQLException sqle) {
- assertEquals("SQLite.Exception: error in step",sqle.getMessage());
- } finally {
- try {
- st.close();
- } catch (Exception ee) {
- }
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- e.printStackTrace();
+ ps.setNull(1, 1, "");
+ ps.execute();
+ } catch (SQLException sqle) {
+ assertEquals("SQLite.Exception: error in step", sqle.getMessage());
} finally {
try {
- st.execute("drop table if exists person");
- ps.close();
+ st.close();
} catch (Exception ee) {
}
}
+ } finally {
+ try {
+ st.execute("drop table if exists person");
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
- // test non UDT REF type OK
+ // test non UDT REF type OK
- personTableCreate = "create table person (name TEXT, Address TEXT)";
+ personTableCreate = "create table person (name TEXT, Address TEXT)";
+ try {
+ st = conn.createStatement();
+ st.execute("drop table if exists person");
+ st.execute(personTableCreate);
+ String insert
+ = "insert into person (name, address) values (?, '1600 Amphitheatre Mountain View');";
+ ps = conn.prepareStatement(insert);
+ try {
+ ps.setNull(1, 1, "");
+ ps.execute();
+ } finally {
try {
-
- st = conn.createStatement();
- st.execute("drop table if exists person");
- st.execute(personTableCreate);
- String insert = "insert into person (name, address) values (?, '1600 Amphitheatre Mountain View');";
- ps = conn.prepareStatement(insert);
- try {
- ps.setNull(1,1, "");
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- sqle.printStackTrace();
- } finally {
- try {
- st.close();
- } catch (Exception ee) {
- }
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- e.printStackTrace();
- } finally {
- try {
- st.execute("drop table if exists person");
- ps.close();
- } catch (Exception ee) {
- }
+ st.close();
+ } catch (Exception ee) {
}
-
-
+ }
+ } finally {
+ try {
+ st.execute("drop table if exists person");
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
}
-
- /**
- * @test java.sql.PreparedStatement#setObject(int parameterIndex, Object x)
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setObject",
- args = {int.class, java.lang.Object.class}
- )
- @KnownFailure("exception test fails")
- public void testSetObject_int_Object() {
-
+ // exception test fails
+ public void testSetObject_int_Object() throws SQLException {
PreparedStatement ps = null;
try {
String query = "insert into type (IntVal) values (?);";
@@ -2186,8 +1648,6 @@
+ Integer.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2205,8 +1665,6 @@
st.execute("select * from type where LongVal='test text';");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2236,8 +1694,6 @@
+ d.getTime() + "';");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2252,8 +1708,6 @@
try {
ps.setObject(1, null);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2261,11 +1715,8 @@
}
}
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (Exception ee) {
}
@@ -2279,21 +1730,10 @@
}
- /**
- * @test java.sql.PreparedStatement#setObject(int parameterIndex, Object x,
- * int targetSqlType)
- *
- * this test doesn't pass on RI
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not all types supported",
- method = "setObject",
- args = {int.class, java.lang.Object.class, int.class}
- )
- @KnownFailure("Fails for Types.DATE")
- public void testSetObject_int_Object_int() {
-
+ /**
+ * This test doesn't pass on RI
+ */
+ public void testSetObject_int_Object_int() throws SQLException {
PreparedStatement ps = null;
try {
String query = "insert into type (IntVal) values (?);";
@@ -2307,8 +1747,6 @@
+ Integer.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2326,8 +1764,6 @@
st.execute("select * from type where LongVal='test text';");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2337,19 +1773,13 @@
query = "insert into type (DecVal) values (?);";
ps = conn.prepareStatement(query);
-
- try {
- ps.setObject(1, new Object(), Types.DECIMAL);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
+ ps.setObject(1, new Object(), Types.DECIMAL);
+ ps.execute();
query = "insert into type (dateVal) values (?);";
ps = conn.prepareStatement(query);
Date d = new Date(123456789);
-
try {
ps.setObject(1, d, Types.DATE);
ps.execute();
@@ -2358,8 +1788,6 @@
+ d.getTime() + "';");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2374,20 +1802,14 @@
try {
ps.setObject(1, "", Types.BLOB);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
} catch (Exception ee) {
}
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (Exception ee) {
}
@@ -2399,24 +1821,12 @@
} catch (SQLException e) {
// ok
}
-
}
/**
- * @test java.sql.PreparedStatement#setObject(int parameterIndex, Object x,
- * int targetSqlType, int scale)
- *
- * this test doesn't pass on RI
+ * This test doesn't pass on RI; Fails for Types.DATE
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setObject",
- args = {int.class, java.lang.Object.class, int.class, int.class}
- )
- @KnownFailure("Fails for Types.DATE")
- public void testSetObject_int_Object_int_int() {
-
+ public void testSetObject_int_Object_int_int() throws SQLException {
PreparedStatement ps = null;
try {
String query = "insert into type (IntVal) values (?);";
@@ -2431,8 +1841,6 @@
+ Integer.MAX_VALUE);
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2450,8 +1858,6 @@
st.execute("select * from type where LongVal='test text';");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2462,13 +1868,8 @@
query = "insert into type (DecVal) values (?);";
ps = conn.prepareStatement(query);
BigDecimal bd2 = new BigDecimal("12.21");
-
- try {
- ps.setObject(1, bd2, Types.DECIMAL, 2);
- ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
+ ps.setObject(1, bd2, Types.DECIMAL, 2);
+ ps.execute();
query = "insert into type (dateVal) values (?);";
ps = conn.prepareStatement(query);
@@ -2481,8 +1882,6 @@
+ d.getTime() + "';");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2497,20 +1896,14 @@
try {
ps.setObject(1, "", Types.BLOB, 0);
ps.execute();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
} catch (Exception ee) {
}
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
-
ps.close();
} catch (Exception ee) {
}
@@ -2524,22 +1917,11 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setTime(int parameterIndex, Time x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTime",
- args = {int.class, java.sql.Time.class}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testSetTimeint_Time() {
-
+ // statement.close() does not wrap up
+ public void testSetTimeint_Time() throws SQLException {
Time[] times = { new Time(24, 25, 26), new Time(Integer.MAX_VALUE),
new Time(123456789) };
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -2555,8 +1937,6 @@
+ times[i].getTime() + "'");
ResultSet rs = st.getResultSet();
assertEquals(1, getCount(rs));
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2582,19 +1962,10 @@
}
String query1 = "insert into type (Tint) values (?)";
ps1 = conn.prepareStatement(query1);
-
- try {
- ps1.setTime(1, times[0]);
- ps1.execute();
-
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setTime(1, times[0]);
+ ps1.execute();
} finally {
try {
-
ps.close();
ps1.close();
} catch (Exception ee) {
@@ -2602,19 +1973,8 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setTime(int parameterIndex, Time x,
- * Calendar cal)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTime",
- args = {int.class, java.sql.Time.class, java.util.Calendar.class}
- )
- @KnownFailure("preparedStatement.execute() does not return False on update.")
- public void testSetTime_int_Time_Calendar() {
-
+ // preparedStatement.execute() does not return False on update.
+ public void testSetTime_int_Time_Calendar() throws SQLException {
Calendar[] cals = { Calendar.getInstance(),
Calendar.getInstance(Locale.GERMANY),
Calendar.getInstance(TimeZone.getDefault()) };
@@ -2622,7 +1982,6 @@
Time[] times = { new Time(24, 25, 26), new Time(Integer.MAX_VALUE),
new Time(123456789) };
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -2634,8 +1993,6 @@
ps.setTime(1, times[i], cals[i]);
assertFalse(ps.execute());
assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2661,19 +2018,10 @@
}
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
-
- try {
- ps1.setTime(1, times[0], cals[2]);
- ps1.execute();
-
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setTime(1, times[0], cals[2]);
+ ps1.execute();
} finally {
try {
-
ps.close();
ps1.close();
} catch (Exception ee) {
@@ -2681,23 +2029,11 @@
}
}
- /**
- * @test java.sql.PreparedStatement#setTimestamp(int parameterIndex,
- * Timestamp x)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTimestamp",
- args = {int.class, java.sql.Timestamp.class}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update.")
- public void testSetTimestamp_int_Timestamp() {
-
+ // preparedStatement.execute() does not return false on update.
+ public void testSetTimestamp_int_Timestamp() throws SQLException {
Timestamp[] timestamps = { new Timestamp(2007, 10, 17, 19, 06, 50, 23),
new Timestamp(123) };
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -2705,13 +2041,9 @@
ps = conn.prepareStatement(query);
for (int i = 0; i < timestamps.length; i++) {
- try {
- ps.setTimestamp(1, timestamps[i]);
- assertFalse(ps.execute());
- assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
- }
+ ps.setTimestamp(1, timestamps[i]);
+ assertFalse(ps.execute());
+ assertTrue(ps.getUpdateCount() > 0);
}
try {
@@ -2729,19 +2061,10 @@
}
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
-
- try {
- ps1.setTimestamp(1, timestamps[0]);
- ps1.execute();
-
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setTimestamp(1, timestamps[0]);
+ ps1.execute();
} finally {
try {
-
ps.close();
ps1.close();
} catch (Exception ee) {
@@ -2749,15 +2072,6 @@
}
}
- /**
- * @test {@link java.sql.PreparedStatement#setBlob(int, java.sql.Blob)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setBlob",
- args = {int.class, java.sql.Blob.class}
- )
public void testSetBlob() {
ResultSet res = null;
PreparedStatement ps = null;
@@ -2772,15 +2086,6 @@
}
}
- /**
- * @test {@link java.sql.PreparedStatement#setClob(int, java.sql.Clob)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setClob",
- args = {int.class, java.sql.Clob.class}
- )
public void testSetClob() {
ResultSet res = null;
PreparedStatement ps = null;
@@ -2795,18 +2100,8 @@
}
}
- /**
- * @test {@link java.sql.PreparedStatement#setTimestamp(int, Timestamp, Calendar)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTimestamp",
- args = {int.class, java.sql.Timestamp.class, java.util.Calendar.class}
- )
- @KnownFailure("preparedStatement.execute() does not return false on update.")
- public void testSetTimestampIntTimestampCalendar() {
+ // preparedStatement.execute() does not return false on update.
+ public void testSetTimestampIntTimestampCalendar() throws SQLException {
Calendar[] cals = { Calendar.getInstance(),
Calendar.getInstance(Locale.GERMANY),
Calendar.getInstance(TimeZone.getDefault()) };
@@ -2814,7 +2109,6 @@
Timestamp[] timestamps = { new Timestamp(2007, 10, 17, 19, 06, 50, 23),
new Timestamp(123) };
-
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
@@ -2826,8 +2120,6 @@
ps.setTimestamp(1, timestamps[i], cals[i]);
assertFalse(ps.execute());
assertTrue(ps.getUpdateCount() > 0);
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -2853,19 +2145,10 @@
}
String query1 = "insert into type (Tint) values (?);";
ps1 = conn.prepareStatement(query1);
-
- try {
- ps1.setTimestamp(1, timestamps[0], cals[2]);
- ps1.execute();
-
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.toString());
- }
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ps1.setTimestamp(1, timestamps[0], cals[2]);
+ ps1.execute();
} finally {
try {
-
ps.close();
ps1.close();
} catch (Exception ee) {
@@ -2873,16 +2156,6 @@
}
}
- /**
- * @test {@link java.sql.PreparedStatement#setURL(int, java.net.URL)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setURL",
- args = {int.class, java.net.URL.class}
- )
public void testSetURL() {
ResultSet res = null;
PreparedStatement ps = null;
@@ -2900,16 +2173,6 @@
}
- /**
- * @test {@link java.sql.PreparedStatement#setArray(int, java.sql.Array)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setArray",
- args = {int.class, java.sql.Array.class}
- )
public void testSetArray() {
ResultSet res = null;
PreparedStatement ps = null;
@@ -2928,16 +2191,6 @@
}
- /**
- * @test {@link java.sql.PreparedStatement#setRef(int, java.sql.Ref)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setRef",
- args = {int.class, java.sql.Ref.class}
- )
public void testSetRef() {
ResultSet res = null;
PreparedStatement ps = null;
@@ -2953,16 +2206,6 @@
}
- /**
- * @test {@link java.sql.PreparedStatement#setUnicodeStream(int, java.io.InputStream, int)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setUnicodeStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
public void testSetUnicodestream() {
ResultSet res = null;
PreparedStatement ps = null;
@@ -2981,41 +2224,21 @@
}
}
- public void testSetCharacterSteam() {
- ResultSet res = null;
- PreparedStatement ps = null;
- try {
- String query = "insert into type (TText) values (?);";
- ps = conn.prepareStatement(query);
- InputStream file = Class.forName(this.getClass().getName())
- .getResourceAsStream("/blob.c");
- assertNotNull("Error in test setup: file not found",file);
- Reader reader = new InputStreamReader(file);
- ps.setCharacterStream(1, reader, 100);
- } catch (Exception e) {
- fail("Error in test setup "+e.getMessage());
- e.printStackTrace();
- }
+ public void testSetCharacterSteam() throws SQLException {
+ String query = "insert into type (TText) values (?);";
+ PreparedStatement ps = conn.prepareStatement(query);
+ InputStream file = OldPreparedStatementTest.class.getResourceAsStream("/blob.c");
+ assertNotNull("Error in test setup: file not found",file);
+ Reader reader = new InputStreamReader(file);
+ ps.setCharacterStream(1, reader, 100);
}
- /**
- * @test {@link java.sql.PreparedStatement#setAsciiStream(int, InputStream, int)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setAsciiStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
- public void testSetAxciiStream() {
+ public void testSetAsciiStream() {
ResultSet res = null;
- PreparedStatement ps = null;
try {
String query = "insert into type (TText) values (?);";
- ps = conn.prepareStatement(query);
- InputStream file = Class.forName(this.getClass().getName())
- .getResourceAsStream("/blob.c");
+ PreparedStatement ps = conn.prepareStatement(query);
+ InputStream file = OldPreparedStatementTest.class.getResourceAsStream("/blob.c");
ps.setAsciiStream(0, file, 100);
fail("Exception expected not supported");
} catch (SQLException e) {
@@ -3026,112 +2249,76 @@
}
}
- /**
- * @test {@link java.sql.PreparedStatement#setBinaryStream(int, InputStream, int)}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setBinaryStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
- public void testSetBinaryStream() {
-
- ResultSet res = null;
- PreparedStatement ps = null;
+ public void testSetBinaryStream() throws Exception {
try {
String query = "insert into type (TText) values (?);";
- ps = conn.prepareStatement(query);
- InputStream file = Class.forName(this.getClass().getName())
- .getResourceAsStream("/blob.c");
+ PreparedStatement ps = conn.prepareStatement(query);
+ InputStream file = OldPreparedStatementTest.class.getResourceAsStream("/blob.c");
ps.setBinaryStream(0, file, 100);
fail("Exception expected not supported");
- } catch (SQLException e) {
- // ok
- } catch (Exception e) {
- fail("Error in test setup "+e.getMessage());
- e.printStackTrace();
+ } catch (SQLException expected) {
}
}
private class MockRef implements Ref {
-
public String getBaseTypeName() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Object getObject() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Object getObject(Map<String, Class<?>> map) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
- public void setObject(Object value) throws SQLException {
- // TODO Auto-generated method stub
-
- }
-
+ public void setObject(Object value) throws SQLException {}
}
private class MockArray implements Array {
public Object getArray() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Object getArray(long index, int count) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Object getArray(long index, int count, Map<String, Class<?>> map)
throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Object getArray(Map<String, Class<?>> map) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public int getBaseType() throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public String getBaseTypeName() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public ResultSet getResultSet() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public ResultSet getResultSet(long index, int count)
throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public ResultSet getResultSet(long index, int count,
Map<String, Class<?>> map) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public ResultSet getResultSet(Map<String, Class<?>> map)
throws SQLException {
- // TODO Auto-generated method stub
return null;
}
@@ -3141,48 +2328,39 @@
private class MockBlob implements Blob {
public InputStream getBinaryStream() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public byte[] getBytes(long pos, int length) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public long length() throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public long position(Blob pattern, long start) throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public long position(byte[] pattern, long start) throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public OutputStream setBinaryStream(long pos) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public int setBytes(long pos, byte[] theBytes) throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public int setBytes(long pos, byte[] theBytes, int offset, int len)
throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public void truncate(long len) throws SQLException {
- // TODO Auto-generated method stub
}
@@ -3196,60 +2374,47 @@
private class MockClob implements Clob {
public InputStream getAsciiStream() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Reader getCharacterStream() throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public String getSubString(long pos, int length) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public long length() throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public long position(Clob searchstr, long start) throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public long position(String searchstr, long start) throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public OutputStream setAsciiStream(long pos) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public Writer setCharacterStream(long pos) throws SQLException {
- // TODO Auto-generated method stub
return null;
}
public int setString(long pos, String str) throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
public int setString(long pos, String str, int offset, int len)
throws SQLException {
- // TODO Auto-generated method stub
return 0;
}
- public void truncate(long len) throws SQLException {
- // TODO Auto-generated method stub
-
- }
+ public void truncate(long len) throws SQLException {}
public void free() throws SQLException {}
diff --git a/luni/src/test/java/libcore/java/sql/OldResultSetGetterTests.java b/luni/src/test/java/libcore/java/sql/OldResultSetGetterTests.java
new file mode 100644
index 0000000..1b8b140
--- /dev/null
+++ b/luni/src/test/java/libcore/java/sql/OldResultSetGetterTests.java
@@ -0,0 +1,1458 @@
+/*
+ * Copyright (C) 2007 Google Inc.
+ *
+ * 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.sql;
+
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.sql.DatabaseMetaData;
+import java.sql.Date;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * Tests based on
+ * <a href="http://java.sun.com/products/jdbc/download.html">JDBC 1.0 API spec</a> Table 1.0
+ */
+public final class OldResultSetGetterTests extends OldSQLTest {
+
+ String queryAllSelect = "select * from type";
+
+ ResultSet res = null;
+
+ Statement st = null;
+
+ // Judgement concerning support is based on the result of ResultSet.getOject
+ // and Table 1 of JDBC 1.0 spec.
+ static boolean booleanSupported = false;
+ static boolean blobSupported = false;
+ static boolean bigIntSupported = false;
+ static boolean smallIntSupported = false;
+ static boolean mediumIntSupported = false;
+ static boolean realSupported = false;
+ static boolean floatSupported = false;
+ static boolean dateSupported = false;
+ static boolean timeSupported = false;
+ static boolean timeStampSupported = false;
+ static boolean dateTimeSupported = false;
+ static boolean urlSupported= false;
+ static boolean tinyIntSupported = false;
+ static boolean decimalSupported = false;
+ static boolean numericSupported = false;
+
+ static List<String> colNames = Arrays.asList("BoolVal", "IntVal", "LongVal",
+ "Bint", "Tint", "Sint", "Mint", "IntegerVal", "RealVal",
+ "DoubleVal", "FloatVal", "DecVal", "NumVal", "charStr",
+ "dateVal", "timeVal", "TS", "DT", "TBlob", "BlobVal", "MBlob",
+ "LBlob", "TText", "TextVal", "MText", "LText", "MaxLongVal",
+ "MinLongVal", "validURL", "invalidURL");
+
+ static List<String> values = Arrays.asList("1", "-1", "22", "2", "33",
+ "3","1","2","3.9","23.2","33.3","44",
+ "5", "test string", "1799-05-26", "12:35:45", "2007-10-09 14:28:02.0",
+ "1221-09-22 10:11:55","1","2","3","4","Test text message tiny",
+ "Test text", "Test text message medium",
+ "Test text message long");
+
+ static boolean[] supported = new boolean[]{
+ booleanSupported,
+ true,
+ true,
+ bigIntSupported,
+ tinyIntSupported,
+ smallIntSupported,
+ mediumIntSupported,
+ true,
+ realSupported,
+ true,
+ floatSupported,
+ decimalSupported,
+ numericSupported,
+ true,
+ dateSupported,
+ timeSupported,
+ timeStampSupported,
+ dateTimeSupported,
+ blobSupported,
+ blobSupported,
+ blobSupported,
+ blobSupported,
+ true,
+ true,
+ true,
+ true,
+ bigIntSupported,
+ bigIntSupported,
+ urlSupported,
+ urlSupported
+ };
+
+ // Not supported: BIT,VARBINARY, LONGVARBINARY, BINARY, VARCHAR, LONGVARCHAR
+ static Class[] typeMap = new Class[]{
+ java.lang.String.class, //
+ java.lang.Integer.class,//Types.INTEGER,
+ java.lang.Integer.class, //Types.LONG, not a JDBC 1.0 type
+ java.lang.Long.class, // Types.BIGINT,
+ java.lang.Byte.class, // Types.TINYINT,
+ java.lang.Short.class, // Types.SMALLINT,
+ java.lang.Integer.class, //Types.MEDIUMINT, , not a JDBC 1.0 type
+ java.lang.Integer.class, // Types.Integer
+ java.lang.Float.class, // Types.REAL,
+ java.lang.Double.class, // Types.FLOAT,
+ java.lang.Double.class, // Types.DOUBLE,
+ java.math.BigDecimal.class, // Types.DECIMAL,
+ java.math.BigDecimal.class, // Types.NUMERIC,
+ java.lang.String.class, // Types.CHAR
+ java.sql.Date.class, // Types.DATE,
+ java.sql.Time.class, // Types.TIME,
+ java.sql.Timestamp.class, // Types.TIMESTAMP,
+ java.sql.Date.class, // types datetime, not a JDBC 1.0 type
+ java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
+ java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
+ java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
+ java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
+ java.lang.String.class, // not a JDBC 1.0 type
+ java.lang.String.class, // not a JDBC 1.0 type
+ java.lang.String.class, // not a JDBC 1.0 type
+ java.lang.String.class, // not a JDBC 1.0 type
+ java.lang.Long.class, // Types.BIGINT,
+ java.lang.Long.class, // Types.BIGINT,
+ java.net.URL.class, // not a JDBC 1.0 type
+ java.net.URL.class // not a JDBC 1.0 type
+
+
+ };
+
+ // first inserted row : actual values
+ // second inserted row: null values
+ String[] queries = {
+ "create table type (" +
+
+ " BoolVal BOOLEAN," + " IntVal INT," + " LongVal LONG,"
+ + " Bint BIGINT," + " Tint TINYINT," + " Sint SMALLINT,"
+ + " Mint MEDIUMINT, " +
+
+ " IntegerVal INTEGER, " + " RealVal REAL, "
+ + " DoubleVal DOUBLE, " + " FloatVal FLOAT, "
+ + " DecVal DECIMAL, " +
+
+ " NumVal NUMERIC, " + " charStr CHAR(20), "
+ + " dateVal DATE, " + " timeVal TIME, " + " TS TIMESTAMP, "
+ +
+
+ " DT DATETIME, " + " TBlob TINYBLOB, " + " BlobVal BLOB, "
+ + " MBlob MEDIUMBLOB, " + " LBlob LONGBLOB, " +
+
+ " TText TINYTEXT, " + " TextVal TEXT, "
+ + " MText MEDIUMTEXT, " + " LText LONGTEXT, " +
+
+ " MaxLongVal BIGINT, MinLongVal BIGINT, "+
+
+ " validURL URL, invalidURL URL "+
+
+ ");"
+ ,
+
+ "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
+ + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
+ + "NumVal, charStr, dateVal, timeVal, TS,"
+ + "DT, TBlob, BlobVal, MBlob, LBlob,"
+ + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal,"
+ + " validURL, invalidURL"
+ + ") "
+ + "values (1, -1, 22, 2, 33,"
+ + "3, 1, 2, 3.9, 23.2, 33.3, 44,"
+ + "5, 'test string', '1799-05-26', '12:35:45', '2007-10-09 14:28:02.0',"
+ + "'1221-09-22 10:11:55', 1, 2, 3, 4,"
+ + "'Test text message tiny', 'Test text',"
+ + " 'Test text message medium', 'Test text message long', "
+ + Long.MAX_VALUE+", "+Long.MIN_VALUE+", "
+ + "'http://www.android.com', 'helloWorld' "+
+ ");"
+ ,
+
+ "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
+ + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
+ + "NumVal, charStr, dateVal, timeVal, TS,"
+ + "DT, TBlob, BlobVal, MBlob, LBlob,"
+ + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal,"
+ +" validURL, invalidURL"
+ + ") "
+ + "values (null, null, null, null, null,"
+ + "null, null, null, null, null, null, null,"
+ + "null, null, null, null, null,"
+ + "null, null, null, null, null,"
+ + "null, null, null, null,null, null, null, null);"
+ };
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ conn.setAutoCommit(false);
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.execute(queries[i]);
+ }
+ res = st.executeQuery(queryAllSelect);
+ assertTrue(res.next());
+ }
+
+ public void tearDown() throws SQLException {
+ try {
+ st.execute("drop table if exists type");
+ st.close();
+ res.close();
+ } finally {
+ try {
+ st.close();
+ res.close();
+ } catch (SQLException ee) {
+ }
+ }
+ super.tearDown();
+ }
+
+ public void testGetBytesInt() throws SQLException {
+ int i = 1;
+ // null value
+ i = 1;
+ res.next();
+ for (String t : values) {
+ assertNull(res.getBytes(i));
+ i++;
+ }
+
+ try {
+ res.close();
+ res.getBytes(24);
+ fail("Should get Exception");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ }
+
+ public void testGetBytesIntVarbinary() throws SQLException {
+ Statement st = null;
+ Statement stQuery = null;
+ PreparedStatement stPrep = null;
+ ResultSet res = null;
+
+ // setup
+ try {
+ String testString = "HelloWorld";
+ st = conn.createStatement();
+ st.executeUpdate("create table testBinary (VARBINARY value);");
+ stPrep = conn
+ .prepareStatement("insert into testBinary values (?);");
+ stPrep.setBytes(1, testString.getBytes());
+ stPrep.execute();
+
+ stQuery = conn.createStatement();
+ res = stQuery.executeQuery("select * from testBinary");
+ assertTrue(res.next());
+ byte[] output = res.getBytes(1);
+ String helloTest = new String(output);
+ assertNotNull(helloTest);
+ assertEquals(testString, helloTest);
+ } finally {
+ if (res != null) res.close();
+ if (stPrep != null) stPrep.close();
+ if (st != null) st.close();
+ if (stQuery != null) stQuery.close();
+ }
+ }
+
+ public void testGetBytesIntBinary() throws SQLException {
+
+ Statement st = null;
+ Statement stQuery = null;
+ PreparedStatement stPrep = null;
+ ResultSet res = null;
+
+
+ // setup
+
+ String testString = "HelloWorld";
+ st = conn.createStatement();
+ st.executeUpdate("create table testBinary (BINARY value);");
+ stPrep = conn.prepareStatement("insert into testBinary values (?);");
+ stPrep.setBytes(1, testString.getBytes());
+ stPrep.execute();
+ try {
+ stQuery = conn.createStatement();
+ res = stQuery.executeQuery("select * from testBinary");
+ assertTrue(res.next());
+ byte[] output = res.getBytes(1);
+ String helloTest = new String(output);
+ assertNotNull(helloTest);
+ assertEquals(testString, helloTest);
+ } finally {
+ if (res != null) res.close();
+ if (stPrep != null) stPrep.close();
+ if (st != null) st.close();
+ if (stQuery != null) stQuery.close();
+ }
+ }
+
+ public void testGetBytesString() throws SQLException {
+ int i = 1;
+
+ // null value
+ res.next();
+ for (String t : colNames) {
+ assertNull(res.getBytes(t));
+ }
+
+ try {
+ res.close();
+ res.getBytes(colNames.get(24));
+ fail("Should get Exception");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // last assertion fails: invalid conversion. Test passes on RI
+ public void testGetBytesStringVarbinary() throws SQLException {
+ Statement st = null;
+ Statement stQuery = null;
+ PreparedStatement stPrep = null;
+ ResultSet res = null;
+
+ // setup
+ try {
+ String testString = "HelloWorld";
+ st = conn.createStatement();
+ st.executeUpdate("create table testBinary (VARBINARY value);");
+ stPrep = conn
+ .prepareStatement("insert into testBinary values (?);");
+ stPrep.setBytes(1, testString.getBytes());
+ stPrep.execute();
+
+ stQuery = conn.createStatement();
+ res = stQuery.executeQuery("select value from testBinary");
+ assertTrue(res.next());
+ byte[] output = res.getBytes("value");
+ String helloTest = new String(output);
+ assertNotNull(helloTest);
+ assertEquals(testString, helloTest);
+ } finally {
+ if (res != null) res.close();
+ if (stPrep != null) stPrep.close();
+ if (st != null) st.close();
+ if (stQuery != null) stQuery.close();
+ }
+
+ }
+
+ // last assertion fails: invalid conversion. Test passes on RI
+ public void testGetBytesStringBinary() throws SQLException {
+ Statement st = null;
+ Statement stQuery = null;
+ PreparedStatement stPrep = null;
+ ResultSet res = null;
+
+ // setup
+
+ String testString = "HelloWorld";
+ st = conn.createStatement();
+ st.executeUpdate("create table testBinary (BINARY value);");
+ stPrep = conn.prepareStatement("insert into testBinary values (?);");
+ stPrep.setBytes(1, testString.getBytes());
+ stPrep.execute();
+ try {
+ stQuery = conn.createStatement();
+ res = stQuery.executeQuery("select value from testBinary");
+ assertTrue(res.next());
+ byte[] output = res.getBytes("value");
+ String helloTest = new String(output);
+ assertNotNull(helloTest);
+ assertEquals(testString, helloTest);
+ } finally {
+ if (res != null) res.close();
+ if (stPrep != null) stPrep.close();
+ if (st != null) st.close();
+ if (stQuery != null) stQuery.close();
+ }
+ }
+
+ public void testGetConcurrency() throws SQLException {
+ assertEquals(ResultSet.CONCUR_UPDATABLE, res.getConcurrency());
+ }
+
+ public void testGetDateInt() throws SQLException {
+ GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
+ Date input = new Date(testCal.getTimeInMillis());
+ Date d = res.getDate(15);
+ assertEquals(input.toString(),"1799-05-26");
+ assertEquals(input,d);
+
+ try {
+ d = res.getDate(500);
+ fail("Should get exception");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ // null value
+ assertTrue(res.next());
+ d = res.getDate(15);
+ assertNull(d);
+ }
+
+ public void testGetDateIntCalendar() throws SQLException {
+ GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
+ Date input = new Date(testCal.getTimeInMillis());
+ Date d = res.getDate(15, testCal);
+
+ assertEquals(input.toString(),"1799-05-26");
+ assertEquals(input,d);
+
+ try {
+ d = res.getDate(500, testCal);
+ fail("Should get exception");
+ } catch (SQLException e) {
+ //ok
+ }
+
+
+ // null value
+ assertTrue(res.next());
+ d = res.getDate(15,testCal);
+ assertNull(d);
+ }
+
+ public void testGetDateString() throws SQLException {
+ GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
+ Date input = new Date(testCal.getTimeInMillis());
+ Date d = res.getDate("dateVal");
+ assertEquals(input.toString(),"1799-05-26");
+ assertEquals(input,d);
+
+ try {
+ d = res.getDate("bla");
+ fail("Should get exception");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ // null value
+ assertTrue(res.next());
+ d = res.getDate("dateVal");
+ assertNull(d);
+ }
+
+ public void testGetDateStringCalendar() throws SQLException {
+ GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
+ Date input = new Date(testCal.getTimeInMillis());
+ Date d = res.getDate("dateVal", testCal);
+ assertEquals(input.toString(),"1799-05-26");
+ assertEquals(input,d);
+
+ try {
+ res.getDate("bla", testCal);
+ fail("Should get exception");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ // null value
+ assertTrue(res.next());
+ d = res.getDate("dateVal",testCal);
+ assertNull(d);
+ }
+
+ public void testGetDoubleInt() throws SQLException {
+ double output = 0.0;
+ double[] input = {2.0, 3.9 , 23.2};
+
+ output = res.getDouble(8);
+ assertEquals(input[0],output);
+
+ output = res.getDouble(9);
+ assertEquals(input[1],output);
+
+ output = res.getDouble(10);
+ assertEquals(input[2],output);
+
+ try {
+ res.getDouble(500);
+ } catch (SQLException e) {
+ //ok
+ }
+
+ // null value
+ res.next();
+ output = res.getDouble(8);
+ assertEquals(0.0,output);
+
+ output = res.getDouble(9);
+ assertEquals(0.0,output);
+
+ output = res.getDouble(10);
+ assertEquals(0.0,output);
+ }
+
+ public void testGetDoubleString() throws SQLException {
+ double input = 23.2;
+ double output = 0.0;
+
+ output = res.getDouble("DoubleVal");
+ assertEquals (input,output);
+
+ try{
+ res.getDouble("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+
+ // null value
+ assertTrue(res.next());
+ output = res.getDouble("DoubleVal");
+ assertEquals (0.0 , output);
+ }
+
+ public void testGetFloatInt() throws SQLException {
+ float defaultF = 0.0f;
+ float[] input = {3.9f, 23.2f, 33.3f};
+
+ float output = res.getFloat(9);
+ assertEquals(input[0], output);
+
+ output = res.getFloat(10);
+ assertEquals(input[1], output);
+
+ output = res.getFloat(11);
+ assertEquals(input[2], output);
+
+ try {
+ res.getFloat(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ output = res.getFloat(8);
+ assertEquals(defaultF, output);
+
+ output = res.getFloat(9);
+ assertEquals(defaultF, output);
+
+ output = res.getFloat(10);
+ assertEquals(defaultF, output);
+ }
+
+ public void testGetFloatString() throws SQLException {
+ float defaultF = 0.0f;
+ String[] input = {"RealVal", "DoubleVal", "FloatVal"};
+ float[] inputF = {3.9f, 23.2f, 33.3f};
+
+ float output = res.getFloat(input[0]);
+ assertEquals(inputF[0], output);
+
+ output = res.getFloat(input[1]);
+ assertEquals(inputF[1], output);
+
+ output = res.getFloat(input[2]);
+ assertEquals(inputF[2], output);
+
+ try {
+ res.getFloat(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ output = res.getFloat(8);
+ assertEquals(defaultF, output);
+
+ output = res.getFloat(9);
+ assertEquals(defaultF, output);
+
+ output = res.getFloat(10);
+ assertEquals(defaultF, output);
+ }
+
+ public void testGetIntInt() throws SQLException {
+ // real input val -1, 22, 2, 33,3, 1, 2
+ List<Integer> input = Arrays.asList(1, -1, 22, 2, 33,3, 1, 2);
+ ListIterator<Integer> it = input.listIterator();
+ Double test2 = new Double(23.2);
+ for (int i = 1;i<9;i++ ) {
+ assertEquals(it.next().intValue(),res.getInt(i));
+ }
+
+ try {
+ res.getInt(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ for (int i = 2;i<11;i++ ) {
+ assertEquals(0,res.getInt(i));
+ }
+ }
+
+ public void testGetIntString() throws SQLException {
+ List<String> inputS = Arrays.asList("BoolVal", "IntVal", "LongVal",
+ "Bint", "Tint", "Sint", "Mint", "IntegerVal");
+ ListIterator<String> itS = inputS.listIterator();
+ List<Integer> input = Arrays.asList(1, -1, 22, 2, 33, 3, 1, 2);
+ ListIterator<Integer> it = input.listIterator();
+ while (it.hasNext()) {
+ assertEquals(it.next().intValue(), res.getInt(itS.next()));
+ }
+
+ try {
+ res.getInt("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ for (String s : inputS) {
+ assertEquals(0, res.getInt(s));
+ }
+ }
+
+ public void testGetLongInt() throws SQLException {
+ long maxVal = Long.MAX_VALUE;
+ long minVal = Long.MIN_VALUE;
+
+ assertEquals(maxVal, res.getLong(27));
+ assertEquals(minVal, res.getLong(28));
+
+ try {
+ res.getInt(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ assertEquals(0, res.getLong(27));
+ assertEquals(0, res.getLong(28));
+ }
+
+ public void testGetLongString() throws SQLException {
+ long maxVal = Long.MAX_VALUE;
+ long minVal = Long.MIN_VALUE;
+ assertEquals(maxVal, res.getLong("MaxLongVal"));
+ assertEquals(minVal, res.getLong("MinLongVal"));
+
+ try {
+ res.getInt("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ assertEquals(0,res.getLong("MaxLongVal"));
+ assertEquals(0,res.getLong("MinLongVal"));
+ }
+
+ /**
+ * Test method for {@link java.sql.ResultSet#getMetaData()}.
+ * type mappings according to
+ * http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec/jdbc-spec.frame8.html
+ * Not supported datatypes are not checked.
+ *
+ * Wrong value returned for Long: java.lang.String (VARCHAR)
+ */
+ public void testGetMetaData() throws SQLException {
+ /*
+ * List<String> types = Arrays.asList("BOOLEAN", "INT", "LONG",
+ * "BIGINT", "TINYINT", "SMALLINT", "MEDIUMINT", "INTEGER", "REAL",
+ * "DOUBLE", "FLOAT", "DECIMAL", "NUMERIC", "CHAR(20)", "DATE", "TIME",
+ * "TIMESTAMP", "DATETIME", "TINYBLOB", "BLOB", "MEDIUMBLOB",
+ * "LONGBLOB", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT", "BIGINT",
+ * "BIGINT","URL","URL");
+ */
+ List<String> types = Arrays.asList("VARCHAR", "INTEGER", "INTEGER",
+ "BIGINT", "SMALLINT", "SHORT", "INTEGER", "INTEGER", "FLOAT",
+ "DOUBLE", "DOUBLE", "DECIMAL", "NUMERIC", "VARCHAR", "DATE",
+ "TIME", "TIMESTAMP", "DATETIME", "BLOB", "BLOB", "BLOB",
+ "BLOB", "VARCHAR", "VARCHAR", "VARCHAR", "VARCHAR", "BIGINT",
+ "BIGINT", "URL", "URL");
+
+
+
+ ListIterator<String> it = types.listIterator();
+ ListIterator<String> colNameIt = colNames.listIterator();
+ ResultSetMetaData meta = res.getMetaData();
+ assertNotNull(meta);
+ assertEquals("Error in test setup. Columns do not match", types
+ .size(), meta.getColumnCount());
+ for (int i = 1; i < 31; i++) {
+ String colName = colNameIt.next();
+ String type = it.next();
+ if (supported[i - 1]) {
+ assertTrue("Wrong column name at " + i, colName
+ .equalsIgnoreCase(meta.getColumnName(i)));
+ assertTrue("Wrong type at " + i+" required" +type+ " but is "+meta.getColumnTypeName(i), type.equalsIgnoreCase(meta
+ .getColumnTypeName(i)));
+ }
+ }
+ }
+
+ // Wrong value returned for Long: java.lang.String
+ public void testGetObjectInt() throws SQLException {
+ for (int i = 1; i <= typeMap.length; i++) {
+ if (supported[i-1]) {
+ Object value = res.getObject(i);
+ assertTrue("value " + value.getClass().getName()
+ + " does not correspond " + typeMap[i-1] + "at "+i, value
+ .getClass().equals(typeMap[i-1]));
+ }
+ }
+
+ try {
+ res.getObject(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ res.next();
+ for (int i = 1; i <= typeMap.length; i++) {
+ Object value = res.getObject(i);
+ assertNull(value);
+ }
+ }
+
+ // Wrong value returned for Long: java.lang.String
+ public void testGetObjectString() throws SQLException {
+ ListIterator<String> colNameIt = colNames.listIterator();
+ for (int i = 1; i <= typeMap.length; i++) {
+ String name = colNameIt.next();
+ if (supported[i-1]) {
+ Object value = res.getObject(name);
+ assertTrue("value " + value.getClass().getName()
+ + " for "+name+" does not correspond " + typeMap[i-1] + "at "+i, value
+ .getClass().equals(typeMap[i-1]));
+ }
+ }
+
+ try {
+ res.getObject("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+
+ colNameIt = colNames.listIterator();
+ res.next();
+ for (int i = 1; i <= typeMap.length; i++) {
+ Object value = res.getObject(colNameIt.next());
+ assertNull(value);
+ }
+ }
+
+ // If there is no current row 0 must be returned. res.close() does not wrap up
+ public void testGetRow() throws SQLException {
+ assertEquals(1, res.getRow());
+ assertTrue(res.isFirst());
+ res.next();
+ assertEquals(2, res.getRow());
+ assertTrue(res.isLast());
+ res.next();
+ assertTrue(res.isAfterLast());
+ assertEquals(0, res.getRow());
+
+ try {
+ res.close();
+ res.getRow();
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ public void testGetShortInt() throws SQLException {
+ short shorty = res.getShort(6);
+ assertEquals(3,shorty);
+
+ res.next();
+ shorty = res.getShort(6);
+ assertEquals(0,shorty);
+
+ try {
+ res.getShort(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ public void testGetShortString() throws SQLException {
+ short shorty = res.getShort("Sint");
+ assertEquals(3,shorty);
+
+ res.next();
+ shorty = res.getShort("Sint");
+ assertEquals(0,shorty);
+
+ try {
+ res.getShort("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ /**
+ * According to spec info.getStatement should return null but an exception
+ * is thrown: stale result set.
+ */
+ public void testGetStatement() throws SQLException {
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet info = meta.getTypeInfo();
+ Statement statement2 = info.getStatement();
+ assertNull(statement2);
+
+ statement2 = res.getStatement();
+ assertEquals(st, statement2);
+
+ // exception testing
+ try {
+ res.close();
+ res.getStatement();
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ public void testGetStringInt() throws SQLException {
+ List<String> texts = Arrays.asList("Test text message tiny",
+ "Test text", "Test text message medium",
+ "Test text message long");
+ int i = 23;
+
+ //text and exception testing
+ for (String t : texts) {
+ assertEquals(t, res.getString(i));
+ i++;
+ }
+
+ // the rest: everything should work with getString
+
+ texts = Arrays.asList("1", "-1", "22", "2", "33",
+ "3","1","2","3.9","23.2","33.3","44",
+ "5", "test string", "1799-05-26", "12:35:45", "2007-10-09 14:28:02.0",
+ "1221-09-22 10:11:55","1","2","3","4");
+ i= 1;
+
+ for (String t : texts) {
+ assertEquals(t, res.getString(i));
+ i++;
+ }
+
+ //null testing
+ i = 1;
+ res.next();
+ for (String t : values) {
+ assertNull(res.getString(i));
+ i++;
+ }
+
+ // exception testing
+ try {
+ res.getString(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ }
+
+ public void testGetStringString() throws SQLException {
+ ListIterator<String> colNameIt = colNames.listIterator();
+ for (String t : values) {
+ assertEquals(t, res.getString(colNameIt.next()));
+ }
+
+ res.next();
+ for (String name: colNames) {
+ assertNull(res.getString(name));
+ }
+
+ try {
+ res.getString("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // getTime should return Time value for a TIMESTAMP type but returns null
+ public void testGetTimeInt() throws SQLException {
+ // values "12:35:45", "2007-10-09 14:28:02.0", "1221-09-22 10:11:55"
+
+ Calendar cal = new GregorianCalendar();
+ cal.clear();
+ cal.set(Calendar.HOUR_OF_DAY, 12);
+ cal.set(Calendar.MINUTE, 35);
+ cal.set(Calendar.SECOND, 45);
+ cal.set(Calendar.MILLISECOND, 0);
+ // set with calendar value (correct init time: since epoch)
+ long millis = cal.getTime().getTime();
+ Time t1 = new java.sql.Time(millis);
+ assertNotNull("t1", t1);
+
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis2 = cal2.getTime().getTime();
+ Time t2 = new java.sql.Time(millis2);
+
+ int i = 16;
+
+ Time resTime = res.getTime(i);
+ assertNotNull("Pos " + i + " null", resTime);
+ assertEquals(t1.toString(), resTime.toString());
+ assertEquals(t1.getTime(), resTime.getTime());
+ assertEquals(t1, resTime);
+ // Compatibility Test: TIMESTAMP value
+ i = 17;
+
+ resTime = res.getTime(i);
+ assertNotNull("Pos " + i + " null", resTime);
+ assertEquals(t2.toString(), resTime.toString());
+ assertEquals(t2.getTime(), resTime.getTime());
+ assertEquals(t2, resTime);
+
+ i = 16;
+ res.next();
+ assertNull(res.getTime(i));
+
+ try {
+ res.getTime(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ // getTime on TIMESTAMP value fails: returns null
+ public void testGetTimeIntCalendar() throws SQLException {
+ List<Time> times = new LinkedList<Time>();
+ List<Calendar> cals = new LinkedList<Calendar>();
+ // Arrays.asList("12:35:45", "2007-10-09 14:28:02.0",
+ // "1221-09-22 10:11:55");
+
+ Calendar cal1 = new GregorianCalendar();
+ cal1.clear();
+ cal1.set(Calendar.HOUR_OF_DAY, 12);
+ cal1.set(Calendar.MINUTE, 35);
+ cal1.set(Calendar.SECOND, 45);
+ cal1.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal1.getTime().getTime();
+ Time t1 = new java.sql.Time(millis);
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis2 = cal2.getTime().getTime();
+ Time t2 = new java.sql.Time(millis2);
+
+ // TIME value
+
+ int i = 16;
+
+ Time timeRes = res.getTime(i,new GregorianCalendar());
+ assertNotNull(timeRes);
+ assertEquals(t1.toString(), timeRes.toString());
+ assertEquals(t1.getTime(), timeRes.getTime());
+ assertEquals(t1, timeRes);
+
+ // TIMESTAMP value
+ i = 17;
+
+ timeRes = res.getTime(i,new GregorianCalendar());
+ assertNotNull(timeRes);
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.getTime(), timeRes.getTime());
+ assertEquals(t2, timeRes);
+
+ res.next();
+ for (Calendar c : cals) {
+ assertNull(res.getTime(16,c));
+ i++;
+ }
+
+ try {
+ res.getTime(500,Calendar.getInstance());
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // getTime should return a Time value for a TIMESTAMP type but returns null
+ public void testGetTimeString() throws SQLException {
+ List<Time> times = new LinkedList<Time>();
+
+ List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
+ Iterator<String> it = stringTimes.iterator();
+
+ // Arrays.asList("12:35:45", "2007-10-09 14:28:02.0",
+ // "1221-09-22 10:11:55");
+
+ Calendar cal = new GregorianCalendar();
+ cal.clear();
+ cal.set(Calendar.HOUR_OF_DAY, 12);
+ cal.set(Calendar.MINUTE, 35);
+ cal.set(Calendar.SECOND, 45);
+ cal.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal.getTime().getTime();
+ Time t1 = new java.sql.Time(millis);
+
+ String col = it.next();
+
+ Time timeRes = res.getTime(col);
+ assertNotNull(timeRes);
+ assertEquals(t1.toString(), timeRes.toString());
+ assertEquals(t1.getTime(), timeRes.getTime());
+ assertEquals(t1, timeRes);
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis2 = cal.getTime().getTime();
+ Time t2 = new java.sql.Time(millis2);
+
+ col = it.next();
+
+ timeRes = res.getTime(col);
+ assertNotNull(timeRes);
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.getTime(), timeRes.getTime());
+ assertEquals(t2, timeRes);
+
+ res.next();
+ assertNull(res.getTime(col));
+
+ try {
+ res.getTime("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // getTime on TIMESTAMP value fails: returns null
+ public void testGetTimeStringCalendar() throws SQLException {
+ List<Time> times = new LinkedList<Time>();
+
+ List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
+ Iterator<String> it = stringTimes.iterator();
+ List<Calendar> cals = new LinkedList<Calendar>();
+
+ // Arrays.asList("12:35:45", "2007-10-09 14:28:02.0",
+ // "1221-09-22 10:11:55");
+
+ Calendar cal1 = new GregorianCalendar();
+ cal1.clear();
+ cal1.set(Calendar.HOUR_OF_DAY, 12);
+ cal1.set(Calendar.MINUTE, 35);
+ cal1.set(Calendar.SECOND, 45);
+ cal1.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal1.getTime().getTime();
+ Time t1 = new java.sql.Time(millis);
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis2 = cal2.getTime().getTime();
+ Time t2 = new java.sql.Time(millis2);
+
+ // TIME value
+ String col = it.next();
+
+ Time timeRes = res.getTime(col, new GregorianCalendar());
+ assertNotNull(timeRes);
+ assertEquals(t1.toString(), timeRes.toString());
+ assertEquals(t1.getTime(), timeRes.getTime());
+ assertEquals(t1, res.getTime(col));
+ //TIMESTAMP value
+ col = it.next();
+
+ timeRes = res.getTime(col, new GregorianCalendar());
+ assertNotNull(timeRes);
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.getTime(), timeRes.getTime());
+ assertEquals(t2, res.getTime(col));
+
+ res.next();
+ assertNull(res.getTime(stringTimes.get(0), new GregorianCalendar()));
+
+ try {
+ res.getTime("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ public void testGetTimestampInt() throws SQLException {
+ List<Timestamp> times = new LinkedList<Timestamp>();
+
+ List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
+ Iterator<String> it = stringTimes.iterator();
+ List<Calendar> cals = new LinkedList<Calendar>();
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal2.getTime().getTime();
+ Timestamp t2 = new Timestamp(millis);
+ times.add(t2);
+
+ Calendar cal3 = new GregorianCalendar();
+ cal3.set(Calendar.YEAR, 1221);
+ cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
+ cal3.set(Calendar.DATE, 22);
+ cal3.set(Calendar.HOUR_OF_DAY, 10);
+ cal3.set(Calendar.MINUTE, 11);
+ cal3.set(Calendar.SECOND, 55);
+ cal3.set(Calendar.MILLISECOND, 0);
+
+ millis = cal3.getTime().getTime();
+ Timestamp t3 = new Timestamp(millis);
+ times.add(t3);
+ // TIMESTAMP value
+ int i = 17;
+
+ Timestamp timeRes = res.getTimestamp(i);
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.getTime(), timeRes.getTime());
+ assertEquals(t2, timeRes);
+ // DATE value
+ i = 18;
+ timeRes = res.getTimestamp(i);
+ assertEquals(t3.toString(), timeRes.toString());
+ assertEquals(t3.getTime(), timeRes.getTime());
+ assertEquals(t3, timeRes);
+
+ res.next();
+ assertNull(res.getTime(i));
+
+ try {
+ res.getTime(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ public void testGetTimestampIntCalendar() throws SQLException {
+ List<Timestamp> times = new LinkedList<Timestamp>();
+
+ List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
+ Iterator<String> it = stringTimes.iterator();
+// List<Calendar> cals = new LinkedList<Calendar>();
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal2.getTime().getTime();
+ Timestamp t2 = new Timestamp(millis);
+ times.add(t2);
+ //
+ Calendar cal3 = new GregorianCalendar();
+ cal3.set(Calendar.YEAR, 1221);
+ cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
+ cal3.set(Calendar.DATE, 22);
+ cal3.set(Calendar.HOUR_OF_DAY, 10);
+ cal3.set(Calendar.MINUTE, 11);
+ cal3.set(Calendar.SECOND, 55);
+ cal3.set(Calendar.MILLISECOND, 0);
+
+ millis = cal3.getTime().getTime();
+ Timestamp t3 = new Timestamp(millis);
+ times.add(t3);
+
+// cals.add(cal1);
+// cals.add(cal2);
+// cals.add(cal3);
+//
+// ListIterator<Calendar> calIt = cals.listIterator();
+
+ int i = 17;
+
+ Timestamp timeRes = res.getTimestamp(i,new GregorianCalendar());
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2, timeRes);
+
+ i = 18;
+
+ timeRes = res.getTimestamp(i,new GregorianCalendar());
+ assertEquals(t3.toString(), timeRes.toString());
+ assertEquals(t3, timeRes);
+
+ res.next();
+ assertNull(res.getTime(17,cal2));
+ assertNull(res.getTime(18,cal3));
+
+ try {
+ res.getTime(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ public void testGetTimestampString() throws SQLException {
+ List<Timestamp> times = new LinkedList<Timestamp>();
+
+ List<String> stringTimes = Arrays.asList( "TS", "DT");
+ Iterator<String> it = stringTimes.iterator();
+// List<Calendar> cals = new LinkedList<Calendar>();
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal2.getTime().getTime();
+ Timestamp t2 = new Timestamp(millis);
+ times.add(t2);
+ //
+ Calendar cal3 = new GregorianCalendar();
+ cal3.set(Calendar.YEAR, 1221);
+ cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
+ cal3.set(Calendar.DATE, 22);
+ cal3.set(Calendar.HOUR_OF_DAY, 10);
+ cal3.set(Calendar.MINUTE, 11);
+ cal3.set(Calendar.SECOND, 55);
+ cal3.set(Calendar.MILLISECOND, 0);
+
+ millis = cal3.getTime().getTime();
+ Timestamp t3 = new Timestamp(millis);
+ times.add(t3);
+
+ String col = it.next();
+
+ Timestamp timeRes = res.getTimestamp(col);
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.getTime(), timeRes.getTime());
+ assertEquals(t2, timeRes);
+ // DATE value
+ col = it.next();
+
+ timeRes = res.getTimestamp(col);
+ assertEquals(t3.toString(), timeRes.toString());
+ assertEquals(t3.toString(), timeRes.toString());
+ assertEquals(t3.getTime(), timeRes.getTime());
+ assertEquals(t3, timeRes);
+
+ res.next();
+ assertNull(res.getTime(stringTimes.get(0)));
+ assertNull(res.getTime(stringTimes.get(1)));
+
+ try {
+ res.getTime(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ public void testGetTimestampStringCalendar() throws SQLException {
+ List<Timestamp> times = new LinkedList<Timestamp>();
+
+ List<String> stringTimes = Arrays.asList( "TS", "DT");
+ Iterator<String> it = stringTimes.iterator();
+
+ Calendar cal2 = new GregorianCalendar();
+ cal2.set(Calendar.YEAR, 2007);
+ cal2.set(Calendar.MONTH, Calendar.OCTOBER);
+ cal2.set(Calendar.DATE, 9);
+ cal2.set(Calendar.HOUR_OF_DAY, 14);
+ cal2.set(Calendar.MINUTE, 28);
+ cal2.set(Calendar.SECOND, 02);
+ cal2.set(Calendar.MILLISECOND, 0);
+
+ long millis = cal2.getTime().getTime();
+ Timestamp t2 = new Timestamp(millis);
+ times.add(t2);
+ //
+ Calendar cal3 = new GregorianCalendar();
+ cal3.set(Calendar.YEAR, 1221);
+ cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
+ cal3.set(Calendar.DATE, 22);
+ cal3.set(Calendar.HOUR_OF_DAY, 10);
+ cal3.set(Calendar.MINUTE, 11);
+ cal3.set(Calendar.SECOND, 55);
+ cal3.set(Calendar.MILLISECOND, 0);
+
+ millis = cal3.getTime().getTime();
+ Timestamp t3 = new Timestamp(millis);
+ times.add(t3);
+
+ Timestamp timeRes = res.getTimestamp(stringTimes.get(0),cal2);
+ assertEquals(t2.toString(), timeRes.toString());
+ assertEquals(t2.getTime(), timeRes.getTime());
+ assertEquals(t2, timeRes);
+ // DATE value
+ timeRes = res.getTimestamp(stringTimes.get(1),cal3);
+ assertEquals(t3.toString(), timeRes.toString());
+ assertEquals(t3.getTime(), timeRes.getTime());
+ assertEquals(t3, timeRes);
+
+ // calIt = cals.listIterator();
+
+ res.next();
+ assertNull(res.getTime(stringTimes.get(0),cal2));
+ assertNull(res.getTime(stringTimes.get(1),cal3));
+
+ try {
+ res.getTime(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ // res.close() does not wrap up
+ public void testGetType() throws SQLException {
+ assertEquals(ResultSet.TYPE_FORWARD_ONLY, res.getType());
+
+ try {
+ st.close();
+ res.getType();
+ fail("Exception not thrown.");
+ } catch (SQLException e) {
+ //ok
+ }
+
+ }
+
+ public void testGetURLInt() throws SQLException, MalformedURLException {
+ URL input = new URL("http://www.android.com");
+ URL validURL = res.getURL(29);
+ assertEquals(input, validURL);
+
+ try {
+ URL invalidURL = res.getURL(30);
+ assertNull(invalidURL);
+ } catch (SQLException e) {
+ // ok
+ }
+
+ res.next();
+ assertNull(res.getURL(29));
+ assertNull(res.getURL(30));
+
+ try {
+ res.getURL(500);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ public void testGetURLString() throws MalformedURLException, SQLException {
+ URL input = new URL("http://www.android.com");
+ URL validURL = res.getURL("validURL");
+ assertEquals(input, validURL);
+
+ try {
+ URL invalidURL = res.getURL("invalidURL");
+ assertNull(invalidURL);
+ } catch (SQLException e) {
+ // ok
+ }
+
+ res.next();
+ assertNull(res.getURL("validURL"));
+ assertNull(res.getURL("invalidURL"));
+
+ try {
+ res.getURL("bla");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/sql/ResultSetMetaDataTest.java b/luni/src/test/java/libcore/java/sql/OldResultSetMetaDataTest.java
similarity index 71%
rename from luni/src/test/java/tests/sql/ResultSetMetaDataTest.java
rename to luni/src/test/java/libcore/java/sql/OldResultSetMetaDataTest.java
index 429a75f..4dbcdfd 100755
--- a/luni/src/test/java/tests/sql/ResultSetMetaDataTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldResultSetMetaDataTest.java
@@ -14,23 +14,15 @@
* limitations under the License.
*/
-package tests.sql;
+package libcore.java.sql;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
-@TestTargetClass(ResultSetMetaData.class)
-public class ResultSetMetaDataTest extends SQLTest {
+public final class OldResultSetMetaDataTest extends OldSQLTest {
ResultSetMetaData rsmd = null;
Statement st = null;
@@ -53,7 +45,7 @@
}
@Override
- public void tearDown() {
+ public void tearDown() throws SQLException {
try {
rs.close();
st.close();
@@ -63,16 +55,7 @@
super.tearDown();
}
- /**
- * @test java.sql.ResultSetMetaData#getCatalogName(int column)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Catalog not supported.",
- method = "getCatalogName",
- args = {int.class}
- )
- @KnownFailure("not supported")
+ // not supported
public void testGetCatalogName() throws SQLException {
try {
assertNotNull(rsmd.getCatalogName(1));
@@ -89,15 +72,6 @@
}
}
- /**
- * @test java.sql.ResultSetMetaData#getColumnClassName(int column)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getColumnClassName",
- args = {int.class}
- )
public void testGetColumnClassName() {
try {
assertNotNull(rsmd);
@@ -123,16 +97,7 @@
}
}
- /**
- * @test java.sql.ResultSetMetaData#getColumnCount()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException checking test fails",
- method = "getColumnCount",
- args = {}
- )
- @KnownFailure("SQLException checking test fails")
+ // SQLException checking test fails
public void testGetColumnCount() {
try {
assertEquals(3, rsmd.getColumnCount());
@@ -150,16 +115,7 @@
}
- /**
- * @test java.sql.ResultSetMetaData#getColumnLabel(int column)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getColumnLabel",
- args = {int.class}
- )
- @KnownFailure("Column label has format TABLE.COLUMN expected: COLUMN")
+ // Column label has format TABLE.COLUMN expected: COLUMN
public void testGetColumnLabel() {
String[] labels = { "id", "name", "family" };
try {
@@ -186,16 +142,7 @@
}
}
- /**
- * @test java.sql.ResultSetMetaData#getColumnName(int column)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getColumnName",
- args = {int.class}
- )
- @KnownFailure("Column label has format TABLE.COLUMN expected: COLUMN")
+ // Column label has format TABLE.COLUMN expected: COLUMN
public void testGetColumnName() {
String[] labels = { "id", "name", "family" };
try {
@@ -223,16 +170,8 @@
}
/**
- * @test java.sql.ResultSetMetaData#getColumnType(int column)
- *
- * for extensive tests see: ResultSetGetterTest.testGetMetaData
+ * For extensive tests see: ResultSetGetterTest.testGetMetaData
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Not all types supported. More type checking done in ResultSetGetterTest.testGetMetaData",
- method = "getColumnType",
- args = {int.class}
- )
public void testGetColumnType() {
int[] types = { Types.SMALLINT, Types.VARCHAR, Types.VARCHAR};
try {
@@ -259,16 +198,8 @@
}
/**
- * @test java.sql.ResultSetMetaData#getColumnTypeName(int column)
- *
* for extensive tests see: ResultSetGetterTest.testGetMetaData
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not all types supported: see ResultSetGetterTests.",
- method = "getColumnTypeName",
- args = {int.class}
- )
public void testGetColumnTypeName() {
try {
assertTrue("smallint".equalsIgnoreCase(rsmd.getColumnTypeName(1)));
@@ -292,17 +223,7 @@
}
}
- /**
- * @throws SQLException
- * @test java.sql.ResultSetMetaData#getTableName(int column)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTableName",
- args = {int.class}
- )
- @KnownFailure("For int = 0, exception expected")
+ // For int = 0, exception expected
public void testGetTableName() throws SQLException {
try {
assertEquals("zoo", rsmd.getTableName(1));
@@ -348,16 +269,7 @@
}
}
- /**
- * @test {@link java.sql.ResultSetMetaData#getPrecision(int column)}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fails: always returns 0, exception tests fail ,failing statements commented out",
- method = "getPrecision",
- args = {int.class}
- )
- @KnownFailure("not supported")
+ // not supported
public void testGetPrecision() throws SQLException {
Statement st2 = null;
Statement st3 = null;
@@ -424,17 +336,11 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#getScale(int column)}
+ * Always returns 0, exception tests fail no positive test case for
+ * black-box test possible: no default value indicated.
+ *
+ * Not supported
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail: always returns 0, exception tests fail"+
- " no positive test case for black-box test possible: no default"+
- " value indicated",
- method = "getScale",
- args = {int.class}
- )
- @KnownFailure("Not supported")
public void testGetScale() throws SQLException {
try {
int scale = 3;
@@ -481,18 +387,8 @@
}
}
- /**
- * @test {@link java.sql.ResultSetMetaData#getSchemaName(int column)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Tests fail: always returns null. Feature only partially implemented. Missing: positive test.",
- method = "getSchemaName",
- args = {int.class}
- )
- @KnownFailure("not supported")
+ // not supported
public void testGetSchema() {
-
try {
assertNull("Functionality is now supported. Change test",rsmd.getSchemaName(2));
} catch (SQLException e1) {
@@ -500,8 +396,6 @@
e1.printStackTrace();
}
-
-
try {
rsmd.getSchemaName(0);
fail("SQLException is not thrown");
@@ -515,7 +409,6 @@
// expected
}
-
try {
conn.close();
rsmd.getSchemaName(2);
@@ -527,17 +420,12 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isAutoIncrement(int column)}
+ * Tests fail: always returns false, failing statements commented out.
+ * Feature only partially implemented.Missing: Test positive case
+ *
+ * Not supported.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Tests fail: always returns false, failing statements commented out. Feature only partially implemented.Missing: Test positive case",
- method = "isAutoIncrement",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testisAutoIncrement() {
-
try {
assertFalse(rsmd.isAutoIncrement(1));
} catch (SQLException e1) {
@@ -572,18 +460,8 @@
}
- /**
- * @test {@link java.sql.ResultSetMetaData#isCaseSensitive(int column)}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail: always returns false. Exception tests fail, failing statements commented out. Feature only partially implemented.",
- method = "isCaseSensitive",
- args = {int.class}
- )
- @KnownFailure("not supported")
+ // not supported
public void testIsCaseSensitive() {
-
try {
assertFalse(rsmd.isCaseSensitive(1));
assertFalse(rsmd.isCaseSensitive(2));
@@ -620,17 +498,13 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isCurrency(int column)}
+ * Tests fail: always returns false. Exceptions and tests non Numeric fields
+ * fail, failing statements commented out. Feature only partially
+ * implemented. May be an optional feature.
+ *
+ * Not supported.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Tests fail: always returns false. Exceptions and tests non Numeric fields fail, failing statements commented out. Feature only partially implemented. May be an optional feature.",
- method = "isCurrency",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testIsCurrency() {
-
try {
assertFalse(rsmd.isCurrency(1));
} catch (SQLException e1) {
@@ -638,9 +512,7 @@
e1.printStackTrace();
}
-
// Exception testing
-
try {
rsmd.isCurrency(0);
fail("SQLException is not thrown");
@@ -654,7 +526,6 @@
// expected
}
-
try {
rs.close();
rsmd.isCurrency(1);
@@ -664,18 +535,8 @@
}
}
- /**
- * @test {@link java.sql.ResultSetMetaData#isDefinitelyWritable(int column)}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail: always returns true. Exceptions fail, Feature only partially implemented.",
- method = "isDefinitelyWritable",
- args = {int.class}
- )
- @KnownFailure("not supported")
+ // not supported
public void testIsDefinitlyWritable() {
-
try {
assertTrue(rsmd.isDefinitelyWritable(1));
} catch (SQLException e1) {
@@ -701,17 +562,13 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isNullable(int column)}
+ * Tests fail: always returns ResultSetMetaData.columnNullableUnknown.
+ * Exceptions fail, failing statements commented out. Feature only
+ * partially implemented. May be an optional feature.
+ *
+ * Not supported.
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail: always returns ResultSetMetaData.columnNullableUnknown. Exceptions fail, failing statements commented out. Feature only partially implemented. May be an optional feature.",
- method = "isNullable",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testIsNullable() {
-
try {
assertEquals(ResultSetMetaData.columnNullable, rsmd
.isNullable(1));
@@ -744,17 +601,10 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isReadOnly(int column)}
+ * Cannot know from blackbox test if readonly or writable. Exceptions fail,
+ * Feature only partially implemented.
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Cannot know from blackbox test if readonly or writable. Exceptions fail, Feature only partially implemented.",
- method = "isReadOnly",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testIsReadOnly() {
-
try {
assertFalse(rsmd.isReadOnly(1));
} catch (SQLException e1) {
@@ -773,17 +623,10 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isSearchable(int column)}
+ * Tests fail: always returns false. Exceptions fail, Feature only partially
+ * implemented. Missing: test for searchable field.
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail: always returns false. Exceptions fail, Feature only partially implemented. Missing: test for searchable field.",
- method = "isSearchable",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testIsSearchable() {
-
try {
assertTrue(rsmd.isSearchable(1));
assertTrue(rsmd.isSearchable(2));
@@ -804,17 +647,11 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isSigned(int column)}
+ * Tests fail: always returns false. Exceptions and tests on non numeric
+ * fields fail, Feature only partially implemented. Missing: test positive
+ * result
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail: always returns false. Exceptions and tests on non numeric fields fail, Feature only partially implemented. Missing: test positive result.",
- method = "isSigned",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testIsSigned() {
-
try {
assertFalse(rsmd.isSigned(1));
} catch (SQLException e1) {
@@ -833,17 +670,11 @@
}
/**
- * @test {@link java.sql.ResultSetMetaData#isWritable(int column)}
+ * Analogous to is Readonly. Exceptions and tests on non numeric fields
+ * fail, Failing statements commented out. Feature only partially
+ * implemented.
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Analaguous to is Readonly. Exceptions and tests on non numeric fields fail, failing statements commented out. Feature only partially implemented.",
- method = "isWritable",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testIsWritable() {
-
try {
assertTrue(rsmd.isWritable(1));
assertTrue(rsmd.isWritable(2));
@@ -865,16 +696,8 @@
/**
- * @test {@link java.sql.ResultSetMetaData#getColumnDisplaySize(int Column)}
+ * Tests fail. always returns 0. Missing case where display size greater than 0
*/
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail. always returns 0. Missing case where display"+
- " size greater than 0",
- method = "getColumnDisplaySize",
- args = {int.class}
- )
- @KnownFailure("not supported")
public void testGetColumnDisplaySize() {
try {
for (int i = 0; i < rsmd.getColumnCount(); i++) {
diff --git a/luni/src/test/java/libcore/java/sql/OldResultSetTest.java b/luni/src/test/java/libcore/java/sql/OldResultSetTest.java
new file mode 100644
index 0000000..ea18db6
--- /dev/null
+++ b/luni/src/test/java/libcore/java/sql/OldResultSetTest.java
@@ -0,0 +1,482 @@
+/*
+ * 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 libcore.java.sql;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import tests.support.DatabaseCreator;
+
+public final class OldResultSetTest extends OldSQLTest {
+
+ ResultSet target = null;
+ ResultSet emptyTarget = null;
+ ResultSet scrollableTarget = null;
+ ResultSet writableTarget = null;
+ Statement stForward = null;
+ Statement stScrollable = null;
+ Statement stWritable = null;
+ final String selectAllAnimals = "select id, name from zoo";
+ final String selectEmptyTable = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+
+ @Override public void setUp() throws Exception {
+ super.setUp();
+
+ conn.setAutoCommit(false);
+ stForward = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ stForward.execute(selectAllAnimals);
+ target = stForward.getResultSet();
+ assertNotNull(target);
+
+ // empty table
+ stForward = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ stForward.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
+ stForward.execute(selectEmptyTable);
+ emptyTarget = stForward.getResultSet();
+ }
+
+ public void tearDown() throws SQLException {
+ super.tearDown();
+ target.close();
+ stForward.close();
+ }
+
+ public void testAbsolute() throws SQLException {
+ assertTrue(target.isBeforeFirst());
+ assertFalse(target.absolute(0));
+ assertTrue(target.absolute(1));
+ assertTrue(target.isFirst());
+ assertTrue(target.absolute(-1));
+ assertTrue(target.isLast());
+ target.next();
+ assertTrue(target.isAfterLast());
+ }
+
+ // res.close() does not wrap up
+ public void testAfterLast() throws SQLException {
+ target.afterLast();
+ assertTrue(target.isAfterLast());
+ assertFalse(target.next());
+
+ emptyTarget.afterLast();
+ assertFalse(emptyTarget.isAfterLast());
+
+ try {
+ target.close();
+ target.beforeFirst();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ }
+ }
+
+ // statement.close() does not wrap up
+ public void testBeforeFirst() throws SQLException {
+ target.beforeFirst();
+ assertTrue(target.isBeforeFirst());
+ assertTrue(target.next());
+ assertFalse(target.isBeforeFirst());
+
+ emptyTarget.beforeFirst();
+ assertFalse(emptyTarget.isBeforeFirst());
+
+ try {
+ target.close();
+ target.beforeFirst();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ }
+ }
+
+ /**
+ * According to the JDBC spec close has to "Releases this ResultSet
+ * object's database and JDBC resources immediately", and this implies
+ * the fields should be released as well (so that garbage collection
+ * can take place)
+ */
+ public void testClose1() {
+ try {
+ target.close();
+ target.next();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ /**
+ * Test that exception in one prepared statement does not affect second
+ * statement. (Atomicity Rule)
+ */
+ public void testClose() throws SQLException {
+ PreparedStatement ps1 = null;
+ PreparedStatement ps2 = null;
+ try {
+ Statement s = conn.createStatement();
+ s.addBatch("create table t1 (a text);");
+
+ s.addBatch("insert into t1 values('abc');");
+ s.addBatch("insert into t1 values('def');");
+ s.addBatch("insert into t1 values('ghi');");
+ s.executeBatch();
+ s.close();
+
+ conn.commit();
+ ps1 = conn.prepareStatement("select * from t1");
+ ps2 = conn.prepareStatement("select * from t1 whe a like '?000'");
+
+ ResultSet rs1 = ps1.executeQuery();
+ try {
+ ResultSet rs2 = ps2.executeQuery();
+ while (rs2.next()){
+ // do nothing
+ }
+ fail("Should get SQLException");
+ } catch (SQLException sqle) {
+ // ok : Division by zero
+ }
+
+ // Although exception happened on ps2 rs1 should still work
+ // Isolation property if ACID rules
+
+ while (rs1.next()) {
+ // do nothing: switching of rows should be possible
+ }
+
+ conn.commit();
+
+ rs1.close();
+ ps1.close();
+ ps2.close();
+ } finally {
+ try {
+ if (ps1 != null) ps1.close();
+ if (ps2 != null) ps2.close();
+ conn.rollback();
+ } catch (SQLException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public void testFindColumn() throws SQLException {
+ assertEquals(1, target.findColumn("id"));
+ assertEquals(2, target.findColumn("name"));
+
+ try {
+ target.findColumn("bla");
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ // statement.close() does not wrap up
+ public void testtestFirst() throws SQLException {
+ assertFalse(emptyTarget.first());
+ assertTrue(target.first());
+
+ try {
+ target.close();
+ // releases all resources such that it can be finalized!
+ target.first();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ }
+ }
+
+ // statement.close() does not wrap up
+ public void testtestIsAfterLast() throws SQLException {
+ assertFalse(target.isAfterLast());
+ target.absolute(-1); // last
+ target.next();
+ assertTrue(target.isAfterLast());
+ assertFalse(emptyTarget.isAfterLast());
+
+ try {
+ target.close();
+ // releases all resources such that it can be finalized!
+ target.isAfterLast();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ }
+ }
+
+ // In Second code block assertion fails. statement.close() does not wrap up
+ public void testtestIsBeforeFirst() throws SQLException {
+ assertTrue(target.isBeforeFirst());
+ assertTrue(target.next());
+ assertFalse(target.isBeforeFirst());
+ assertTrue(target.isFirst());
+ assertTrue(emptyTarget.isBeforeFirst());
+
+ try {
+ target.close();
+ // releases all resources such that it can be finalized!
+ target.isBeforeFirst();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // statement.close() does not wrap up
+ public void testtestIsFirst() throws SQLException {
+ assertFalse(target.isFirst());
+ target.first();
+ assertTrue(target.isFirst());
+ target.next();
+ assertFalse(target.isFirst());
+
+ assertFalse(emptyTarget.isFirst());
+
+ try {
+ target.close();
+ // releases all resources such that it can be finalized!
+ target.isFirst();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ }
+ }
+
+ /**
+ * Second block first assertion fails. Is Last should evaluate true if the
+ * row on which the cursor is actually provides a result.statment.close()
+ * does not wrap up
+ */
+ public void testtestIsLast() throws SQLException {
+ assertFalse(target.isLast());
+ target.absolute(-1);
+ assertTrue(target.isLast());
+
+ //check default value no valid row
+ assertFalse(emptyTarget.isLast());
+ assertFalse(emptyTarget.next());
+ assertFalse(emptyTarget.isLast());
+
+ try {
+ target.close();
+ target.isLast();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ // statement.close() does not wrap up
+ public void testtestLast() throws SQLException {
+ assertFalse(target.isLast());
+ target.last();
+ assertTrue(target.isLast());
+
+ try {
+ target.close();
+ target.last();
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ // ok
+ }
+ }
+
+ /**
+ * SQLException checking test fails. Clearing of warnings and closed streams
+ * not supported.
+ */
+ public void testNext() throws SQLException {
+ //before first - first
+ assertTrue(target.next());
+ //first - second
+ assertTrue(target.next());
+ //after last
+ assertFalse(target.next());
+ assertTrue(target.isAfterLast());
+ // one more
+ assertFalse(target.next());
+
+ assertFalse(emptyTarget.next());
+
+ target.close();
+ try {
+ target.next();
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ public void testPrevious() throws SQLException {
+ target.first();
+ target.previous();
+ assertTrue(target.isBeforeFirst());
+
+ target.last();
+ target.next();
+ target.previous();
+ assertFalse(target.isAfterLast());
+
+ target.close();
+ try {
+ target.previous();
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // no exception is thrown when moving cursor backwards on forward only statement
+ public void testRelative() throws SQLException {
+
+ // forward only
+ int initialRow = target.getRow();
+ assertFalse(target.relative(0));
+ assertEquals(initialRow, target.getRow());
+
+ assertTrue(target.relative(1));
+ assertTrue(target.isFirst());
+ assertEquals(1, target.getRow());
+
+ assertTrue(target.relative(1));
+ assertFalse(target.isFirst());
+ assertEquals(2, target.getRow());
+ assertFalse(target.relative(2));
+
+ try {
+ // should not be able to scroll backwards in forward only RS
+ target.relative(-2);
+ assertEquals(2,target.getRow());
+ fail("Should get SQLException");
+ } catch (SQLException e) {
+ // ok
+ } catch (Exception e) {
+ fail("Unexpected exception: " + e.getMessage());
+ }
+
+ assertFalse(emptyTarget.relative(Integer.MAX_VALUE));
+ assertTrue(emptyTarget.isAfterLast());
+ }
+
+ // Scrollable resultSet. Not supported
+ public void testRelativeScrollableResultSet() throws SQLException {
+ // scrollable resultSet
+ int initialRow = scrollableTarget.getRow();
+ assertFalse(scrollableTarget.relative(0));
+ assertEquals(initialRow, scrollableTarget.getRow());
+
+ assertTrue(scrollableTarget.relative(1));
+ assertTrue(scrollableTarget.isFirst());
+ assertEquals(1, scrollableTarget.getRow());
+
+ assertTrue(scrollableTarget.relative(1));
+ assertFalse(scrollableTarget.isFirst());
+
+ assertEquals(2, scrollableTarget.getRow());
+ assertFalse(scrollableTarget.relative(2));
+ scrollableTarget.relative(-2);
+ assertEquals(2,scrollableTarget.getRow());
+
+ assertFalse(scrollableTarget.relative(Integer.MIN_VALUE));
+ assertTrue(scrollableTarget.isBeforeFirst());
+
+ stScrollable.close();
+ try {
+ scrollableTarget.relative(1);
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ // not supported
+ public void testUpdateObjectStringObject() throws SQLException {
+ writableTarget.next();
+ writableTarget.updateObject("family","bird");
+
+ try {
+ target.next();
+ target.updateObject("family","bird");
+ fail("SQLException was not thrown");
+ } catch (SQLException e) {
+ fail("Unexpected exception: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Only exception testing. Missing testing for wrong type
+ */
+ public void testUpdateStringStringString() throws Exception {
+ writableTarget.next();
+ writableTarget.updateString("family","bird");
+
+ // non writable target.
+ try {
+ target.next();
+ target.updateString("family","bird");
+ fail("SQLException was not thrown");
+ } catch (SQLException e) {
+ //ok
+ }
+
+
+ // writable but wrong type
+ target.updateString(1,"test");
+
+ target.close();
+
+ // Exception test
+ try {
+ target.updateString("family", "test");
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+
+ /**
+ * Test method for {@link java.sql.ResultSet#wasNull()}.
+ * Spec sais: if something was read... -> if nothing was read it should be false
+ */
+ public void testWasNull() throws SQLException {
+ // Check default: select statement executed but no get on target called yet
+ // Either false or throw an exception.
+ try {
+ assertFalse(target.wasNull());
+ } catch (SQLException e) {
+ //ok
+ }
+
+ stForward.execute("insert into zoo values(8,null,null);");
+ stForward.execute(selectAllAnimals);
+ target = stForward.getResultSet();
+ assertNotNull(target);
+ assertTrue(target.last());
+ assertNull(target.getObject(2));
+ assertTrue(target.wasNull());
+ assertNotNull(target.getObject(1));
+ assertFalse(target.wasNull());
+
+ target.close();
+ try {
+ target.wasNull();
+ fail("Exception expected");
+ } catch (SQLException e) {
+ //ok
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/sql/SQLTest.java b/luni/src/test/java/libcore/java/sql/OldSQLTest.java
similarity index 69%
rename from luni/src/test/java/tests/sql/SQLTest.java
rename to luni/src/test/java/libcore/java/sql/OldSQLTest.java
index 1b7d241..da2f968 100755
--- a/luni/src/test/java/tests/sql/SQLTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldSQLTest.java
@@ -14,26 +14,20 @@
* limitations under the License.
*/
-package tests.sql;
-
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
+package libcore.java.sql;
import java.io.File;
-import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
+import junit.framework.TestCase;
-@TestTargetClass(Statement.class)
-public class SQLTest extends TestCase {
+public abstract class OldSQLTest extends TestCase {
static Connection conn;
- @Override
- public void setUp() throws Exception {
+ @Override public void setUp() throws Exception {
getSQLiteConnection();
createZoo();
}
@@ -56,16 +50,13 @@
assertNotNull("Connection created ", conn);
}
- @Override
- public void tearDown() {
+ @Override public void tearDown() throws SQLException {
Statement st = null;
try {
if (! conn.isClosed()) {
st = conn.createStatement();
st.execute("drop table if exists zoo");
}
- } catch (SQLException e) {
- fail("Couldn't drop table: " + e.getMessage());
} finally {
try {
if (st != null) {
@@ -78,8 +69,7 @@
}
}
- public void createZoo() {
-
+ public void createZoo() throws SQLException {
String[] queries = {
"create table zoo(id smallint, name varchar(10), family varchar(10))",
"insert into zoo values (1, 'Kesha', 'parrot')",
@@ -91,9 +81,6 @@
for (int i = 0; i < queries.length; i++) {
st.execute(queries[i]);
}
- } catch (SQLException e) {
- e.printStackTrace();
- fail("Unexpected exception: " + e.getMessage());
} finally {
try {
if (st != null) {
@@ -103,25 +90,6 @@
}
}
- public void createProcedure() {
- String proc = "CREATE PROCEDURE welcomeAnimal (IN parameter1 integer, IN parameter2 char(20), IN parameter3 char(20)) "
- + " BEGIN "
- + " INSERT INTO zoo(id, name, family) VALUES (parameter1, parameter2, parameter3); "
- + "SELECT * FROM zoo;" + " END;";
- Statement st = null;
- try {
- st = conn.createStatement();
- st.execute("DROP PROCEDURE IF EXISTS welcomeAnimal");
- st.execute(proc);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- } finally {
- try {
- st.close();
- } catch (SQLException ee) {}
- }
- }
-
public int getCount(ResultSet rs) {
int count = 0;
try {
diff --git a/luni/src/test/java/tests/sql/StatementTest.java b/luni/src/test/java/libcore/java/sql/OldStatementTest.java
similarity index 63%
rename from luni/src/test/java/tests/sql/StatementTest.java
rename to luni/src/test/java/libcore/java/sql/OldStatementTest.java
index d41a875..0130e3d 100755
--- a/luni/src/test/java/tests/sql/StatementTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldStatementTest.java
@@ -14,13 +14,7 @@
* limitations under the License.
*/
-package tests.sql;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.sql;
import java.sql.BatchUpdateException;
import java.sql.PreparedStatement;
@@ -29,25 +23,12 @@
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.Statement;
-import java.util.Arrays;
-import java.util.List;
import java.util.Vector;
import java.util.logging.Logger;
-@TestTargetClass(Statement.class)
-public class StatementTest extends SQLTest {
+public final class OldStatementTest extends OldSQLTest {
- /**
- * @test java.sql.Statement#addBatch(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addBatch",
- args = {java.lang.String.class}
- )
public void testAddBatch() throws SQLException {
-
Statement st = null;
try {
st = conn.createStatement();
@@ -58,9 +39,6 @@
assertEquals(2, updateCounts.length);
assertEquals(1, updateCounts[0]);
assertEquals(1, updateCounts[1]);
-
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
st.close();
@@ -96,16 +74,7 @@
}
}
- /**
- * @test java.sql.Statement#clearWarnings()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clearWarnings",
- args = {}
- )
- public void testClearWarnings() {
+ public void testClearWarnings() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
@@ -123,8 +92,6 @@
st.clearWarnings();
SQLWarning w = st.getWarnings();
assertNull(w);
- } catch (Exception e) {
- fail("Unexpected Exception: " + e.getMessage());
} finally {
try {
st.close();
@@ -133,18 +100,7 @@
}
}
- /**
- * @test java.sql.Statement#getWarnings()
- *
- * TODO getWarnings is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported. always returns null. ",
- method = "getWarnings",
- args = {}
- )
- public void testGetWarnings() {
+ public void testGetWarnings() throws SQLException {
Statement st = null;
int errorCode1 = -1;
@@ -159,12 +115,9 @@
errorCode1 = e.getErrorCode();
}
- try {
- SQLWarning wrs = st.getWarnings();
- assertNull(wrs);
- } catch (Exception e) {
- fail("Change test implementation: get warnings is supported now");
- }
+ SQLWarning wrs = st.getWarnings();
+ assertNull(wrs);
+
/*
Statement st = null;
int errorCode1 = -1;
@@ -207,17 +160,7 @@
}
- /**
- * @test {@link java.sql.Statement#clearBatch()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clearBatch",
- args = {}
- )
public void testClearBatch() throws SQLException {
-
Statement st = null;
try {
@@ -232,9 +175,6 @@
for (int i = 0; i < updateCounts.length; i++) {
assertEquals(0, updateCounts[i]);
}
-
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
st.close();
@@ -270,19 +210,7 @@
}
}
- /**
- * @test java.sql.Statement#execute(String sql)
- *
- * TODO not pass on SQLite and RI.
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "execute",
- args = {java.lang.String.class}
- )
- @KnownFailure("Return value wrong for queries below.")
+ // TODO not pass on SQLite and RI.
public void testExecute() throws SQLException {
String[] queries = {
@@ -337,16 +265,7 @@
}
}
- /**
- * @test java.sql.Statement#execute(String sql, int autoGeneratedKeys)
- * TODO not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Missing implementation for Statement.RETURN_GENERATED_KEYS: keys not yet supported",
- method = "execute",
- args = {java.lang.String.class, int.class}
- )
+ // TODO not supported
public void testExecute_String_int() {
String[] queries = {
"update zoo set name='Masha', family='cat' where id=2;",
@@ -399,23 +318,12 @@
}
}
- /**
- * @test java.sql.Statement#getConnection()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "getConnection",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testGetConnection() {
+ // statement.close() does not wrap up
+ public void testGetConnection() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
assertSame(conn, st.getConnection());
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -430,27 +338,14 @@
} catch (SQLException e) {
//ok
}
-
-
}
- /**
- * @test java.sql.Statement#getFetchDirection()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SQLException test fails. Not all Fetch directions supported.",
- method = "getFetchDirection",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testGetFetchDirection() {
+ // statement.close() does not wrap up
+ public void testGetFetchDirection() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
assertEquals(ResultSet.FETCH_UNKNOWN, st.getFetchDirection());
- } catch (SQLException e) {
- fail("SQLException is thrown " + e.getMessage());
} finally {
try {
st.close();
@@ -480,16 +375,7 @@
}
}
- /**
- * @test java.sql.Statement#setFetchDirection(int)
- * TODO not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported. ",
- method = "setFetchDirection",
- args = {int.class}
- )
+ // TODO not supported
public void testSetFetchDirection() {
Statement st = null;
try {
@@ -507,55 +393,15 @@
} catch (SQLException ee) {
}
}
-
- /*
- try {
- st = conn.createStatement();
- st.setFetchDirection(-1);
- fail("SQLException is not thrown");
- } catch (SQLException e) {
- // expected
- } finally {
- try {
- st.close();
- } catch (SQLException ee) {
- }
- }
-
- try {
- st = conn.createStatement();
- st.setFetchDirection(100);
- fail("SQLException is not thrown");
- } catch (SQLException e) {
- // expected
- } finally {
- try {
- st.close();
- } catch (SQLException ee) {
- }
- }
-
- */
}
- /**
- * @test java.sql.Statement#getFetchSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "getFetchSize",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testGetFetchSize() {
+ // statement.close() does not wrap up
+ public void testGetFetchSize() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
st.execute("select * from zoo;");
assertEquals(1, st.getFetchSize());
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
st.close();
@@ -572,17 +418,8 @@
}
}
- /**
- * @test {@link java.sql.Statement#setFetchSize(int)}
- * TODO not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported.",
- method = "setFetchSize",
- args = {int.class}
- )
- public void testSetFetchSize() {
+ // TODO not supported
+ public void testSetFetchSize() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
@@ -605,8 +442,6 @@
}
*/
- } catch (SQLException e) {
- fail("SQLException is thrown");
} finally {
try {
st.close();
@@ -615,17 +450,8 @@
}
}
- /**
- * @test java.sql.Statement#setMaxFieldSize(int max)
- * TODO not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "setMaxFieldSize",
- args = {int.class}
- )
- public void testSetMaxFieldSize() {
+ // TODO not supported
+ public void testSetMaxFieldSize() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
@@ -636,20 +462,8 @@
fail("Revise test implemenation for feature impl. has changed");
} catch (SQLException sqle) {
assertEquals("not supported", sqle.getMessage());
-// fail("SQLException is thrown: " + sqle.getMessage());
}
}
- /*
- try {
- st.setMaxFieldSize(-1);
- fail("SQLException isn't thrown");
- } catch (SQLException sqle) {
- // expecteds
- }
- */
- } catch (SQLException e) {
- fail("Can't create statement, SQLException is thrown: "
- + e.getMessage());
} finally {
try {
st.close();
@@ -658,17 +472,8 @@
}
}
- /**
- * @test java.sql.Statement#getMaxFieldSize()
- * TODO not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "getMaxFieldSize",
- args = {}
- )
- public void testGetMaxFieldSize() {
+ // TODO not supported
+ public void testGetMaxFieldSize() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
@@ -678,12 +483,8 @@
fail("Revise test implemenation for feature impl. has changed");
} catch (SQLException sqle) {
assertEquals("not supported", sqle.getMessage());
- // fail("SQLException is thrown: " + sqle.getMessage());
}
}
- } catch (SQLException e) {
- fail("Can't create statement, SQLException is thrown: "
- + e.getMessage());
} finally {
try {
st.close();
@@ -692,29 +493,25 @@
}
}
- public void testMaxRows() {
+ public void testMaxRows() throws SQLException {
Statement st = null;
try {
st = conn.createStatement();
for (int i = 0; i < 300; i += 50) {
- try {
- st.setMaxRows(i);
- assertEquals(i, st.getMaxRows());
- ResultSet r = st.executeQuery("select * from zoo;");
- int rowCount = 0;
- while (r.next()) {
- ++rowCount;
- }
- if (i == 0) {
- // 0 means unlimited.
- assertTrue("rowCount=" + rowCount + " i=" + i, rowCount > i);
- } else {
- assertTrue("rowCount=" + rowCount + " i=" + i, rowCount <= i);
- }
- r.close();
- } catch (SQLException sqle) {
- fail("SQLException is thrown: " + sqle.getMessage());
+ st.setMaxRows(i);
+ assertEquals(i, st.getMaxRows());
+ ResultSet r = st.executeQuery("select * from zoo;");
+ int rowCount = 0;
+ while (r.next()) {
+ ++rowCount;
}
+ if (i == 0) {
+ // 0 means unlimited.
+ assertTrue("rowCount=" + rowCount + " i=" + i, rowCount > i);
+ } else {
+ assertTrue("rowCount=" + rowCount + " i=" + i, rowCount <= i);
+ }
+ r.close();
}
try {
st.setMaxRows(-1);
@@ -722,9 +519,6 @@
} catch (SQLException sqle) {
// expecteds
}
- } catch (SQLException e) {
- fail("Can't create statement, SQLException is thrown: "
- + e.getMessage());
} finally {
try {
st.close();
@@ -733,19 +527,8 @@
}
}
- /**
- * @test java.sql.Statement#close()
- * not passed according to Java Docs: should release all resources
- * IMMEDIATELY
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testClose() {
+ /** not passed according to spec; should release resources immediately */
+ public void testClose() throws SQLException {
Statement st = null;
ResultSet res = null;
try {
@@ -762,8 +545,6 @@
assertNotNull(res);
assertTrue(res.next());
st.close();
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -781,19 +562,9 @@
} catch (SQLException e) {
// ok
}
-
}
- /**
- * @test java.sql.Statement#execute(String sql, int[] columnIndexes)
- * TODO not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "execute",
- args = {java.lang.String.class, int[].class}
- )
+ // TODO not supported
public void testExecute_String_intArray() {
Statement st = null;
try {
@@ -830,15 +601,6 @@
}
}
- /**
- * @test java.sql.Statement#execute(String sql, String[] columnNames)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "execute",
- args = {java.lang.String.class, java.lang.String[].class}
- )
public void testExecute_String_StringArray() {
Statement st = null;
try {
@@ -871,17 +633,8 @@
}
}
- /**
- * @test java.sql.Statement#executeBatch()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test fails: dropping table hutch affects at least 2 rows.executeBatch() always returns same result: 1.",
- method = "executeBatch",
- args = {}
- )
- @KnownFailure("always returns 1 for no. of updates")
- public void testExecuteBatch() {
+ // always returns 1 for no. of updates
+ public void testExecuteBatch() throws SQLException {
String[] queries = {
"update zoo set name='Masha', family='cat' where id=2;",
@@ -912,8 +665,6 @@
fail("BatchupdateException expected");
} catch (BatchUpdateException e) {
//ok
- } catch (SQLException e) {
- fail("BatchupdateException expected");
} finally {
try {
st.close();
@@ -929,8 +680,6 @@
}
int[] resArray = st.executeBatch();
assertTrue(java.util.Arrays.equals(result, resArray));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -945,8 +694,6 @@
fail("Exception expected");
} catch (BatchUpdateException bue) {
// ok select returns a resultSet
- } catch (SQLException sqle) {
- fail("Unknown SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
@@ -963,17 +710,8 @@
}
}
- /**
- * @test java.sql.Statement#executeQuery(String sql)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Not according to spec.",
- method = "executeQuery",
- args = {java.lang.String.class}
- )
- @KnownFailure("Does throw an exception on non select statment.")
- public void testExecuteQuery_String() {
+ // Does throw an exception on non select statement.
+ public void testExecuteQuery_String() throws SQLException {
String[] queries1 = { "select * from zoo",
"select name, family from zoo where id = 1" };
@@ -999,8 +737,6 @@
fail("SQLException is thrown for query: " + queries1[i]);
}
}
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -1021,30 +757,19 @@
// expected
}
}
- } catch (SQLException sqle) {
- fail("Unknown SQLException is thrown: " + sqle.getMessage());
} finally {
try {
st.close();
} catch (Exception ee) {
}
}
-
}
/**
- * @throws SQLException
- * @test java.sql.Statement#executeUpdate(String sql)
+ * Spec is not precise enough: should be: number of rows affected. eg. to be
+ * consistent for deletes: 'delete from s1;' should be different from
+ * 'delete from s1 where c1 = 1;'
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "impl not according to spec.",
- method = "executeUpdate",
- args = {java.lang.String.class}
- )
- @KnownFailure("Spec is not precise enough: should be: number of rows affected."+
- " eg. to be consistent for deletes: 'delete from s1;' should be different from "+
- "'delete from s1 where c1 = 1;' ")
public void testExecuteUpdate_String() throws SQLException {
String[] queries1 = {
@@ -1062,22 +787,12 @@
try {
st = conn.createStatement();
for (int i = 0; i < queries1.length; i++) {
- try {
- int count = st.executeUpdate(queries1[i]);
- assertTrue(count > 0);
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- }
+ int count = st.executeUpdate(queries1[i]);
+ assertTrue(count > 0);
}
- try {
- assertEquals(0, st.executeUpdate(queries2));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- }
+ assertEquals(0, st.executeUpdate(queries2));
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -1098,7 +813,7 @@
assertEquals(1,stat.executeUpdate("delete from s1 where c1 = 1;"));
assertEquals(2, stat.executeUpdate("update s1 set c1 = 5;"));
- // analogous to statemente before, delete all should return 2
+ // analogous to statement before, delete all should return 2
assertEquals(2,stat.executeUpdate("delete from s1;"));
// there are no rows in table: 0 should be returned
@@ -1115,17 +830,7 @@
stat.close();
}
- /**
- * @test java.sql.Statement#executeUpdate(String sql, int[] columnIndexes)
- *
- * TODO executeUpdate(String sql, int[] columnIndexes) is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "executeUpdate",
- args = {java.lang.String.class, int[].class}
- )
+ // TODO executeUpdate(String sql, int[] columnIndexes) is not supported
public void testExecuteUpdate_String_intArray() throws SQLException {
Statement st = null;
try {
@@ -1163,17 +868,7 @@
}
}
- /**
- * @test java.sql.Statement#executeUpdate(String sql, int autoGeneratedKeys)
- *
- * TODO executeUpdate(String sql, int autoGeneratedKeys) is not supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported",
- method = "executeUpdate",
- args = {java.lang.String.class, int.class}
- )
+ // executeUpdate(String sql, int autoGeneratedKeys) is not supported
public void testExecuteUpdate_String_int() {
String[] queries = {
"update zoo set name='Masha', family='cat' where id=2;",
@@ -1220,17 +915,7 @@
}
}
- /**
- * @test java.sql.Statement#executeUpdate(String sql, String[] columnNames)
- *
- * TODO executeUpdate(String sql, String[] columnNames) is not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "executeUpdate",
- args = {java.lang.String.class, java.lang.String[].class}
- )
+ // TODO executeUpdate(String sql, String[] columnNames) is not supported
public void testExecuteUpdate_String_StringArray() throws SQLException {
Statement st = null;
try {
@@ -1271,17 +956,8 @@
}
}
- /**
- * @test java.sql.Statement#getUpdateCount()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "getUpdateCount",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testGetUpdateCount() {
+ // statement.close() does not wrap up
+ public void testGetUpdateCount() throws SQLException {
Statement st = null;
try {
String query = "update zoo set name='Masha', family='cat' where id=2;";
@@ -1291,8 +967,6 @@
query = "update zoo set name='Masha', family='cat' where id=5;";
st.executeUpdate(query);
assertEquals(0, st.getUpdateCount());
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -1308,17 +982,6 @@
}
}
- /**
- * @test {@link java.sql.Statement#getGeneratedKeys()}
- *
- * TODO getGeneratedKeys() is not supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported",
- method = "getGeneratedKeys",
- args = {}
- )
public void testGeneratedKeys() throws SQLException {
Statement st = null;
try {
@@ -1331,17 +994,7 @@
}
}
- /**
- * @test {@link java.sql.Statement#setCursorName(String)}
- *
- * TODO setCursorName() is not supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported",
- method = "setCursorName",
- args = {java.lang.String.class}
- )
+ // TODO setCursorName() is not supported
public void testSetCursorName() throws SQLException {
Statement st = null;
try {
@@ -1354,17 +1007,7 @@
}
}
- /**
- * @test {@link java.sql.Statement#setEscapeProcessing}
- *
- * TODO setExcapeProcessing() is not supported
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported",
- method = "setEscapeProcessing",
- args = {boolean.class}
- )
+ // TODO setEscapeProcessing() is not supported
public void testSetEscapeProcessing() {
Statement st = null;
try {
@@ -1375,65 +1018,32 @@
} catch (SQLException e) {
assertEquals("not supported", e.getMessage());
}
-
}
- /**
- * @test {@link java.sql.Statement#setQueryTimeout}
- *
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Error in impl. default query timeout for sqlite dbs is 0.",
- method = "setQueryTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Error in impl. default query timeout for sqlite dbs is 0.",
- method = "getQueryTimeout",
- args = {}
- )
- })
- public void testSetQueryTimeout() {
+ public void testSetQueryTimeout() throws SQLException {
+ Statement st = conn.createStatement();
+ st.setQueryTimeout(2);
+ assertEquals(2, st.getQueryTimeout());
+
try {
- Statement st = conn.createStatement();
- st.setQueryTimeout(2);
- assertEquals(2, st.getQueryTimeout());
+ st = conn.createStatement();
+ st.setQueryTimeout(-1);
+ fail("SQLException not thrown");
+ } catch (SQLException expected) {
+ // expected
+ }
- try {
- st = conn.createStatement();
- st.setQueryTimeout(-1);
- fail("SQLException not thrown");
- } catch (SQLException expected) {
- // expected
- }
-
- try {
- st = conn.createStatement();
- st.close();
- st.setQueryTimeout(3);
- fail("SQLException not thrown");
- } catch (SQLException expected) {
- // expected
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
+ try {
+ st = conn.createStatement();
+ st.close();
+ st.setQueryTimeout(3);
+ fail("SQLException not thrown");
+ } catch (SQLException expected) {
+ // expected
}
}
- /**
- * @test {@link java.sql.Statement#getResultSetType()}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Tests fail. not fully supported: returns only ResultSet.TYPE_SCROLL_INSENSITIVE. Either should throw an unsupported exception or behave according to spec.",
- method = "getResultSetType",
- args = {}
- )
- @KnownFailure("not fully supported")
+ // not fully supported
public void testGetResultSetType() {
Statement st = null;
// test default value
@@ -1475,17 +1085,7 @@
}
}
- /**
- * @test {@link java.sql.Statement#getResultSetHoldability()}
- *
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported",
- method = "getResultSetHoldability",
- args = {}
- )
- @KnownFailure("Test for default value fails")
+ // Test for default value fails
public void testGetResultSetHoldability() {
// test default value
@@ -1500,21 +1100,16 @@
// failing tests
try {
- st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
+ conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
fail("Exception expected: not supported");
- /*
- st.getResultSetHoldability();
- assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, st
- .getResultSetHoldability());
- */
} catch (SQLException e) {
// ok: not supported
}
try {
- st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
+ conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
fail("Exception expected: not supported");
@@ -1523,22 +1118,11 @@
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, st
.getResultSetHoldability());
*/
- } catch (SQLException e) {
- // ok: not supported
+ } catch (SQLException expected) {
}
}
- /**
- * @test {@link java.sql.Statement#getResultSetConcurrency()}
- *
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests fail. returns only ResultSet.TYPE_SCROLL_INSENSITIVE. Either should throw an unsupported exception or behave according to spec.",
- method = "getResultSetConcurrency",
- args = {}
- )
- @KnownFailure("Not supported")
+ // Not supported
public void testGetResultSetConcurrency() {
Statement st = null;
@@ -1576,64 +1160,40 @@
}
}
- /**
- * @test {@link java.sql.Statement#getResultSet()}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Error in implementation. Is not according to spec:if updateCount > 0 resultset must be null.",
- method = "getResultSet",
- args = {}
- )
- @KnownFailure("Does not return null on update count > 0 (not a select statement) ")
- public void testGetResultSet() {
+ // Does not return null on update count > 0 (not a select statement)
+ public void testGetResultSet() throws SQLException {
Statement st = null;
ResultSet res = null;
- try {
- st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
- ResultSet.CONCUR_READ_ONLY,
- ResultSet.CLOSE_CURSORS_AT_COMMIT);
- st.execute("create table test (c1);");
- res = st.getResultSet();
- assertNull(res);
- } catch (SQLException e) {
- fail("Unexpected Exception "+e);
- }
+ st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.CLOSE_CURSORS_AT_COMMIT);
+ st.execute("create table test (c1);");
+ res = st.getResultSet();
+ assertNull(res);
- try {
- st = conn.createStatement();
- String select = "select * from zoo where id == 4;";
- String insert = "insert into zoo (id, name, family) values (4, 'Vorobuy', 'bear');";
- st.execute(insert);
- st.execute(select);
- assertEquals(-1, st.getUpdateCount());
- res = st.getResultSet();
- assertNotNull(res);
- res.next();
- assertEquals(4,res.getInt(1));
- assertEquals("Vorobuy",res.getString(2));
- assertEquals("bear",res.getString(3));
+ st = conn.createStatement();
+ String select = "select * from zoo where id == 4;";
+ String insert = "insert into zoo (id, name, family) values (4, 'Vorobuy', 'bear');";
+ st.execute(insert);
+ st.execute(select);
+ assertEquals(-1, st.getUpdateCount());
+ res = st.getResultSet();
+ assertNotNull(res);
+ res.next();
+ assertEquals(4,res.getInt(1));
+ assertEquals("Vorobuy",res.getString(2));
+ assertEquals("bear",res.getString(3));
// assertEquals(0, st.getUpdateCount()); not supported
- assertFalse(res.next());
- } catch (SQLException e) {
- fail("SQLException is thrown:"+e.getMessage());
- }
+ assertFalse(res.next());
- try {
- st = conn.createStatement();
- String insert = "insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');";
- st
- .execute(insert);
- res = st.getResultSet();
- // statement is an update and should return null according to spec.
- if (st.getUpdateCount() > 0) {
- assertNull(res);
- }
-
- } catch (SQLException e) {
- fail("SQLException is thrown:"+e.getMessage());
+ st = conn.createStatement();
+ insert = "insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');";
+ st.execute(insert);
+ res = st.getResultSet();
+ // statement is an update and should return null according to spec.
+ if (st.getUpdateCount() > 0) {
+ assertNull(res);
}
try {
@@ -1645,33 +1205,15 @@
}
}
- /**
- * @test {@link java.sql.Statement#setQueryTimeout}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Errors in impl.An other value is returned than was set (X * 1000)Default query timeout for sqlite dbs is 0.",
- method = "getQueryTimeout",
- args = {}
- )
- @KnownFailure("An other value is returned than was set (X * 1000)")
- public void testGetQueryTimeout() {
+ // An other value is returned than was set (X * 1000)
+ public void testGetQueryTimeout() throws SQLException {
Statement st = null;
- try {
- st = conn.createStatement();
- st.setQueryTimeout(2000);
- assertEquals(2000, st.getQueryTimeout());
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- }
+ st = conn.createStatement();
+ st.setQueryTimeout(2000);
+ assertEquals(2000, st.getQueryTimeout());
- try {
- st = conn.createStatement();
- assertEquals(0,st.getQueryTimeout());
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- }
+ st = conn.createStatement();
+ assertEquals(0,st.getQueryTimeout());
try {
st.close();
@@ -1682,18 +1224,8 @@
}
}
- /**
- * @test {@link java.sql.Statement#getMoreResults()}
- *
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not fully supported",
- method = "getMoreResults",
- args = {}
- )
- @KnownFailure("not supported")
- public void testGetMoreResults() {
+ // not supported
+ public void testGetMoreResults() throws SQLException {
Statement st = null;
ResultSet res1 = null;
ResultSet res2 = null;
@@ -1713,8 +1245,6 @@
} catch (SQLException e) {
//ok
}
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
} finally {
try {
st.close();
@@ -1730,75 +1260,28 @@
}
}
- /**
- * @test {@link java.sql.Statement#getMoreResults(int)}
- *
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Callable Statements are not supported",
- method = "getMoreResults",
- args = {int.class}
- )
- public void testGetMoreResultsInt() {
- /*
- } catch (BatchUpdateException e) {
- fail("Unexpected Exception "+e.getMessage());
- } catch (SQLException e) {
- assertEquals("not supported",e.getMessage());
- } finally {
- try {
- st.close();
- } catch (SQLException ee) {
- }
- }
-
- try {
- st.getMoreResults(Integer.MAX_VALUE);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- */
- }
-
- /**
- * @test {@link java.sql.Statement#cancel()}
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test fails. See also SQLite.DatabaseTest test of interrupt().",
- method = "cancel",
- args = {}
- )
- @KnownFailure("Bug in implementation of cancel: Does not fulfill spec.")
- public void testCancel() {
+ // Bug in implementation of cancel: Does not fulfill spec.
+ public void testCancel() throws SQLException {
Statement st = null;
+ st = conn.prepareStatement("insert into zoo values (7,'Speedy Gonzales','Mouse');");
+
+ CancelThread c = new CancelThread(st);
+ InsertThread ins = new InsertThread((PreparedStatement)st);
+
try {
- st = conn.prepareStatement("insert into zoo values (7,'Speedy Gonzales','Mouse');");
-
- CancelThread c = new CancelThread(st);
- InsertThread ins = new InsertThread((PreparedStatement)st);
-
- try {
- ins.t.join();
- c.t.join();
- } catch (InterruptedException e) {
- fail("Error in test setup: ");
- } catch (Exception e){
- // Insert thread may throw an exception
- // that it could not complete statement
- }
-
- // both threads have terminated and cancel should have cancelled the insert statement.
- ResultSet res = st.executeQuery("select * from zoo where id=7");
- assertFalse(res.next());
-
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
+ ins.t.join();
+ c.t.join();
+ } catch (InterruptedException e) {
+ fail("Error in test setup: ");
+ } catch (Exception e){
+ // Insert thread may throw an exception
+ // that it could not complete statement
}
+ // both threads have terminated and cancel should have cancelled the insert statement.
+ ResultSet res = st.executeQuery("select * from zoo where id=7");
+ assertFalse(res.next());
+
try {
st.close();
st.cancel();
@@ -1816,25 +1299,26 @@
t = new Thread(this,"Cancel thread");
t.start();
}
+
public void run() {
- Logger.global.info("*Cancel* thread started");
- try {
- Thread.sleep(1500);
- } catch (InterruptedException e1) {
- fail("Error in test setup");
- e1.printStackTrace();
- }
- try {
- Logger.global.info("*Cancel* thread, about to do stmt.cancel()");
- stmt.cancel();
- Logger.global.info("*Cancel* thread, stmt.cancel() done");
- } catch (SQLException e) {
- fail("Error in test setup");
- e.printStackTrace();
- }
- Logger.global.info("*Cancel* thread terminated");
+ Logger.global.info("*Cancel* thread started");
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e1) {
+ fail("Error in test setup");
+ e1.printStackTrace();
+ }
+ try {
+ Logger.global.info("*Cancel* thread, about to do stmt.cancel()");
+ stmt.cancel();
+ Logger.global.info("*Cancel* thread, stmt.cancel() done");
+ } catch (SQLException e) {
+ fail("Error in test setup");
+ e.printStackTrace();
+ }
+ Logger.global.info("*Cancel* thread terminated");
}
- }
+ }
class InsertThread implements Runnable{
Thread t;
@@ -1844,25 +1328,25 @@
t = new Thread(this,"Insert thread");
t.start();
}
- public void run() {
- Logger.global.info("*Insert* thread started");
- try {
- Thread.sleep(1500);
- } catch (InterruptedException e1) {
- fail("Error in test setup");
- e1.printStackTrace();
- }
- try {
- Logger.global.info("*Insert* thread, about to do insertion");
- stmt.execute();
- stmt.execute();
- Logger.global.info("*Insert* thread inserted");
- } catch (SQLException e) {
- fail("Error in test setup");
- e.printStackTrace();
- }
- Logger.global.info("*Insert* thread terminated");
- }
- }
+ public void run() {
+ Logger.global.info("*Insert* thread started");
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e1) {
+ fail("Error in test setup");
+ e1.printStackTrace();
+ }
+ try {
+ Logger.global.info("*Insert* thread, about to do insertion");
+ stmt.execute();
+ stmt.execute();
+ Logger.global.info("*Insert* thread inserted");
+ } catch (SQLException e) {
+ fail("Error in test setup");
+ e.printStackTrace();
+ }
+ Logger.global.info("*Insert* thread terminated");
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/sql/OldTimestampTest.java b/luni/src/test/java/libcore/java/sql/OldTimestampTest.java
index 1bce26d..ab2034b 100644
--- a/luni/src/test/java/libcore/java/sql/OldTimestampTest.java
+++ b/luni/src/test/java/libcore/java/sql/OldTimestampTest.java
@@ -21,7 +21,7 @@
import java.util.TimeZone;
import junit.framework.TestCase;
-public class OldTimestampTest extends TestCase {
+public final class OldTimestampTest extends TestCase {
public void test_toString() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
diff --git a/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java b/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java
index 33e28b0..8b24c6d 100644
--- a/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java
+++ b/luni/src/test/java/libcore/java/text/DecimalFormatSymbolsTest.java
@@ -16,6 +16,10 @@
package libcore.java.text;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
@@ -32,4 +36,22 @@
checkLocaleIsEquivalentToRoot(new Locale("xx", "XX"));
checkLocaleIsEquivalentToRoot(new Locale("not exist language", "not exist country"));
}
+
+ // http://code.google.com/p/android/issues/detail?id=14495
+ public void testSerialization() throws Exception {
+ DecimalFormatSymbols originalDfs = DecimalFormatSymbols.getInstance(Locale.GERMANY);
+
+ // Serialize...
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ new ObjectOutputStream(out).writeObject(originalDfs);
+ byte[] bytes = out.toByteArray();
+
+ // Deserialize...
+ ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ DecimalFormatSymbols deserializedDfs = (DecimalFormatSymbols) in.readObject();
+ assertEquals(-1, in.read());
+
+ // The two objects should claim to be equal.
+ assertEquals(originalDfs, deserializedDfs);
+ }
}
diff --git a/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java b/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java
index fd383aa..5c47153 100644
--- a/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/OldNumberFormatTest.java
@@ -17,9 +17,6 @@
package libcore.java.text;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.text.ChoiceFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
@@ -31,18 +28,8 @@
import junit.framework.TestCase;
import tests.support.Support_Locale;
-@TestTargetClass(NumberFormat.class)
public class OldNumberFormatTest extends TestCase {
- /**
- * @tests java.text.NumberFormat#getIntegerInstance(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getIntegerInstance",
- args = {java.util.Locale.class}
- )
public void test_getIntegerInstanceLjava_util_Locale()
throws ParseException {
// Test for method java.text.NumberFormat
@@ -125,15 +112,6 @@
format.isParseIntegerOnly());
}
- /**
- * @tests java.text.NumberFormat#setMaximumIntegerDigits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMaximumIntegerDigits",
- args = {int.class}
- )
public void test_setMaximumIntegerDigits() {
NumberFormat format = NumberFormat.getInstance();
format.setMaximumIntegerDigits(2);
@@ -143,15 +121,6 @@
assertEquals("Wrong result: case 2", "0", format.format(123));
}
- /**
- * @tests java.text.NumberFormat#setCurrency(java.util.Currency)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setCurrency",
- args = {java.util.Currency.class}
- )
public void test_setCurrencyLjava_util_Currency() {
// Test for method void setCurrency(java.util.Currency)
// a subclass that supports currency formatting
@@ -184,16 +153,6 @@
}
}
- /**
- * @tests java.text.NumberFormat#parseObject(java.lang.String,
- * java.text.ParsePosition)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseObject",
- args = {java.lang.String.class, java.text.ParsePosition.class}
- )
public void test_parseObjectLjava_lang_StringLjava_text_ParsePosition() {
Locale[] requiredLocales = {Locale.FRANCE};
if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
@@ -262,15 +221,6 @@
}
}
- /**
- * @tests java.text.NumberFormat#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
public void test_clone() {
int max_digits = 100;
@@ -292,15 +242,6 @@
nf2.getMaximumIntegerDigits() == max_digits);
}
- /**
- * @tests java.text.NumberFormat#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
public void test_equals() {
NumberFormat nf1 = NumberFormat.getInstance();
@@ -322,15 +263,6 @@
assertFalse("Object is equal null", nf1.equals(null));
}
- /**
- * @tests java.text.NumberFormat#format(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {double.class}
- )
public void test_formatLdouble() {
Locale deLocale = new Locale("de", "CH");
Locale[] requiredLocales = {Locale.US, deLocale};
@@ -367,15 +299,6 @@
// END android-changed
}
- /**
- * @tests java.text.NumberFormat#format(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {long.class}
- )
public void test_formatLlong() {
Locale deLocale = new Locale("de", "CH");
Locale[] requiredLocales = {Locale.US, deLocale};
@@ -413,15 +336,6 @@
// END android-changed
}
- /**
- * @tests java.text.NumberFormat#getAvailableLocales()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableLocales",
- args = {}
- )
public void test_getAvailableLocales() {
Locale[] l = NumberFormat.getAvailableLocales();
@@ -439,15 +353,6 @@
assertTrue("there is no Locale.US", isUS);
}
- /**
- * @tests java.text.NumberFormat#getCurrencyInstance()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCurrencyInstance",
- args = {}
- )
public void test_getCurrencyInstance() {
Locale.setDefault(Locale.US);
@@ -471,15 +376,6 @@
"$1.00", format.format(0.999));
}
- /**
- * @tests java.text.NumberFormat#getCurrencyInstance(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCurrencyInstance",
- args = {java.util.Locale.class}
- )
public void test_getCurrencyInstanceLjava_util_Locale() {
// BEGIN android-changed
Locale usLocale = Locale.US;
@@ -551,15 +447,6 @@
// END android-changed
}
- /**
- * @tests java.text.NumberFormat#getInstance()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {}
- )
public void test_getInstance() {
Locale.setDefault(Locale.US);
NumberFormat format = NumberFormat.getInstance();
@@ -579,15 +466,6 @@
"123,456,789", format.format(123456789));
}
- /**
- * @tests java.text.NumberFormat#getInstance(Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.util.Locale.class}
- )
public void test_getInstanceLjava_util_Locale() {
Locale testLocale = new Locale("de", "CH");
Locale[] requiredLocales = {Locale.US, testLocale};
@@ -633,15 +511,6 @@
// END android-changed
}
- /**
- * @tests java.text.NumberFormat#getNumberInstance()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNumberInstance",
- args = {}
- )
public void test_getNumberInstance() {
Locale.setDefault(Locale.US);
NumberFormat format = NumberFormat.getNumberInstance();
@@ -661,15 +530,6 @@
"123,456,789", format.format(123456789));
}
- /**
- * @tests java.text.NumberFormat#getNumberInstance(Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNumberInstance",
- args = {java.util.Locale.class}
- )
public void test_getNumberInstanceLjava_util_Locale() {
Locale deLocale = new Locale("de", "CH");
Locale[] requiredLocales = {Locale.US, deLocale};
@@ -710,21 +570,11 @@
try {
NumberFormat.getInstance(null);
fail("java.lang.NullPointerException is not thrown");
- } catch (java.lang.NullPointerException npe) {
- // expested
+ } catch (java.lang.NullPointerException expected) {
}
// END android-changed
}
- /**
- * @tests java.text.NumberFormat#getPercentInstance()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPercentInstance",
- args = {}
- )
public void test_getPercentInstance() {
Locale.setDefault(Locale.US);
NumberFormat format = NumberFormat.getPercentInstance();
@@ -744,15 +594,6 @@
"12,345,678,900%", format.format(123456789));
}
- /**
- * @tests java.text.NumberFormat#getPercentInstance(Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPercentInstance",
- args = {java.util.Locale.class}
- )
public void test_getPercentInstanceLjava_util_Locale() {
Locale csLocale = new Locale("cs", "CZ");
Locale[] requiredLocales = {Locale.US, csLocale};
@@ -779,20 +620,10 @@
try {
NumberFormat.getInstance(null);
fail("java.lang.NullPointerException is not thrown");
- } catch (java.lang.NullPointerException npe) {
- // expested
+ } catch (java.lang.NullPointerException expected) {
}
}
- /**
- * @tests java.text.NumberFormat#getMaximumFractionDigits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMaximumFractionDigits",
- args = {}
- )
public void test_getMaximumFractionDigits() {
NumberFormat nf1 = NumberFormat.getInstance();
@@ -813,15 +644,6 @@
+ " instead of Integer.MAX_VALUE", result == Integer.MAX_VALUE);
}
- /**
- * @tests java.text.NumberFormat#getMinimumFractionDigits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMinimumFractionDigits",
- args = {}
- )
public void test_getMinimumFractionDigits() {
NumberFormat nf1 = NumberFormat.getInstance();
nf1.setMinimumFractionDigits(Integer.MAX_VALUE);
@@ -841,15 +663,6 @@
+ " instead of 52", result == 52);
}
- /**
- * @tests java.text.NumberFormat#getMaximumIntegerDigits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMaximumIntegerDigits",
- args = {}
- )
public void test_getMaximumIntegerDigits() {
NumberFormat nf1 = NumberFormat.getInstance();
nf1.setMaximumIntegerDigits(Integer.MAX_VALUE);
@@ -869,15 +682,6 @@
+ " instead of Integer.MAX_VALUE", result == Integer.MAX_VALUE);
}
- /**
- * @tests java.text.NumberFormat#getMinimumIntegerDigits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMinimumIntegerDigits",
- args = {}
- )
public void test_getMinimumIntegernDigits() {
NumberFormat nf1 = NumberFormat.getInstance();
nf1.setMinimumIntegerDigits(Integer.MAX_VALUE);
@@ -897,15 +701,6 @@
+ " instead of 5148", result == 73780);
}
- /**
- * @tests java.text.NumberFormat#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
public void test_hashCode() {
NumberFormat nf1 = NumberFormat.getInstance();
@@ -935,15 +730,6 @@
.hashCode());
}
- /**
- * @tests java.text.NumberFormat#isGroupingUsed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isGroupingUsed",
- args = {}
- )
public void test_isGroupingUsed() {
NumberFormat nf1 = NumberFormat.getInstance();
assertTrue("grouping is not used for NumberFormat.getInstance", nf1
@@ -960,15 +746,6 @@
nf1.isGroupingUsed());
}
- /**
- * @tests java.text.NumberFormat#setGroupingUsed(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setGroupingUsed",
- args = {boolean.class}
- )
public void test_setGroupingUsed() {
Locale csLocale = new Locale("cs", "CZ");
Locale[] requiredLocales = {Locale.US, csLocale};
@@ -1033,15 +810,6 @@
"-123\u00a0456\u00a0789\u00a0010\u00a0%", nf2.format(-1234567890.1));
}
- /**
- * @tests java.text.NumberFormat#isParseIntegerOnly()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isParseIntegerOnly",
- args = {}
- )
public void test_isParseIntegerOnly() {
NumberFormat nf1 = NumberFormat.getInstance();
assertTrue("ParseIntegerOnly is not used for NumberFormat.getInstance",
@@ -1058,15 +826,6 @@
nf1.isParseIntegerOnly());
}
- /**
- * @tests java.text.NumberFormat#setParseIntegerOnly(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setParseIntegerOnly",
- args = {boolean.class}
- )
public void test_setParseIntegerOnly() {
NumberFormat nf1 = NumberFormat.getInstance(Locale.US);
nf1.setParseIntegerOnly(true);
@@ -1088,15 +847,6 @@
"-1,234,567,890", nf1.format(-1234567890.));
}
- /**
- * @tests java.text.NumberFormat#setMaximumFractionDigits(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMaximumFractionDigits",
- args = {int.class}
- )
public void test_setMaximumFractionDigits() {
NumberFormat nf1 = NumberFormat.getInstance(Locale.US);
nf1.setMaximumFractionDigits(Integer.MAX_VALUE);
@@ -1128,15 +878,6 @@
"1,234,567,890", nf1.format(1234567890.0987654321));
}
- /**
- * @tests java.text.NumberFormat#setMinimumFractionDigits(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMinimumFractionDigits",
- args = {int.class}
- )
public void test_setMinimumFractionDigits() {
NumberFormat nf1 = NumberFormat.getInstance(Locale.US);
@@ -1167,15 +908,6 @@
"1,234,567,890.098", nf1.format(1234567890.098));
}
- /**
- * @tests java.text.NumberFormat#setMinimumIntegerDigits(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMinimumIntegerDigits",
- args = {int.class}
- )
public void test_setMinimumIntegerDigits() {
NumberFormat nf1 = NumberFormat.getInstance(Locale.US);
@@ -1203,15 +935,6 @@
+ " instead of Integer.MIN_VALUE", result == 0);
}
- /**
- * @tests java.text.NumberFormat#parse(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parse",
- args = {java.lang.String.class}
- )
@BrokenTest("Fails in CTS, passes in CoreTestRunner")
public void test_parseLjava_lang_String() {
NumberFormat nf1 = NumberFormat.getInstance();
@@ -1274,15 +997,6 @@
}
}
- /**
- * @tests java.text.NumberFormat#NumberFormat()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NumberFormat",
- args = {}
- )
public void test_constructor() {
MyNumberFormat mf = new MyNumberFormat();
assertFalse("Greated NumberFormat object is null", mf == null);
diff --git a/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java
index 4da54e6..cbcf7e9 100644
--- a/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/OldSimpleDateFormatTest.java
@@ -387,12 +387,24 @@
FormatTester test = new FormatTester();
Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 2, 15, 3, 6);
- format.setTimeZone(new SimpleTimeZone(60000, "ONE MINUTE"));
+ TimeZone tz0001 = new SimpleTimeZone(60000, "ONE MINUTE");
+ TimeZone tz0130 = new SimpleTimeZone(5400000, "ONE HOUR, THIRTY");
+ TimeZone tzMinus0130 = new SimpleTimeZone(-5400000, "NEG ONE HOUR, THIRTY");
+
+ format.setTimeZone(tz0001);
+ test.test(" Z", cal, " +0001", DateFormat.TIMEZONE_FIELD);
+ test.test(" ZZZZ", cal, " +0001", DateFormat.TIMEZONE_FIELD);
+ format.setTimeZone(tz0130);
+ test.test(" Z", cal, " +0130", DateFormat.TIMEZONE_FIELD);
+ format.setTimeZone(tzMinus0130);
+ test.test(" Z", cal, " -0130", DateFormat.TIMEZONE_FIELD);
+
+ format.setTimeZone(tz0001);
test.test(" z", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
test.test(" zzzz", cal, " GMT+00:01", DateFormat.TIMEZONE_FIELD);
- format.setTimeZone(new SimpleTimeZone(5400000, "ONE HOUR, THIRTY"));
+ format.setTimeZone(tz0130);
test.test(" z", cal, " GMT+01:30", DateFormat.TIMEZONE_FIELD);
- format.setTimeZone(new SimpleTimeZone(-5400000, "NEG ONE HOUR, THIRTY"));
+ format.setTimeZone(tzMinus0130);
test.test(" z", cal, " GMT-01:30", DateFormat.TIMEZONE_FIELD);
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
diff --git a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
index dd1c99c..2649ba3 100644
--- a/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/SimpleDateFormatTest.java
@@ -103,4 +103,73 @@
c.setTime(d);
return c;
}
+
+ // http://code.google.com/p/android/issues/detail?id=13420
+ public void testParsingUncommonTimeZoneAbbreviations() {
+ String fmt = "yyyy-MM-dd HH:mm:ss.SSS z";
+ String date = "2010-12-23 12:44:57.0 CET";
+ // ICU considers "CET" (Central European Time) to be common in Britain...
+ assertEquals(1293104697000L, parseDate(Locale.UK, fmt, date).getTimeInMillis());
+ // ...but not in the US. Check we can parse such a date anyway.
+ assertEquals(1293104697000L, parseDate(Locale.US, fmt, date).getTimeInMillis());
+ }
+
+ public void testFormattingUncommonTimeZoneAbbreviations() {
+ // In Honeycomb, only one Olson id was associated with CET (or any
+ // other "uncommon" abbreviation).
+ String fmt = "yyyy-MM-dd HH:mm:ss.SSS z";
+ String date = "1970-01-01 01:00:00.000 CET";
+ SimpleDateFormat sdf = new SimpleDateFormat(fmt, Locale.US);
+ sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
+ assertEquals(date, sdf.format(new Date(0)));
+ sdf = new SimpleDateFormat(fmt, Locale.US);
+ sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zurich"));
+ assertEquals(date, sdf.format(new Date(0)));
+ }
+
+ // http://code.google.com/p/android/issues/detail?id=8258
+ public void testTimeZoneFormatting() throws Exception {
+ Date epoch = new Date(0);
+
+ // Create a SimpleDateFormat that defaults to America/Chicago...
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
+ // We should see something appropriate to America/Chicago...
+ assertEquals("1969-12-31 18:00:00 -0600", sdf.format(epoch));
+ // We can set any TimeZone we want:
+ sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
+ assertEquals("1969-12-31 16:00:00 -0800", sdf.format(epoch));
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+ assertEquals("1970-01-01 00:00:00 +0000", sdf.format(epoch));
+
+ // A new SimpleDateFormat will default to America/Chicago...
+ sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
+ // ...and parsing an America/Los_Angeles time will *not* change that...
+ sdf.parse("2010-12-03 00:00:00 -0800");
+ // ...so our time zone here is "America/Chicago":
+ assertEquals("1969-12-31 18:00:00 -0600", sdf.format(epoch));
+ // We can set any TimeZone we want:
+ sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
+ assertEquals("1969-12-31 16:00:00 -0800", sdf.format(epoch));
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+ assertEquals("1970-01-01 00:00:00 +0000", sdf.format(epoch));
+
+ sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+ Date date = sdf.parse("2010-07-08 02:44:48");
+ assertEquals(1278557088000L, date.getTime());
+ sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
+ sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
+ assertEquals("2010-07-07T19:44:48-0700", sdf.format(date));
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+ assertEquals("2010-07-08T02:44:48+0000", sdf.format(date));
+ }
+
+ public void testLocales() throws Exception {
+ // Just run through them all. Handy as a poor man's benchmark, and a sanity check.
+ for (Locale l : Locale.getAvailableLocales()) {
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz", l);
+ sdf.format(new Date(0));
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/DateTest.java b/luni/src/test/java/libcore/java/util/DateTest.java
index 37d36d1..ddcc3e5 100644
--- a/luni/src/test/java/libcore/java/util/DateTest.java
+++ b/luni/src/test/java/libcore/java/util/DateTest.java
@@ -16,7 +16,9 @@
package libcore.java.util;
+import java.util.Calendar;
import java.util.Date;
+import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
@@ -28,4 +30,17 @@
TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
assertEquals("Wed Dec 31 18:00:00 CST 1969", new Date(0).toString());
}
+
+ public void test_toGMTString() throws Exception {
+ // Based on https://issues.apache.org/jira/browse/HARMONY-501
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+ Calendar c = Calendar.getInstance();
+ c.clear();
+ c.set(Calendar.YEAR, 21);
+ assertEquals("Wed Jan 01 00:00:00 PST 21", c.getTime().toString());
+ assertEquals("1 Jan 21 08:00:00 GMT", c.getTime().toGMTString());
+ c.set(Calendar.YEAR, 321);
+ assertEquals("Sun Jan 01 00:00:00 PST 321", c.getTime().toString());
+ assertEquals("1 Jan 321 08:00:00 GMT", c.getTime().toGMTString());
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/OldPriorityQueueTest.java b/luni/src/test/java/libcore/java/util/OldPriorityQueueTest.java
index 041a823..d8750b5 100644
--- a/luni/src/test/java/libcore/java/util/OldPriorityQueueTest.java
+++ b/luni/src/test/java/libcore/java/util/OldPriorityQueueTest.java
@@ -16,9 +16,6 @@
package libcore.java.util;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
@@ -26,20 +23,10 @@
import junit.framework.TestCase;
import tests.util.SerializationTester;
-@TestTargetClass(PriorityQueue.class)
public class OldPriorityQueueTest extends TestCase {
private static final String SERIALIZATION_FILE_NAME = "/serialization/tests/api/java/util/PriorityQueue.golden.ser";
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PriorityQueue",
- args = {int.class}
- )
public void test_ConstructorI() {
PriorityQueue<Object> queue = new PriorityQueue<Object>(100);
assertNotNull(queue);
@@ -54,16 +41,6 @@
}
}
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
public void test_remove_Ljava_lang_Object_using_comparator() {
PriorityQueue<String> queue = new PriorityQueue<String>(10,
new MockComparatorStringByLength());
@@ -78,16 +55,6 @@
assertTrue(queue.remove("AA"));
}
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassCastException.",
- method = "remove",
- args = {java.lang.Object.class}
- )
public void test_remove_Ljava_lang_Object_not_exists() {
Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
List<Integer> list = Arrays.asList(array);
@@ -97,15 +64,6 @@
assertFalse(integerQueue.remove(""));
}
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
public void test_Serialization() throws Exception {
Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
List<Integer> list = Arrays.asList(array);
@@ -120,15 +78,6 @@
assertEquals(0, destIntegerQueue.size());
}
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
public void test_Serialization_casting() throws Exception {
Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
List<Integer> list = Arrays.asList(array);
@@ -143,15 +92,6 @@
assertEquals(array[0], I);
}
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
public void test_SerializationCompatibility_cast() throws Exception {
Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
List<Integer> list = Arrays.asList(array);
diff --git a/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java b/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java
index 19a0bf4..39b0223 100644
--- a/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java
+++ b/luni/src/test/java/libcore/java/util/OldTimeZoneTest.java
@@ -18,16 +18,12 @@
package libcore.java.util;
import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import tests.support.Support_Locale;
-@TestTargetClass(TimeZone.class)
public class OldTimeZoneTest extends TestCase {
class Mock_TimeZone extends TimeZone {
@@ -57,22 +53,10 @@
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TimeZone",
- args = {}
- )
public void test_constructor() {
assertNotNull(new Mock_TimeZone());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
public void test_clone() {
TimeZone tz1 = TimeZone.getDefault();
TimeZone tz2 = (TimeZone)tz1.clone();
@@ -80,12 +64,6 @@
assertTrue(tz1.equals(tz2));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableIDs",
- args = {}
- )
public void test_getAvailableIDs() {
String[] str = TimeZone.getAvailableIDs();
assertNotNull(str);
@@ -95,12 +73,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableIDs",
- args = {int.class}
- )
public void test_getAvailableIDsI() {
String[] str = TimeZone.getAvailableIDs(0);
assertNotNull(str);
@@ -110,12 +82,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {}
- )
public void test_getDisplayName() {
TimeZone tz = TimeZone.getTimeZone("GMT-6");
assertEquals("GMT-06:00", tz.getDisplayName());
@@ -123,12 +89,6 @@
assertEquals("Pacific Standard Time", tz.getDisplayName());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {java.util.Locale.class}
- )
public void test_getDisplayNameLjava_util_Locale() {
Locale[] requiredLocales = {Locale.US, Locale.FRANCE};
if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
@@ -141,12 +101,6 @@
assertEquals("heure normale du Pacifique", tz.getDisplayName(Locale.FRANCE));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {boolean.class, int.class}
- )
public void test_getDisplayNameZI() {
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
assertEquals("PST", tz.getDisplayName(false, 0));
@@ -154,12 +108,6 @@
assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {boolean.class, int.class, java.util.Locale.class}
- )
@AndroidOnly("fail on RI. See comment below")
public void test_getDisplayNameZILjava_util_Locale() {
Locale[] requiredLocales = {Locale.US, Locale.UK, Locale.FRANCE};
@@ -178,12 +126,6 @@
assertEquals("heure normale du Pacifique", tz.getDisplayName(false, 1, Locale.FRANCE));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getID",
- args = {}
- )
public void test_getID() {
TimeZone tz = TimeZone.getTimeZone("GMT-6");
assertEquals("GMT-06:00", tz.getID());
@@ -191,12 +133,6 @@
assertEquals("America/Denver", tz.getID());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasSameRules",
- args = {java.util.TimeZone.class}
- )
public void test_hasSameRulesLjava_util_TimeZone() {
TimeZone tz1 = TimeZone.getTimeZone("America/Denver");
TimeZone tz2 = TimeZone.getTimeZone("America/Phoenix");
@@ -212,12 +148,6 @@
assertTrue(tz1.hasSameRules(tz1));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setID",
- args = {java.lang.String.class}
- )
public void test_setIDLjava_lang_String() {
TimeZone tz = TimeZone.getTimeZone("GMT-6");
assertEquals("GMT-06:00", tz.getID());
diff --git a/luni/src/test/java/libcore/java/util/OldTreeMapTest.java b/luni/src/test/java/libcore/java/util/OldTreeMapTest.java
index ab27cf2..def5e68 100644
--- a/luni/src/test/java/libcore/java/util/OldTreeMapTest.java
+++ b/luni/src/test/java/libcore/java/util/OldTreeMapTest.java
@@ -17,9 +17,6 @@
package libcore.java.util;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.io.Serializable;
import java.text.CollationKey;
import java.text.Collator;
@@ -33,7 +30,6 @@
import java.util.TreeMap;
import tests.support.Support_MapTest2;
-@TestTargetClass(TreeMap.class)
public class OldTreeMapTest extends junit.framework.TestCase {
public static class ReversedComparator implements Comparator {
@@ -84,15 +80,6 @@
Object objArray[] = new Object[1000];
- /**
- * @tests java.util.TreeMap#TreeMap()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {}
- )
public void test_Constructor() {
// Test for method java.util.TreeMap()
new Support_MapTest2(new TreeMap()).runTest();
@@ -100,15 +87,6 @@
assertTrue("New treeMap non-empty", new TreeMap().isEmpty());
}
- /**
- * @tests java.util.TreeMap#TreeMap(java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {java.util.Comparator.class}
- )
public void test_ConstructorLjava_util_Comparator() {
// Test for method java.util.TreeMap(java.util.Comparator)
Comparator comp = new ReversedComparator();
@@ -124,15 +102,6 @@
}
- /**
- * @tests java.util.TreeMap#TreeMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {java.util.Map.class}
- )
public void test_ConstructorLjava_util_Map() {
// Test for method java.util.TreeMap(java.util.Map)
TreeMap myTreeMap = new TreeMap(new HashMap(tm));
@@ -161,15 +130,6 @@
}
}
- /**
- * @tests java.util.TreeMap#TreeMap(java.util.SortedMap)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {java.util.SortedMap.class}
- )
public void test_ConstructorLjava_util_SortedMap() {
// Test for method java.util.TreeMap(java.util.SortedMap)
Comparator comp = new ReversedComparator();
@@ -192,15 +152,6 @@
}
}
- /**
- * @tests java.util.TreeMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
public void test_containsKeyLjava_lang_Object() {
// Test for method boolean
// java.util.TreeMap.containsKey(java.lang.Object)
@@ -222,15 +173,6 @@
}
}
- /**
- * @tests java.util.TreeMap#firstKey()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "firstKey",
- args = {}
- )
public void test_firstKey() {
// Test for method java.lang.Object java.util.TreeMap.firstKey()
assertEquals("Returned incorrect first key", "0", tm.firstKey());
@@ -243,15 +185,6 @@
}
}
- /**
- * @tests java.util.TreeMap#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
public void test_getLjava_lang_Object() {
// Test for method java.lang.Object
// java.util.TreeMap.get(java.lang.Object)
@@ -274,15 +207,6 @@
}
}
- /**
- * @tests java.util.TreeMap#headMap(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "headMap",
- args = {java.lang.Object.class}
- )
public void test_headMapLjava_lang_Object() {
// Test for method java.util.SortedMap
// java.util.TreeMap.headMap(java.lang.Object)
@@ -362,15 +286,6 @@
assertEquals(0, treemap.headMap(null).size());
}
- /**
- * @tests java.util.TreeMap#lastKey()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastKey",
- args = {}
- )
public void test_lastKey() {
// Test for method java.lang.Object java.util.TreeMap.lastKey()
assertTrue("Returned incorrect last key", tm.lastKey().equals(
@@ -384,15 +299,6 @@
}
}
- /**
- * @tests java.util.TreeMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
public void test_putLjava_lang_ObjectLjava_lang_Object() {
// Test for method java.lang.Object
// java.util.TreeMap.put(java.lang.Object, java.lang.Object)
@@ -435,15 +341,6 @@
}
}
- /**
- * @tests java.util.TreeMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
public void test_putAllLjava_util_Map() {
// Test for method void java.util.TreeMap.putAll(java.util.Map)
TreeMap x = new TreeMap();
@@ -472,15 +369,6 @@
}
}
- /**
- * @tests java.util.TreeMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
public void test_removeLjava_lang_Object() {
// Test for method java.lang.Object
// java.util.TreeMap.remove(java.lang.Object)
@@ -502,15 +390,6 @@
}
}
- /**
- * @tests java.util.TreeMap#subMap(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subMap",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
public void test_subMapLjava_lang_ObjectLjava_lang_Object() {
// Test for method java.util.SortedMap
// java.util.TreeMap.subMap(java.lang.Object, java.lang.Object)
@@ -569,15 +448,6 @@
}
}
- /**
- * @tests java.util.TreeMap#tailMap(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tailMap",
- args = {java.lang.Object.class}
- )
public void test_tailMapLjava_lang_Object() {
// Test for method java.util.SortedMap
// java.util.TreeMap.tailMap(java.lang.Object)
diff --git a/luni/src/test/java/libcore/java/util/OldTreeSetTest.java b/luni/src/test/java/libcore/java/util/OldTreeSetTest.java
index 2e0d833..86ed9f4 100644
--- a/luni/src/test/java/libcore/java/util/OldTreeSetTest.java
+++ b/luni/src/test/java/libcore/java/util/OldTreeSetTest.java
@@ -17,9 +17,6 @@
package libcore.java.util;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
@@ -29,22 +26,12 @@
import java.util.SortedSet;
import java.util.TreeSet;
-@TestTargetClass(TreeSet.class)
public class OldTreeSetTest extends junit.framework.TestCase {
TreeSet ts;
Object objArray[] = new Object[1000];
- /**
- * @tests java.util.TreeSet#TreeSet(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeSet",
- args = {java.util.Collection.class}
- )
public void test_ConstructorLjava_util_Collection() {
// Test for method java.util.TreeSet(java.util.Collection)
TreeSet myTreeSet = new TreeSet(Arrays.asList(objArray));
@@ -73,15 +60,6 @@
}
}
- /**
- * @tests java.util.TreeSet#TreeSet(java.util.SortedSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeSet",
- args = {java.util.SortedSet.class}
- )
public void test_ConstructorLjava_util_SortedSet() {
try {
new TreeSet((SortedSet)null);
@@ -91,15 +69,6 @@
}
}
- /**
- * @tests java.util.TreeSet#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
public void test_addLjava_lang_Object() {
// Test for method boolean java.util.TreeSet.add(java.lang.Object)
ts.add(new Integer(-8));
@@ -119,15 +88,6 @@
}
}
- /**
- * @tests java.util.TreeSet#addAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {java.util.Collection.class}
- )
public void test_addAllLjava_util_Collection() {
// Test for method boolean
// java.util.TreeSet.addAll(java.util.Collection)
@@ -157,15 +117,6 @@
}
}
- /**
- * @tests java.util.TreeSet#first()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "first",
- args = {}
- )
public void test_first() {
// Test for method java.lang.Object java.util.TreeSet.first()
assertTrue("Returned incorrect first element",
@@ -180,15 +131,6 @@
}
}
- /**
- * @tests java.util.TreeSet#headSet(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "headSet",
- args = {java.lang.Object.class}
- )
public void test_headSetLjava_lang_Object() {
// Test for method java.util.SortedSet
// java.util.TreeSet.headSet(java.lang.Object)
@@ -220,15 +162,6 @@
}
}
- /**
- * @tests java.util.TreeSet#last()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "last",
- args = {}
- )
public void test_last() {
// Test for method java.lang.Object java.util.TreeSet.last()
assertTrue("Returned incorrect last element",
@@ -243,15 +176,6 @@
}
}
- /**
- * @tests java.util.TreeSet#subSet(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subSet",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
public void test_subSetLjava_lang_ObjectLjava_lang_Object() {
// Test for method java.util.SortedSet
// java.util.TreeSet.subSet(java.lang.Object, java.lang.Object)
@@ -293,15 +217,6 @@
}
}
- /**
- * @tests java.util.TreeSet#tailSet(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tailSet",
- args = {java.lang.Object.class}
- )
public void test_tailSetLjava_lang_Object() {
// Test for method java.util.SortedSet
// java.util.TreeSet.tailSet(java.lang.Object)
diff --git a/luni/src/test/java/libcore/java/util/TimeZoneTest.java b/luni/src/test/java/libcore/java/util/TimeZoneTest.java
index dbde4ac..f7fe649 100644
--- a/luni/src/test/java/libcore/java/util/TimeZoneTest.java
+++ b/luni/src/test/java/libcore/java/util/TimeZoneTest.java
@@ -17,6 +17,7 @@
package libcore.java.util;
import java.util.Date;
+import java.util.Locale;
import java.util.TimeZone;
import java.util.SimpleTimeZone;
@@ -40,4 +41,14 @@
stz.inDaylightTime(new Date());
stz.clone();
}
+
+ // http://b/3049014
+ public void testCustomTimeZoneDisplayNames() {
+ TimeZone tz0001 = new SimpleTimeZone(60000, "ONE MINUTE");
+ TimeZone tz0130 = new SimpleTimeZone(5400000, "ONE HOUR, THIRTY");
+ TimeZone tzMinus0130 = new SimpleTimeZone(-5400000, "NEG ONE HOUR, THIRTY");
+ assertEquals("GMT+00:01", tz0001.getDisplayName(false, TimeZone.SHORT, Locale.US));
+ assertEquals("GMT+01:30", tz0130.getDisplayName(false, TimeZone.SHORT, Locale.US));
+ assertEquals("GMT-01:30", tzMinus0130.getDisplayName(false, TimeZone.SHORT, Locale.US));
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/concurrent/CopyOnWriteArrayListTest.java b/luni/src/test/java/libcore/java/util/concurrent/CopyOnWriteArrayListTest.java
index 8232881..b10be33 100644
--- a/luni/src/test/java/libcore/java/util/concurrent/CopyOnWriteArrayListTest.java
+++ b/luni/src/test/java/libcore/java/util/concurrent/CopyOnWriteArrayListTest.java
@@ -267,4 +267,16 @@
new SerializableTester<CopyOnWriteArrayList<String>>(list, s).test();
}
+
+ /**
+ * Test that we don't retain the array returned by toArray() on the copy
+ * constructor. That array may not be of the required type!
+ */
+ public void testDoesNotRetainToArray() {
+ String[] strings = { "a", "b", "c" };
+ List<String> asList = Arrays.asList(strings);
+ assertEquals(String[].class, asList.toArray().getClass());
+ CopyOnWriteArrayList<Object> objects = new CopyOnWriteArrayList<Object>(asList);
+ objects.add(Boolean.TRUE);
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java b/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java
index b3f57b8..f2d483e 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldNodeChangeEventTest.java
@@ -130,7 +130,7 @@
public synchronized void waitForEvent() {
try {
wait(500);
- } catch (InterruptedException ignored) {
+ } catch (InterruptedException expected) {
}
}
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java b/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java
index be559ed..acdbd69 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldPreferenceChangeEventTest.java
@@ -112,7 +112,7 @@
public synchronized void waitForEvent() {
try {
wait(500);
- } catch (InterruptedException ignored) {
+ } catch (InterruptedException expected) {
}
}
diff --git a/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java b/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java
index a12618e..17e3652 100644
--- a/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java
+++ b/luni/src/test/java/libcore/java/util/prefs/OldPreferencesTest.java
@@ -937,7 +937,7 @@
public synchronized void waitForEvent() {
try {
wait(500);
- } catch (InterruptedException ignored) {
+ } catch (InterruptedException expected) {
}
}
@@ -976,7 +976,7 @@
synchronized (this) {
this.wait(500);
}
- } catch (InterruptedException ignored) {
+ } catch (InterruptedException expected) {
}
}
}
diff --git a/luni/src/test/java/libcore/java/util/regex/OldMatcherTest.java b/luni/src/test/java/libcore/java/util/regex/OldMatcherTest.java
index 549a9ca..450b8d9 100644
--- a/luni/src/test/java/libcore/java/util/regex/OldMatcherTest.java
+++ b/luni/src/test/java/libcore/java/util/regex/OldMatcherTest.java
@@ -17,35 +17,14 @@
package libcore.java.util.regex;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
-@TestTargetClass(
- value = Matcher.class,
- untestedMethods= {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "finalize is hard to test since the implementation only calls a native function",
- method = "finalize",
- args = {}
- )
- }
-
-)
public class OldMatcherTest extends TestCase {
String[] groupPatterns = { "(a|b)*aabb", "((a)|b)*aabb", "((a|b)*)a(abb)",
"(((a)|(b))*)aabb", "(((a)|(b))*)aa(b)b", "(((a)|(b))*)a(a(b)b)" };
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "appendReplacement",
- args = {java.lang.StringBuffer.class, java.lang.String.class}
- )
public void testAppendReplacement() {
Pattern pat = Pattern.compile("XX");
Matcher m = pat.matcher("Today is XX-XX-XX ...");
@@ -78,16 +57,6 @@
assertNotNull(t);
}
- /**
- * @test java.util.regex.Matcher#reset(String)
- * test reset(String) method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the reset(CharSequence input) method.",
- method = "reset",
- args = {java.lang.CharSequence.class}
- )
public void test_resetLjava_lang_String() {
String testPattern = "(abb)";
String testString1 = "babbabbcccabbabbabbabbabb";
@@ -102,12 +71,6 @@
assertTrue("After reset matcher should find pattern in given input", mat.find());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "appendTail",
- args = {java.lang.StringBuffer.class}
- )
public void testAppendTail() {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one-cat-two-cats-in-the-yard");
@@ -143,16 +106,6 @@
assertNotNull(t);
}
- /**
- * @test java.util.regex.Matcher#reset()
- * test reset() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the reset() method. ",
- method = "reset",
- args = {}
- )
public void test_reset() {
String testPattern = "(abb)";
String testString = "babbabbcccabbabbabbabbabb";
@@ -164,16 +117,6 @@
assertTrue("After reset matcher should find pattern in given input", mat.find());
}
- /**
- * @test java.util.regex.Matcher#hasAnchoringBounds()
- * test hasAnchoringBounds() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that hasAnchoringBounds method returns correct value.",
- method = "hasAnchoringBounds",
- args = {}
- )
public void test_hasAnchoringBounds() {
String testPattern = "abb";
String testString = "abb";
@@ -192,16 +135,6 @@
mu.hasAnchoringBounds());
}
- /**
- * @test java.util.regex.Matcher#hasTransparentBounds()
- * test hasTransparentBounds() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that hasTransparentBound method returns correct value.",
- method = "hasTransparentBounds",
- args = {}
- )
public void test_hasTransparentBounds() {
String testPattern = "abb";
String testString = "ab\nb";
@@ -220,16 +153,6 @@
mu.hasTransparentBounds());
}
- /**
- * @test java.util.regex.Matcher#start(int)
- * test start(int) method.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the start(int group) method.",
- method = "start",
- args = {int.class}
- )
public void test_startI() {
String testPattern = "(((abb)a)(bb))";
String testString = "cccabbabbabbabbabb";
@@ -252,16 +175,6 @@
}
}
- /**
- * @test java.util.regex.Matcher#end(int)
- * test end(int) method.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the basic functionality of end(int group) method.",
- method = "end",
- args = {int.class}
- )
public void test_endI() {
String testPattern = "(((abb)a)(bb))";
String testString = "cccabbabbabbabbabb";
@@ -285,16 +198,6 @@
}
- /**
- * @test java.util.regex.Matcher#lookingAt()
- * test lookingAt() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that lookingAt() method returns correct value.",
- method = "lookingAt",
- args = {}
- )
public void test_lookingAt() {
String testPattern = "(((abb)a)(bb))";
String testString1 = "babbabbcccabbabbabbabbabb";
@@ -309,16 +212,6 @@
assertTrue("Should find given pattern in 2 string", mat2.lookingAt());
}
- /**
- * @test java.util.regex.Matcher#find(int)
- * test find (int) method. Created via modifying method for find
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "find",
- args = {int.class}
- )
public void test_findI() {
String testPattern = "(abb)";
String testString = "cccabbabbabbabbabb";
@@ -368,12 +261,7 @@
assertFalse(mat3.find(6));
assertFalse(mat3.find(7));
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies matches() method for predefined.",
- method = "replaceFirst",
- args = {java.lang.String.class}
- )
+
public void testSEOLsymbols() {
Pattern pat = Pattern.compile("^a\\(bb\\[$");
Matcher mat = pat.matcher("a(bb[");
@@ -381,16 +269,6 @@
assertTrue(mat.matches());
}
- /**
- * @test java.util.regex.Matcher#start()
- * test start() method.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the start() method.",
- method = "start",
- args = {}
- )
public void test_start() {
String testPattern = "(abb)";
String testString = "cccabbabbabbabbabb";
@@ -410,16 +288,6 @@
}
}
- /**
- * @test java.util.regex.Matcher#end()
- * test end() method.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the basic functionality of end() method. ",
- method = "end",
- args = {}
- )
public void test_end() {
String testPattern = "(abb)";
String testString = "cccabbabbabbabbabb";
@@ -438,12 +306,7 @@
}
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies groupCount() method.",
- method = "groupCount",
- args = {}
- )
+
public void testGroupCount() {
for (int i = 0; i < groupPatterns.length; i++) {
Pattern test = Pattern.compile(groupPatterns[i]);
@@ -454,12 +317,6 @@
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "region",
- args = {int.class, int.class}
- )
public void testRegion() {
Pattern p = Pattern.compile("abba");
Matcher m = p.matcher("Gabba gabba hey");
@@ -495,12 +352,6 @@
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies matches method for input sequence specified by URL.",
- method = "matches",
- args = {}
- )
public void testMatchesURI() {
Pattern pat = Pattern.
compile("^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
@@ -511,22 +362,10 @@
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "quoteReplacement",
- args = {java.lang.String.class}
- )
public void testQuoteReplacement() {
assertEquals("\\$dollar and slash\\\\", Matcher.quoteReplacement("$dollar and slash\\"));
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "matches",
- args = {}
- )
public void testUnicode() {
assertTrue(Pattern.compile("\\x61a").matcher("aa").matches());
@@ -535,12 +374,7 @@
assertTrue(Pattern.compile("\\0777").matcher("?7").matches());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "matches",
- args = {}
- )
+
public void testUnicodeCategory() {
assertTrue(Pattern.compile("\\p{Ll}").matcher("k").matches()); // Unicode lower case
assertTrue(Pattern.compile("\\P{Ll}").matcher("K").matches()); // Unicode non-lower
@@ -572,13 +406,6 @@
// BEGIN android-note
// Test took ages, now going in steps of 16 code points to speed things up.
// END android-note
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The stress test for matches(String regex) method from String class.",
- clazz = String.class,
- method = "matches",
- args = {java.lang.String.class}
- )
public void testAllCodePoints() {
// Regression for HARMONY-3145
int[] codePoint = new int[1];
@@ -614,16 +441,6 @@
assertEquals(0x110000 / 0x10, cnt);
}
- /**
- * @test java.util.regex.Matcher#regionStart()
- * test regionStart() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the regionStart() method.",
- method = "regionStart",
- args = {}
- )
public void test_regionStart() {
String testPattern = "(abb)";
String testString = "cccabbabbabbabbabb";
@@ -637,16 +454,6 @@
assertEquals("Region sould start from 0 position after reset", 0, mat.regionStart());
}
- /**
- * @test java.util.regex.Matcher#regionEnd()
- * test regionEnd() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the regionEnd() method.",
- method = "regionEnd",
- args = {}
- )
public void test_regionEnd() {
String testPattern = "(abb)";
String testString = "cccabbabbabbabbabb";
@@ -660,16 +467,6 @@
assertEquals("Region end value should be equal to string length after reset", testString.length(), mat.regionEnd());
}
- /**
- * @test java.util.regex.Matcher#toMatchResult()
- * test toMatchResult() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the toMatchResult method.",
- method = "toMatchResult",
- args = {}
- )
public void test_toMatchResult() {
String testPattern = "(((abb)a)(bb))";
String testString = "babbabbcccabbabbabbabbabb";
@@ -687,16 +484,6 @@
assertEquals("Total number of groups does not matched with given pattern", 4, mat.toMatchResult().groupCount());
}
- /**
- * @test java.util.regex.Matcher#usePattern(Pattern newPattern)
- * test usePattern(Pattern newPattern) method.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the usePattern(Pattern newPattern) method.",
- method = "usePattern",
- args = {java.util.regex.Pattern.class}
- )
public void test_usePatternLjava_util_regex_Pattern() {
String testPattern1 = "(((abb)a)(bb))";
String testPattern2 = "(abbabb)";
@@ -713,16 +500,6 @@
assertFalse("matcher should not find pattern in given region", mat.matches());
}
- /**
- * @test java.util.regex.Matcher#useAchoringBounds()
- * test useAchoringBounds() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "useAnchoringBounds",
- args = {boolean.class}
- )
public void test_anchoringBounds() {
String testPattern = "^ro$";
String testString = "android";
@@ -738,16 +515,6 @@
assertFalse("Should find pattern with anchoring bounds", mat.find(0));
}
- /**
- * @test java.util.regex.Matcher#useTransparentBounds()
- * test useTransparentBounds() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the useTransparentBounds(boolean b) method.",
- method = "useTransparentBounds",
- args = {boolean.class}
- )
public void test_transparentBounds() {
String testPattern = "and(?=roid)";
String testString = "android";
@@ -774,16 +541,6 @@
assertFalse("Shouldn't find pattern transparent bounds", mat.matches()); // ***
}
- /**
- * @test java.util.regex.Matcher#hitEnd()
- * test hitEnd() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that hitEnd() method returns correct value. ",
- method = "hitEnd",
- args = {}
- )
public void test_hitEnd() {
String testPattern = "abb";
String testString = "babbabbcccabbabbabbabbabb";
@@ -796,16 +553,6 @@
assertTrue("hitEnd should return true after finding last match", mat.hitEnd()); // ***
}
- /**
- * @test java.util.regex.Matcher#requireEnd()
- * test requireEnd() method.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the requireEnd() method.",
- method = "requireEnd",
- args = {}
- )
public void test_requireEnd() {
String testPattern = "bba";
String testString = "abbbbba";
@@ -827,12 +574,6 @@
/*
* Regression test for HARMONY-674
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Special regression test for matches() method.",
- method = "matches",
- args = {}
- )
public void testPatternMatcher() throws Exception {
Pattern pattern = Pattern.compile("(?:\\d+)(?:pt)");
assertTrue(pattern.matcher("14pt").matches());
diff --git a/luni/src/test/java/libcore/javax/crypto/CipherTest.java b/luni/src/test/java/libcore/javax/crypto/CipherTest.java
index 186355f..7919b35 100644
--- a/luni/src/test/java/libcore/javax/crypto/CipherTest.java
+++ b/luni/src/test/java/libcore/javax/crypto/CipherTest.java
@@ -49,9 +49,9 @@
assertCipherInitWithKeyUsage(KeyUsage.keyAgreement | KeyUsage.decipherOnly,
false, true, false, true);
- // except when wraping a key is specifically allowed or
+ // except when wrapping a key is specifically allowed or
assertCipherInitWithKeyUsage(KeyUsage.keyEncipherment, false, true, true, true);
- // except when wraping data encryption is specifically allowed
+ // except when wrapping data encryption is specifically allowed
assertCipherInitWithKeyUsage(KeyUsage.dataEncipherment, true, true, false, true);
}
@@ -100,16 +100,12 @@
}
}
- private Certificate certificateWithKeyUsage(int keyUsage) {
+ private Certificate certificateWithKeyUsage(int keyUsage) throws Exception {
// note the rare usage of non-zero keyUsage
- return TestKeyStore.create(new String[] { "RSA" },
- null,
- null,
- "rsa-dsa-ec",
- TestKeyStore.localhost(),
- keyUsage,
- true,
- null,
- null).getPrivateKey("RSA", "RSA").getCertificate();
+ return new TestKeyStore.Builder()
+ .aliasPrefix("rsa-dsa-ec")
+ .keyUsage(keyUsage)
+ .build()
+ .getPrivateKey("RSA", "RSA").getCertificate();
}
}
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java
index 241673a..578ee6b 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java
@@ -16,9 +16,6 @@
package libcore.javax.crypto.spec;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import tests.security.AlgorithmParameterGeneratorTest;
import tests.security.AlgorithmParameterKeyAgreementHelper;
@@ -29,23 +26,6 @@
super("DH", new AlgorithmParameterKeyAgreementHelper("DH"));
}
- @TestTargets({
- @TestTargetNew(
- level=TestLevel.ADDITIONAL,
- method="getInstance",
- args={String.class}
- ),
- @TestTargetNew(
- level=TestLevel.ADDITIONAL,
- method="init",
- args={int.class}
- ),
- @TestTargetNew(
- level=TestLevel.COMPLETE,
- method="method",
- args={}
- )
- })
@BrokenTest("Suffers from DH slowness, disabling for now")
public void testAlgorithmParameterGenerator() {
super.testAlgorithmParameterGenerator();
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java
index 9cf2fcd..165daa1 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/AlgorithmParametersTestDH.java
@@ -16,9 +16,6 @@
package libcore.javax.crypto.spec;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import java.math.BigInteger;
import javax.crypto.spec.DHParameterSpec;
import tests.security.AlgorithmParameterKeyAgreementHelper;
@@ -64,23 +61,6 @@
}
- @TestTargets({
- @TestTargetNew(
- level=TestLevel.ADDITIONAL,
- method="getInstance",
- args={String.class}
- ),
- @TestTargetNew(
- level=TestLevel.ADDITIONAL,
- method="init",
- args={byte[].class}
- ),
- @TestTargetNew(
- level=TestLevel.COMPLETE,
- method="method",
- args={}
- )
- })
@BrokenTest("Suffers from DH slowness, disabling for now")
public void testAlgorithmParameters() {
super.testAlgorithmParameters();
diff --git a/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java b/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java
index 6e73ba1..c4322ff 100644
--- a/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java
+++ b/luni/src/test/java/libcore/javax/crypto/spec/KeyPairGeneratorTestDH.java
@@ -16,9 +16,6 @@
package libcore.javax.crypto.spec;
import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
import java.security.NoSuchAlgorithmException;
import tests.security.KeyAgreementHelper;
import tests.security.KeyPairGeneratorTest;
@@ -29,23 +26,6 @@
super("DH", new KeyAgreementHelper("DH"));
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "initialize",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- method = "generateKeyPair",
- args = {}
- ),
- @TestTargetNew(
- level=TestLevel.COMPLETE,
- method="method",
- args={}
- )
- })
@BrokenTest("Takes ages due to DH computations. Disabling for now.")
public void testKeyPairGenerator() throws NoSuchAlgorithmException {
super.testKeyPairGenerator();
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 2ff9567..a6bdc07 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/KeyManagerFactoryTest.java
@@ -23,9 +23,9 @@
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
+import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
-import java.util.HashSet;
import java.util.Set;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
@@ -40,16 +40,18 @@
public class KeyManagerFactoryTest extends TestCase {
// note the rare usage of DSA keys here in addition to RSA
- private static final TestKeyStore TEST_KEY_STORE
- = TestKeyStore.create(new String[] { "RSA", "DSA", "EC", "EC_RSA" },
- null,
- null,
- "rsa-dsa-ec",
- TestKeyStore.localhost(),
- 0,
- true,
- null,
- null);
+ private static final TestKeyStore TEST_KEY_STORE;
+
+ static {
+ try {
+ TEST_KEY_STORE = new TestKeyStore.Builder()
+ .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
+ .aliasPrefix("rsa-dsa-ec")
+ .build();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
public void test_KeyManagerFactory_getDefaultAlgorithm() throws Exception {
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
@@ -58,7 +60,7 @@
test_KeyManagerFactory(kmf);
}
- private static class UseslessManagerFactoryParameters implements ManagerFactoryParameters {}
+ private static class UselessManagerFactoryParameters implements ManagerFactoryParameters {}
private static boolean supportsManagerFactoryParameters(String algorithm) {
// Only the "New" one supports ManagerFactoryParameters
@@ -94,7 +96,7 @@
// init with useless ManagerFactoryParameters
try {
- kmf.init(new UseslessManagerFactoryParameters());
+ kmf.init(new UselessManagerFactoryParameters());
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
@@ -123,7 +125,8 @@
test_KeyManagerFactory_getKeyManagers(kmf, false);
}
- private void test_KeyManagerFactory_getKeyManagers(KeyManagerFactory kmf, boolean empty) {
+ private void test_KeyManagerFactory_getKeyManagers(KeyManagerFactory kmf, boolean empty)
+ throws Exception {
KeyManager[] keyManagers = kmf.getKeyManagers();
assertNotNull(keyManagers);
assertTrue(keyManagers.length > 0);
@@ -153,7 +156,8 @@
// extra null at end requires no initialization
}
- private void test_X509KeyManager(X509KeyManager km, boolean empty, String algorithm) {
+ private void test_X509KeyManager(X509KeyManager km, boolean empty, String algorithm)
+ throws Exception {
String[] keyTypes = keyTypes(algorithm);
for (String keyType : keyTypes) {
String[] aliases = km.getClientAliases(keyType, null);
@@ -196,7 +200,7 @@
}
private void test_X509ExtendedKeyManager(X509ExtendedKeyManager km,
- boolean empty, String algorithm) {
+ boolean empty, String algorithm) throws Exception {
String[] keyTypes = keyTypes(algorithm);
String a = km.chooseEngineClientAlias(keyTypes, null, null);
test_X509KeyManager_alias(km, a, null, true, empty);
@@ -215,7 +219,7 @@
String alias,
String keyType,
boolean many,
- boolean empty) {
+ boolean empty) throws Exception {
if (empty || (!many && (keyType == null || keyType.isEmpty()))) {
assertNull(keyType, alias);
assertNull(keyType, km.getCertificateChain(alias));
@@ -251,8 +255,8 @@
PrivateKeyEntry privateKeyEntry = TEST_KEY_STORE.getPrivateKey(keyAlgName, sigAlgName);
if (!"EC".equals(keyAlgName)) {
assertEquals(keyType,
- Arrays.asList(privateKeyEntry.getCertificateChain()),
- Arrays.asList(certificateChain));
+ Arrays.<Certificate>asList(privateKeyEntry.getCertificateChain()),
+ Arrays.<Certificate>asList(certificateChain));
assertEquals(keyType,
privateKeyEntry.getPrivateKey(), privateKey);
}
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 d7e7c67..16a3359 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
@@ -16,8 +16,6 @@
package libcore.javax.net.ssl;
-import libcore.java.security.StandardNames;
-import libcore.java.security.TestKeyStore;
import java.util.Arrays;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
@@ -27,6 +25,8 @@
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import junit.framework.TestCase;
+import libcore.java.security.StandardNames;
+import libcore.java.security.TestKeyStore;
public class SSLEngineTest extends TestCase {
@@ -69,16 +69,11 @@
public void test_SSLEngine_getSupportedCipherSuites_connect() throws Exception {
// note the rare usage of non-RSA keys
- TestKeyStore testKeyStore
- = TestKeyStore.create(new String[] { "RSA", "DSA", "EC", "EC_RSA" },
- null,
- null,
- "rsa-dsa-ec",
- TestKeyStore.localhost(),
- 0,
- true,
- null,
- null);
+ TestKeyStore testKeyStore = new TestKeyStore.Builder()
+ .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
+ .aliasPrefix("rsa-dsa-ec")
+ .ca(true)
+ .build();
test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, false);
if (StandardNames.IS_RI) {
test_SSLEngine_getSupportedCipherSuites_connect(testKeyStore, true);
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 35346a2..7ca5a63 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
@@ -55,16 +55,11 @@
public void test_SSLSocket_getSupportedCipherSuites_connect() throws Exception {
// note the rare usage of non-RSA keys
- TestKeyStore testKeyStore
- = TestKeyStore.create(new String[] { "RSA", "DSA", "EC", "EC_RSA" },
- null,
- null,
- "rsa-dsa-ec",
- TestKeyStore.localhost(),
- 0,
- true,
- null,
- null);
+ TestKeyStore testKeyStore = new TestKeyStore.Builder()
+ .keyAlgorithms("RSA", "DSA", "EC", "EC_RSA")
+ .aliasPrefix("rsa-dsa-ec")
+ .ca(true)
+ .build();
if (StandardNames.IS_RI) {
test_SSLSocket_getSupportedCipherSuites_connect(testKeyStore,
StandardNames.JSSE_PROVIDER_NAME,
@@ -382,9 +377,12 @@
if (false) {
System.out.println("Session=" + session);
System.out.println("CipherSuite=" + cipherSuite);
- System.out.println("LocalCertificates=" + localCertificates);
- System.out.println("PeerCertificates=" + peerCertificates);
- System.out.println("PeerCertificateChain=" + peerCertificateChain);
+ System.out.println("LocalCertificates="
+ + Arrays.toString(localCertificates));
+ System.out.println("PeerCertificates="
+ + Arrays.toString(peerCertificates));
+ System.out.println("PeerCertificateChain="
+ + Arrays.toString(peerCertificateChain));
System.out.println("PeerPrincipal=" + peerPrincipal);
System.out.println("LocalPrincipal=" + localPrincipal);
System.out.println("Socket=" + socket);
@@ -1058,7 +1056,7 @@
/**
* Not run by default by JUnit, but can be run by Vogar by
- * specifying it explictly (or with main method below)
+ * specifying it explicitly (or with main method below)
*/
public void stress_test_TestSSLSocketPair_create() {
final boolean verbose = true;
@@ -1081,7 +1079,7 @@
}
}
- public static final void main (String[] args) {
+ public static void main (String[] args) {
new SSLSocketTest().stress_test_TestSSLSocketPair_create();
}
}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java b/luni/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
index e92bf67..b82b4d2 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/TrustManagerFactoryTest.java
@@ -17,11 +17,10 @@
package libcore.javax.net.ssl;
import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore;
+import java.security.KeyStore.PrivateKeyEntry;
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;
@@ -41,16 +40,18 @@
private static final String [] KEY_TYPES = new String[] { "RSA", "DSA", "EC", "EC_RSA" };
// 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-ec",
- TestKeyStore.localhost(),
- 0,
- true,
- null,
- null);
+ private static final TestKeyStore TEST_KEY_STORE;
+ static {
+ try {
+ TEST_KEY_STORE = new TestKeyStore.Builder()
+ .keyAlgorithms(KEY_TYPES)
+ .aliasPrefix("rsa-dsa-ec")
+ .ca(true)
+ .build();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
public void test_TrustManagerFactory_getDefaultAlgorithm() throws Exception {
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
@@ -59,7 +60,7 @@
test_TrustManagerFactory(tmf, StandardNames.IS_RI);
}
- private static class UseslessManagerFactoryParameters implements ManagerFactoryParameters {}
+ private static class UselessManagerFactoryParameters implements ManagerFactoryParameters {}
private void test_TrustManagerFactory(TrustManagerFactory tmf,
boolean supportsManagerFactoryParameters)
@@ -84,7 +85,7 @@
// init with useless ManagerFactoryParameters
try {
- tmf.init(new UseslessManagerFactoryParameters());
+ tmf.init(new UselessManagerFactoryParameters());
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
@@ -141,7 +142,7 @@
assertNotNull(issuers);
assertTrue(issuers.length > 1);
assertNotSame(issuers, tm.getAcceptedIssuers());
- boolean defaultTrustmanager
+ boolean defaultTrustManager
// RI de-duplicates certs from TrustedCertificateEntry and PrivateKeyEntry
= issuers.length > (StandardNames.IS_RI ? 1 : 2) * KEY_TYPES.length;
@@ -149,7 +150,7 @@
String sigAlgName = TestKeyStore.signatureAlgorithm(keyType);
PrivateKeyEntry pke = TEST_KEY_STORE.getPrivateKey(keyAlgName, sigAlgName);
X509Certificate[] chain = (X509Certificate[]) pke.getCertificateChain();
- if (defaultTrustmanager) {
+ if (defaultTrustManager) {
try {
tm.checkClientTrusted(chain, keyType);
fail();
diff --git a/luni/src/test/java/tests/SQLite/AbstractSqlTest.java b/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java
similarity index 88%
rename from luni/src/test/java/tests/SQLite/AbstractSqlTest.java
rename to luni/src/test/java/libcore/sqlite/AbstractSqlTest.java
index 937a1d3..d194548 100644
--- a/luni/src/test/java/tests/SQLite/AbstractSqlTest.java
+++ b/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java
@@ -14,30 +14,21 @@
* limitations under the License.
*/
+package libcore.sqlite;
-package tests.SQLite;
-
-import SQLite.Callback;
-import SQLite.Database;
import SQLite.Exception;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
+import junit.framework.TestCase;
/**
* This class provides SQL unit test, which can be used by subclasses eg. to
* test JDBC drivers.
*/
-@TestTargetClass(Database.class)
abstract class AbstractSqlTest extends TestCase {
/**
@@ -93,8 +84,7 @@
* @exception Exception may be thrown by subclasses
*/
@Override
- protected void setUp() throws InstantiationException,
- IllegalAccessException, ClassNotFoundException, SQLException, Exception {
+ protected void setUp() throws java.lang.Exception {
Class.forName(getDriverClassName()).newInstance();
firstConnection = DriverManager.getConnection(getConnectionURL());
firstConnection.setTransactionIsolation(getTransactionIsolation());
@@ -157,13 +147,6 @@
assertTrue(i == ones.length);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- clazz = Database.class,
- method = "exec",
- args = {String.class, Callback.class}
- )
public void testAutoCommitInsertSelect() throws SQLException{
autoCommitInsertSelect();
}
@@ -178,13 +161,6 @@
*
* @throws SQLException if there is a problem accessing the database
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- clazz = Database.class,
- method = "exec",
- args = {String.class, Callback.class}
- )
public void testUpdateSelectCommitSelect() throws SQLException {
autoCommitInsertSelect();
firstStmt.getConnection().setAutoCommit(false);
@@ -204,13 +180,6 @@
*
* @throws SQLException if there is a problem accessing the database
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- clazz = Database.class,
- method = "exec",
- args = {String.class, Callback.class}
- )
public void testUpdateSelectRollbackSelect() throws SQLException {
autoCommitInsertSelect();
firstStmt.getConnection().setAutoCommit(false);
diff --git a/luni/src/test/java/libcore/sqlite/OldBlobTest.java b/luni/src/test/java/libcore/sqlite/OldBlobTest.java
new file mode 100644
index 0000000..3289d38
--- /dev/null
+++ b/luni/src/test/java/libcore/sqlite/OldBlobTest.java
@@ -0,0 +1,135 @@
+/*
+ * 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 libcore.sqlite;
+
+import SQLite.Blob;
+import SQLite.Database;
+import SQLite.Exception;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import tests.support.Support_SQL;
+
+public final class OldBlobTest extends OldSQLiteTest {
+
+ private static Blob testBlob = null;
+
+ private static Database db = null;
+
+ public void setUp() throws java.lang.Exception {
+ super.setUp();
+ testBlob = new Blob();
+
+ super.setUp();
+ Support_SQL.loadDriver();
+ db = new Database();
+ db.open(dbFile.getPath(), 0);
+
+ db.exec("create table B(id integer primary key, val blob)",null);
+ db.exec("insert into B values(1, zeroblob(128))", null);
+ db.exec("insert into B values(2, zeroblob(128))", null);
+ db.exec("insert into B values(3, zeroblob(128))", null);
+
+ // can not fill Blob with data at this point...
+ /*
+ File resources = Support_Resources.createTempFolder();
+ BufferedReader r = null;
+ try {
+ Class c = Class.forName(this.getClass().getName());
+ assertNotNull(c);
+ file = Class.forName(this.getClass().getName())
+ .getResourceAsStream("/blob.c");
+ r = new BufferedReader(new InputStreamReader(file));
+ } catch (NullPointerException e) {
+ fail("Should not throw NullPointerException reading file"
+ + e.getMessage());
+ }
+ OutputStream out = testBlob.getOutputStream();
+ String s = null;
+ while ((s = r.readLine()) != null) {
+ out.write(r.readLine().getBytes());
+ }
+ out.flush();
+ out.close();
+ testBlob.close();
+ */
+ }
+
+ @Override public void tearDown() throws java.lang.Exception {
+ testBlob.close();
+ super.tearDown();
+ }
+
+ /**
+ * db.open_blob is not supported.
+ */
+ public void testBlob() throws Exception, IOException {
+ byte[] b = new byte[4];
+ byte[] b128 = new byte[128];
+ for (int i = 0; i < b128.length; i++) {
+ b128[i] = (byte) i;
+ }
+ Blob blob = db.open_blob(dbFile.getPath(), "B", "val", 1, true);
+ try {
+
+ OutputStream os = blob.getOutputStream();
+ os.write(b128);
+ os.close();
+
+ InputStream is = blob.getInputStream();
+ is.skip(96);
+ assertEquals(4,is.read(b));
+ is.close();
+ } finally {
+ blob.close();
+ }
+ }
+
+ public void testGetInputStream() {
+ InputStream in = testBlob.getInputStream();
+ try {
+ in.read();
+ fail("Exception not thrown for invalid Blob.");
+ } catch (Throwable e) {
+ //ok
+ }
+ }
+
+ public void testGetOutputStream() {
+ OutputStream out = testBlob.getOutputStream();
+
+ try {
+ out.write(null);
+ fail("Write operation unsupported");
+ } catch (Throwable e) {
+ assertEquals("Write operation unsupported", e.getMessage());
+ }
+ }
+
+ public void testClose() {
+ assertNotNull(testBlob);
+
+ testBlob.close();
+ // inputStream either null or some error occurs
+ try {
+ // TODO This does look a bit weird. Revisit later.
+ assertNull(testBlob.getInputStream());
+ } catch (Throwable e) {
+ //ok
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java b/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java
new file mode 100644
index 0000000..f2cbc57
--- /dev/null
+++ b/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java
@@ -0,0 +1,1224 @@
+/*
+ * 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 libcore.sqlite;
+
+import SQLite.Authorizer;
+import SQLite.Blob;
+import SQLite.BusyHandler;
+import SQLite.Callback;
+import SQLite.Constants;
+import SQLite.Database;
+import SQLite.Exception;
+import SQLite.Function;
+import SQLite.FunctionContext;
+import SQLite.ProgressHandler;
+import SQLite.Stmt;
+import SQLite.TableResult;
+import SQLite.Trace;
+import SQLite.Vm;
+import java.io.File;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.logging.Logger;
+import tests.support.DatabaseCreator;
+import tests.support.MockFunction;
+import tests.support.ThreadPool;
+
+public final class OldDatabaseTest extends OldSQLiteTest {
+
+ private static ErrorTracker tracker = null;
+
+ private Statement statement;
+
+ private Database db = null;
+
+ private static final int numThreads = 10;
+
+ private static final int numOfRecords = 30;
+
+ @Override public void setUp() throws java.lang.Exception {
+ super.setUp();
+ assertNotNull("Could not establish DB connection",conn);
+ tracker = new ErrorTracker();
+
+ statement = conn.createStatement();
+
+ // Cleanup tables if necessary
+
+ DatabaseMetaData meta = conn.getMetaData();
+ assertNotNull(meta);
+ ResultSet userTab = meta.getTables(null, null, null, null);
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ this.statement.execute("drop table " + tableName);
+ }
+
+ // Create default test table
+ statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
+ statement.close();
+
+ db = new Database();
+ db.open(dbFile.getPath(), 0);
+ db.busy_handler(null);
+ }
+
+ public void tearDown() throws java.lang.Exception {
+ try {
+ db.close();
+ } catch (Exception e) {
+ if (!(e.getMessage().equals("database already closed"))) {
+ System.err.println("Error closing DB " + dbFile.getPath());
+ }
+ }
+ tracker.reset();
+ super.tearDown();
+ }
+
+ public void testDatabase() throws Exception {
+ // db closed
+ Database db2 = new Database();
+ db.close();
+ db2 = new Database();
+ db2.open(dbFile.getPath(), 0);
+ db2.close();
+ db.open(dbFile.getPath(), 0);
+ //db is open
+ db2.open(dbFile.getPath(), 0);
+ db2.close();
+ }
+
+ public void testOpen() throws Exception {
+ db.close();
+ db.open(dbFile.getPath(), 0);
+ // open second db while db1 still open
+ Database db2 = new Database();
+ db2.open(dbFile.getPath(), 0);
+ db2.open(dbFile.getPath(), 0);
+ db2.close();
+ // open non db file
+ try {
+ URL file = OldDatabaseTest.class.getResource("/blob.c");
+ db2.open(file.getPath(), 0);
+ fail("Should not be able to open non db file");
+ } catch (SQLite.Exception e) {
+ assertEquals("unknown error in open", e.getMessage());
+ }
+ }
+
+ public void testOpen_aux_file() {
+ File temp = null;
+ try {
+ db.open_aux_file("");
+ fail("open should fail");
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+
+ /*
+ try {
+ temp = File.createTempFile("openAuxMethod", ".db");
+ db.open_aux_file("");
+ db.exec("create table AUX_TABLE", null);
+ db.close();
+ } catch (Exception e) {
+ temp.delete();
+ fail("Error handling temporary file "+e.getMessage());
+ e.printStackTrace();
+ } catch (IOException e) {
+ temp.delete();
+ fail("Could not create temporary File");
+ e.printStackTrace();
+ }
+ try {
+ db.open(dbFile.getPath(),0);
+ db.exec("select * from AUX_TABLE", null);
+ fail("Statement should fail");
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ temp.delete();
+ */
+ }
+
+ public void testClose() throws Exception {
+ try {
+ db.close();
+ db.get_table("test");
+ fail();
+ } catch (Exception e) {
+ assertTrue(e.getMessage().equals("database already closed"));
+ try {
+ db.open(dbFile.getPath(), 0);
+ } catch (Exception e1) {
+ fail("Database object could not be reopened after 'close': "
+ + e.getMessage());
+ e1.printStackTrace();
+ }
+ }
+
+ try {
+ db.close();
+ db.close();
+ fail();
+ } catch (Exception e) {
+ assertTrue(e.getMessage().equals("database already closed"));
+ db.open(dbFile.getPath(), 0);
+ }
+ }
+
+ public void testExecStringCallback() throws Exception {
+ TableResult res = new TableResult();
+ db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(1, 10, 20)", null);
+ db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
+ db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1 + " where 1", null);
+ String row[] = (String[]) res.rows.elementAt(0);
+ assertEquals(Integer.parseInt(row[0]), 1);
+ assertEquals(Integer.parseInt(row[1]), 10);
+ assertEquals(Integer.parseInt(row[2]), 20);
+ }
+
+ public void testExecStringCallbackStringArray() throws Exception {
+ TableResult res = new TableResult();
+ String args[] = new String[1];
+ args[0] = "table";
+ db.exec("select name from sqlite_master where type = '%q';", res, args);
+ String[] s = (String[]) res.rows.elementAt(0);
+ assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
+
+ try {
+ db.exec("select name from sqlite_master where type = ", res, args);
+ fail("Testmethod should fail");
+ } catch (Exception e) {
+ // Ok
+ }
+ }
+
+ public void testLast_insert_rowid() throws Exception {
+ assertEquals(0, db.last_insert_rowid());
+ db.exec("create table TEST5(id integer, firstname text, lastname text);", null);
+ db.exec("insert into TEST5 values (1,'James','Bond');", null);
+ db.exec("insert into TEST5 values (2,'Fiona','Apple');", null);
+ assertEquals(2, db.last_insert_rowid());
+ assertEquals(db.last_insert_rowid(), db.last_insert_rowid());
+
+ db.exec("drop table TEST5;", null);
+ assertEquals(2, db.last_insert_rowid());
+ }
+
+ /**
+ * Reason for failure unknown: Database should be locked. Specification
+ * of interrupt is scarce.
+ */
+ public void testInterrupt() throws Exception, SQLException {
+ ThreadPool threadPool = new ThreadPool(numThreads);
+
+ // initialization
+ ResultSet userTabs;
+ userTabs = conn.getMetaData().getTables(null, null, null, null);
+ while (userTabs.next()) {
+ String tableName = userTabs.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ }
+ }
+ db.exec(DatabaseCreator.CREATE_TABLE3, null);
+ db.exec(DatabaseCreator.CREATE_TABLE1, null);
+
+ int id1 = numOfRecords - 3;
+ threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
+ // should not be able to do any other insertions since task 1 holds lock
+ int id2 = numOfRecords + 3;
+ threadPool
+ .runTask(createTask2Interrupt(id2, dbFile.getPath(), tracker));
+
+ threadPool.join();
+
+ List<String> errors = tracker.getErrors();
+ System.out.println("Last error: " + db.error_message());
+ if (errors.size() > 0) {
+ assertEquals(errors.get(0), db.error_string(Constants.SQLITE_LOCKED));
+ for (String s : errors) {
+ Logger.global.info("INTERRUPT Error: " + s);
+ }
+
+ } else {
+ fail("Should have one exception: database should be locked.");
+ }
+
+ // reset
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", null);
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", null);
+ }
+
+ /**
+ * Returns wrong number for updates: returns value > 1 for select.
+ */
+ public void testChanges() throws Exception {
+ TableResult res = new TableResult();
+ assertTrue(db.changes() == 0);
+ db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(2, 5, 7);", null);
+ int rows = (int) db.changes();
+ assertEquals(1,db.changes());
+ db.exec("update " + DatabaseCreator.SIMPLE_TABLE1
+ + " set speed = 7, size= 5 where id = 2;", null);
+ assertEquals(1,db.changes());
+ db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
+ assertEquals(0,db.changes());
+ db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(8, 5, 7);", null);
+ db.exec("Update "+DatabaseCreator.SIMPLE_TABLE1+" set speed = 10;",null);
+ assertTrue(db.changes() > 2);
+ }
+
+ /**
+ * method test fails once in a while. Cannot be sure that exception is
+ * thrown in every test execution.
+ */
+ public void testBusy_handler() throws SQLException, Exception {
+ TestBusyHandler bh = new TestBusyHandler();
+ db.busy_handler(bh);
+ int counter = 0;
+ ThreadPool threadPool = new ThreadPool(numThreads);
+
+ // initialization
+ ResultSet userTabs;
+ userTabs = conn.getMetaData().getTables(null, null, null, null);
+ while (userTabs.next()) {
+ String tableName = userTabs.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ }
+ }
+ db.exec(DatabaseCreator.CREATE_TABLE3, null);
+ db.exec(DatabaseCreator.CREATE_TABLE1, null);
+
+
+ try {
+ conn.setAutoCommit(false);
+ int id1 = numOfRecords - 3;
+ threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
+ int id2 = numOfRecords + 3;
+ threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
+ int oldID = 5;
+ int newID = 100;
+ threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID,
+ tracker));
+
+ threadPool.join();
+
+ List<String> errors = tracker.getErrors();
+ if (errors.size() > 0) {
+// assertEquals(errors.get(0),
+// db.error_string(Constants.SQLITE_LOCKED));
+ for (String s: errors) {
+ System.out.println("Round 2 Error: "+s);
+ }
+ } else {
+ fail("No error happened");
+ }
+
+ // reset
+
+
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
+ null);
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
+ null);
+//
+// // increase timeout for retry
+// db.busy_timeout(1000);
+// db.busy_handler(bh);
+// tracker.reset();
+
+// threadPool = new ThreadPool(numThreads);
+//
+// threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
+// threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
+//
+// threadPool.join();
+//
+// errors = tracker.getErrors();
+// if (errors.size() > 0) {
+// // assertEquals(errors.get(0),
+// // db.error_string(Constants.SQLITE_LOCKED));
+// for (String s: errors) {
+// System.out.println("Round 2 Error"+s);
+// }
+// } else {
+// // ok
+// System.out.println("BUSY: No Error!");
+// }
+//
+//
+ } finally {
+ conn.setAutoCommit(true);
+ db.exec(DatabaseCreator.DROP_TABLE1, null);
+ db.exec(DatabaseCreator.DROP_TABLE3, null);
+ }
+ }
+
+ /**
+ * test fails. Cannot be sure that exception is thrown every time.
+ * Database does not lock values.
+ */
+ public void testBusy_timeout() throws Exception, SQLException {
+ int counter = 0;
+ ThreadPool threadPool = new ThreadPool(numThreads);
+
+ // initialization
+ ResultSet userTabs = conn.getMetaData().getTables(null, null, null, null);
+ while (userTabs.next()) {
+ String tableName = userTabs.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ }
+ }
+ db.exec(DatabaseCreator.CREATE_TABLE3, null);
+ db.exec(DatabaseCreator.CREATE_TABLE1, null);
+
+ // test run
+ try {
+ conn.setAutoCommit(false);
+
+// DatabaseCreator.fillTestTable1(conn, numOfRecords);
+ // set to fail immediately if table is locked.
+ db.busy_handler(null);
+ db.busy_timeout(0);
+ int id1 = numOfRecords - 3;
+
+ threadPool.runTask(createTask2(id1, dbFile.getPath(), tracker));
+ int id2 = numOfRecords + 3;
+ threadPool.runTask(createTask1(id2, dbFile.getPath(), tracker));
+ int oldID = 5;
+ int newID = 100;
+ threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID,
+ tracker));
+
+ threadPool.join();
+
+ List<String> errors = tracker.getErrors();
+ assertTrue("No error occurred on DB but should have",errors.size() > 0);
+
+ assertEquals(errors.get(0),
+ db.error_string(Constants.SQLITE_LOCKED));
+ assertEquals(errors.get(0), "database is locked");
+
+ // reset
+
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
+ null);
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
+ null);
+
+ // increase timeout for retry
+ db.busy_timeout(10000);
+ db.busy_handler(null);
+ tracker.reset();
+ threadPool = new ThreadPool(numThreads);
+
+ threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
+ threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
+
+ threadPool.join();
+
+ errors = tracker.getErrors();
+ if (errors.size() > 0) {
+ fail("busy timeout should prevent from lock exception!");
+ for (String s: errors) {
+ System.out.println("Round 2 Error"+s);
+ }
+ } else {
+ // ok
+ }
+ } finally {
+ conn.setAutoCommit(true);
+ // cleanup
+ db.exec(DatabaseCreator.DROP_TABLE1, null);
+ db.exec(DatabaseCreator.DROP_TABLE3, null);
+ }
+ }
+
+ public void testGet_tableString() throws Exception {
+ TableResult emptyTable = new TableResult();
+ //select from empty table
+ TableResult res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ assertEquals(res.toString(), emptyTable.toString());
+ //fill table-> t
+// DatabaseCreator.fillSimpleTable1(conn);
+// res = db.get_table("select * from "
+// + DatabaseCreator.SIMPLE_TABLE1);
+// assertFalse(emptyTable.toString().equals(res.toString()));
+
+ db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 + " VALUES(1, 10, 20)", null);
+ res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1
+ + " where 1", null);
+ String row[] = (String[]) res.rows.elementAt(0);
+ assertEquals(Integer.parseInt(row[0]), 1);
+ assertEquals(Integer.parseInt(row[1]), 10);
+ assertEquals(Integer.parseInt(row[2]), 20);
+ }
+
+ public void testGet_tableStringStringArray() throws Exception {
+ String args[] = new String[1];
+ args[0] = "table";
+ String argsFail[] = new String[1];
+ try {
+ db.get_table("select name from sqlite_master where type = ", argsFail);
+ fail("Testmethod should fail");
+ } catch (Exception e) {
+ }
+
+ TableResult res = db.get_table(
+ "select name from sqlite_master where type = '%q'",
+ args);
+ String[] s = (String[]) res.rows.elementAt(0);
+ assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
+ }
+
+ public void testGet_tableStringStringArrayTableResult() throws Exception {
+ String args[] = new String[1];
+ String argsFail[] = new String[1];
+ TableResult res = new TableResult();
+ TableResult defaultTableRes = new TableResult();
+ args[0] = "table";
+
+ try {
+ db.get_table("select name from sqlite_master where type = '%q'", argsFail, res);
+ assertEquals(defaultTableRes.toString(), res.toString());
+ } catch (Exception e) {
+ db.get_table("select name from sqlite_master where type = '%q'", args, res);
+ String[] s = (String[]) res.rows.elementAt(0);
+ assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
+ System.out.println("DatabaseTest.testGet_tableStringStringArrayTableResult() "
+ + Arrays.toString(res.types));
+ }
+ }
+
+ public void testComplete() {
+ assertFalse(db.complete("create"));
+ assertTrue(db.complete("create table TEST (res double);"));
+ }
+
+ public void testVersion() {
+ String version = db.version();
+ if (version != null) {
+ assertTrue(Integer.parseInt(db.version().substring(0, 1)) > 0);
+ assertEquals(db.version(), db.version());
+ } else {
+ fail("DB version info missing");
+ }
+ }
+
+ public void testDbversion() throws Exception {
+ String verNo = "";
+ try {
+ verNo = db.dbversion();
+ db.close();
+ assertEquals(db.dbversion(),"unknown");
+ db.open(dbFile.getPath(), 0);
+ assertEquals(verNo, db.dbversion());
+ } catch (Exception e) {
+ db.open(dbFile.getPath(), 0);
+ }
+
+ assertTrue(Integer.parseInt(verNo.substring(0, 1))>= 3 );
+
+ }
+
+ public void testCreate_function() throws Exception {
+ double input = 1.0;
+ db.exec("create table TEST (res double)", null);
+ db.exec("insert into TEST values (" + Double.toString(input) + ")",
+ null);
+ TableResult res = new TableResult();
+ Function sinFunc = (Function) new SinFunc();
+ db.create_function("sin", 1, sinFunc);
+ db.exec("select sin(res) from TEST WHERE res = "
+ + Double.toString(input), res);
+ String row[] = (String[]) res.rows.elementAt(0);
+ String val = row[0];
+ double sinusVal = Double.parseDouble(val);
+ double funcVal = Math.sin(input);
+
+ assertTrue(Math.round(funcVal) == Math.round(sinusVal));
+ }
+
+ /**
+ * Aggregation function not called.
+ */
+ public void testCreate_aggregate() throws Exception {
+ TestTrace t = new TestTrace();
+ MockFunction aggFunction = new MockFunction();
+ db.exec("create table TEST(id integer, firstname text, lastname text)", null);
+ db.exec("insert into TEST values(3, 'James', 'Bond'); ", null);
+ db.exec("insert into TEST values(4, 'Fiona', 'Apple'); ", null);
+ db.trace((Trace) t);
+ db.create_aggregate("myaggfunc", 1, aggFunction);
+ db.function_type("myaggfunc", Constants.SQLITE3_TEXT);
+ db.exec("PRAGMA show_datatypes = on", null);
+
+ assertFalse(aggFunction.functionCalled);
+ assertFalse(aggFunction.stepCalled);
+ assertFalse(aggFunction.lastStepCalled);
+ db.exec("select myaggfunc(TEST.firstname) from TEST", t);
+ assertTrue(aggFunction.stepCalled);
+ assertTrue(aggFunction.lastStepCalled);
+ assertTrue(aggFunction.functionCalled);
+
+ assertEquals("James Fiona ",aggFunction.getAggValue());
+ db.exec("drop table TEST", null);
+
+ try {
+ db.create_aggregate("myaggfunc", 0, null);
+ } catch (Throwable e) {
+ assertEquals("null SQLite.Function not allowed",e.getMessage());
+ }
+
+ try {
+ db.create_aggregate("myaggfunc", 0, aggFunction);
+ } catch (Throwable e) {
+ assertEquals("wrong number of arguments to function myaggfunc()",e.getMessage());
+ }
+ }
+
+ public void testFunction_type() throws Exception {
+ double input = 1.0;
+ TableResult res = new TableResult();
+ Function sinFunc = (Function) new SinFunc();
+
+ db.exec("PRAGMA show_datatypes = on", null);
+ db.exec("create table TEST (res double)", null);
+ db.exec("insert into TEST values (" + Double.toString(input) + ")",
+ null);
+
+ db.create_function("sin", 1, sinFunc);
+ db.function_type("sin", Constants.SQLITE_FLOAT);
+ res = db.get_table("select sin(res) from TEST WHERE res = "
+ + Double.toString(input));
+
+ String row[] = (String[]) res.rows.elementAt(0);
+ String val = row[0];
+ assertTrue("double".equalsIgnoreCase(res.types[0]));
+ assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val)));
+
+ // function determines return type: test that Double type is returned.
+ db.function_type("sin", Constants.SQLITE_BLOB);
+ Stmt s = db.prepare("select sin(res) from TEST WHERE res = ?");
+ s.bind(1, input);
+ s.step();
+
+ res = db.get_table("select sin(res) from TEST WHERE res = "
+ + Double.toString(input));
+ assertTrue("double".equalsIgnoreCase(res.types[0]));
+ row = (String[]) res.rows.elementAt(0);
+ val = row[0];
+ assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val)));
+ }
+
+ public void testLast_error() {
+ assertEquals(db.last_error(), Constants.SQLITE_OK);
+ try {
+ db.exec("create table TEST (res double)",null);
+ db.exec("create table TEST (res double)",null);
+ fail("Error should have happened");
+ } catch (Exception e) {
+ assertEquals(db.last_error(),db.last_error());
+ assertEquals(db.last_error(),Constants.SQLITE_ERROR);
+ }
+ }
+
+ public void testSet_last_error() {
+ assertEquals(db.last_error(), Constants.SQLITE_OK);
+ try {
+ db.exec("sel from test;", null);
+ } catch (Exception e) {
+ assertEquals(Constants.SQLITE_ERROR,db.last_error());
+ }
+ }
+
+ public void testError_message() {
+ String statement = "create table TEST (res double)";
+ try {
+ db.exec(statement,null);
+ db.exec(statement,null);
+ fail("DB Error expected");
+ } catch (Exception e) {
+ String dbError = db.error_message();
+ assertTrue(e.getMessage().equals(dbError));
+
+ }
+ }
+
+ public void testError_string() {
+ TestTrace t = new TestTrace();
+ assertEquals(db.last_error(), Constants.SQLITE_OK);
+ String errorString = db.error_string(Constants.SQLITE_ERROR);
+ try {
+ db.trace((Trace) t);
+ db.exec("create table TEST (res double)", t);
+ db.exec("create table TEST (res double)", t);
+ } catch (Exception e) {
+ assertEquals(db.last_error(), Constants.SQLITE_ERROR);
+ if (db.is3()) {
+ assertEquals("Unsupported Method (sqlite 3): error_string", db
+ .error_string(db.last_error()), errorString);
+ }
+ }
+ }
+
+ /**
+ * ASCII encoding does not work: a UTF encoded val is returned. Spec is not
+ * sufficient. Might be that test impl is wrong or String constructor for
+ * the ASCII encoding.
+ */
+ public void testSet_encoding() throws UnsupportedEncodingException, Exception {
+ String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana?
+ TableResult res = new TableResult();
+ String refOutput = null;
+ Stmt stat = null;
+
+ // DB setup
+ db.exec("create table encodingTest (encoded text DEFAULT NULL);",
+ null);
+ stat = db
+ .prepare("insert into encodingTest(encoded) values(:one);");
+ stat.bind(1, input);
+ stat.step();
+ // stat.close();
+ db.exec("select * from encodingTest;", res);
+ String[] encInput = (String[]) res.rows.elementAt(0);
+ String output = encInput[0];
+ assertEquals(input, output);
+ // db.exec("delete from encodingTest where 1", null);
+
+ // tests for different encoding schemes
+ String[] charsetNames = {"UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE"};
+ for (int i = 0; i < charsetNames.length; i++) {
+ byte[] encInputBytes = input.getBytes(charsetNames[i]);
+ db.set_encoding(charsetNames[i]);
+ db.exec("select * from encodingTest;", res);
+ String[] encOutput = (String[]) res.rows.elementAt(0);
+ String inputAsString = new String(encInputBytes,charsetNames[i]);
+ assertEquals(inputAsString, encOutput[0]);
+ }
+
+ // Default tests
+ db.set_encoding("UTF-16");
+ db.exec("select * from encodingTest;", res);
+ String[] encOutput1 = (String[]) res.rows.elementAt(0);
+ assertEquals("Got "+encOutput1[0]+" as UTF-16",input,encOutput1[0]);
+
+ db.set_encoding("US-ASCII");
+ db.exec("select * from encodingTest;", res);
+ String[] encOutput2 = (String[]) res.rows.elementAt(0);
+ assertEquals(new String(input.getBytes(),"US-ASCII"),encOutput2[0]);
+
+ // DB teardown
+ stat.close();
+ db.exec("delete from encodingTest", null);
+
+ // Default tests
+ try {
+ db.set_encoding("");
+ fail("invalid input should fail");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * Callback never made for authorization. Results of private table are
+ * returned withouth furhter checks.
+ *
+ * Test fails -> implemented correctly?
+ */
+ public void testSet_authorizer() throws Exception {
+ TableResult resPriv = null;
+ TableResult resPub = null;
+ TableResult emptyTable = new TableResult();
+ String insertPublic = "insert into public_table values(1,2)";
+ String insertPrivate = "insert into private_table values(1,2)";
+ // prepare, authorizer is not activated yet
+ db.exec("create table public_table(c1 integer, c2 integer);", null);
+ db.exec("create table private_table(c1 integer, c2 integer);", null);
+ // inserts
+ db.exec(insertPublic, null);
+ db.exec(insertPrivate, null);
+ // selects
+ resPriv = db.get_table("select * from private_table");
+ resPub = db.get_table("select * from public_table");
+
+// db.exec("delete from public_table where 1", null);
+// TableResult emptyPubTable = db.exec("select * from public");
+
+ // set Authorizer (positive case): denies private table
+ AuthorizerCallback cb = new AuthorizerCallback();
+ db.set_authorizer(cb);
+ //select
+
+ db.exec("select * from private_table", cb);
+ assertTrue(cb.wasCalled());
+
+ /*
+ TableResult res = db.get_table("select * from private_table");
+ assertEquals(emptyTable.toString(),res.toString());
+ assertFalse(emptyTable.equals(resPriv));
+
+ res = db.get_table("select * from public_table");
+ assertEquals(resPub,res);
+ */
+
+ // Try insert
+ try {
+ db.exec(insertPublic, null);
+ fail("authorization failed");
+ } catch (Exception e) {
+ }
+
+ try {
+ db.exec(insertPrivate, null);
+ fail("authorization failed");
+ } catch (Exception e1) {
+ // ok
+ }
+ }
+
+ public void testTrace() throws Exception {
+ String stmt = "create table TEST (res double);";
+ TestTrace t = new TestTrace();
+ assertFalse(t.traceCalled);
+ assertEquals(db.last_error(),Constants.SQLITE_OK);
+ db.trace((Trace) t);
+ db.exec(stmt,t);
+ assertTrue(t.traceCalled);
+ assertEquals(t.getTrace(),stmt);
+
+ try {
+ db.close();
+ db.exec(stmt,t);
+ fail("Exception Expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testCompileString() throws Exception {
+ db.compile("select name from sqlite_master;");
+ try {
+ db.compile("test");
+ fail("Compiling of inaccurate statement does not fail.");
+ } catch (Exception e) {
+ }
+ }
+
+ public void testCompileStringStringArray() throws Exception {
+ String args[] = new String[1];
+ args[0] = "table";
+ db.compile("select name from sqlite_master where type = '%q';",args);
+
+ try {
+ db.compile("test",null);
+ fail("Compiling of inaccurate statement does not fail.");
+ } catch (Exception e) {
+ }
+ }
+
+ public void testPrepare() throws Exception {
+ Stmt st = null;
+ Stmt st2 = null;
+ // test empty statement
+ try {
+ st = db.prepare("");
+ assertEquals(0, st.bind_parameter_count());
+ st.step();
+ fail("stmt should not be prepared");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ // test statement with unbound arguments
+ try {
+ st2 = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(3, st2.bind_parameter_count());
+ assertEquals(3, st2.bind_parameter_index(":three"));
+ assertEquals(":two", st2.bind_parameter_name(2));
+ } finally {
+ st2.close();
+ }
+
+ try {
+ db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values(:one,:two,:three,:four);");
+ } catch (Exception e) {
+ assertEquals("table " + DatabaseCreator.SIMPLE_TABLE1
+ + " has 3 columns but 4 values were supplied", e
+ .getMessage());
+ }
+
+ try {
+ db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values(5, '10, 20);");
+ } catch (Exception e) {
+ assertEquals("unrecognized token: \"'10, 20);\"", e.getMessage());
+ }
+
+ try {
+ db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values(5, 10 20);");
+ } catch (Exception e) {
+ assertEquals("near \"20\": syntax error", e.getMessage());
+ }
+
+ }
+
+ /**
+ * Not supported.
+ */
+ public void testOpen_blob() throws Exception, java.lang.Exception {
+ Stmt statement2;
+ Blob blobInput = new Blob();
+
+ // Create test input Blob
+ InputStream inStream = null;
+ byte[] in = {(byte) 1, (byte) 2, (byte) 3, (byte) 4};
+
+ // setup test input
+ db.exec("create table TEST (res blob)",null);
+ inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c");
+ assertNotNull(inStream);
+
+ // insert byte array in db
+ statement2 = db.prepare("insert into TEST(res) values (?)");
+ statement2.bind(1, in);
+ statement2.step();
+ statement2.close();
+
+ // read from db
+ Blob blob = db.open_blob(dbFile.getPath(), "TEST", "res", 1, true);
+ if (blob == null) {
+ fail("Blob could not be retrieved");
+ }
+ //read from blob and compare values (positive case)
+ InputStream is = blob.getInputStream();
+
+ int i = 0;
+ int outByte = 0;
+ byte[] out = new byte[4];
+ while ((outByte = is.read()) > -1) {
+ out[i] = (byte) outByte;
+ i++;
+ }
+ is.close();
+
+ blob.close();
+
+ assertTrue(Arrays.equals(in, out));
+
+ //read from blob and compare values (default blob)
+ db.exec("insert into TEST values(zeroblob(128))", null);
+ Blob blob2 = db.open_blob(dbFile.getPath(), "TEST", "res", 2, true);
+ is = blob2.getInputStream();
+ for (i = 0; i < 128; i++) {
+ assertEquals(0, is.read());
+ }
+ is.close();
+ }
+
+ public void testIs3() {
+ int ver = Integer.parseInt(db.version().substring(0,1));
+ if (db.is3()) {
+ assertTrue( ver == 3);
+ } else {
+ assertTrue(ver != 3);
+ }
+ }
+
+ public void testProgress_handler() throws Exception {
+ int inputVal = 3;
+ TestProgressHandler prog = new TestProgressHandler();
+ db.exec("create table TEST5(id integer, firstname text, lastname text)",null);
+ Vm vm = db.compile("select * from TEST5; "
+ + "insert into TEST5 values(3, 'James', 'Bond'); "
+ + "delete from TEST5 where id = 3; "
+ + "select * from TEST5");
+ int stmt = 0;
+ do {
+ ++stmt;
+ if (stmt > inputVal) {
+ db.progress_handler(inputVal, prog);
+ } else {
+ assertEquals(0, prog.getCounts());
+ }
+ while (vm.step(prog)) {
+ }
+ } while (vm.compile());
+ assertEquals(inputVal,prog.getCounts());
+
+ // Boundary value test
+ inputVal = 0;
+ TestProgressHandler progBoundary = new TestProgressHandler();
+ db.progress_handler(inputVal, progBoundary);
+ Vm vm2 = db.compile("select * from TEST5; "
+ + "insert into TEST5 values(3, 'James', 'Bond'); "
+ + "delete from TEST5 where id = 3; "
+ + "select * from TEST5");
+ do {
+ vm2.step(progBoundary);
+ } while (vm2.compile());
+ assertEquals(inputVal, progBoundary.getCounts());
+
+ try {
+ db.exec("drop table TEST5",null);
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ class SinFunc implements Function {
+ public void function(FunctionContext fc, String args[]) {
+ Double d = new Double(args[0]);
+ fc.set_result(Math.sin(d.doubleValue()));
+ }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
+ }
+
+ class TestTrace implements Trace,Callback {
+
+ private StringBuffer buf = new StringBuffer();
+
+ public boolean traceCalled = false;
+
+ public String getTrace() {
+ return buf.toString();
+ }
+
+ public void trace(String stmt) {
+ traceCalled = true;
+ buf.append(stmt);
+ }
+
+ public void columns(String[] coldata) {}
+
+ public boolean newrow(String[] rowdata) {
+ return false;
+ }
+
+ public void types(String[] types) {}
+ }
+
+ class AuthorizerCallback implements Authorizer, Callback {
+
+ private boolean isAuthorizing = false;
+
+ public boolean wasCalled() {
+ return isAuthorizing;
+ }
+
+ public int authorize(int action, String arg1, String arg2, String arg3,
+ String arg4) {
+ Logger.global.info("DB authorization callback " + action + " " + arg1 + " " + arg2 + " "
+ + arg3 + " " + arg4 + " ");
+ this.isAuthorizing = true;
+ if (action != Constants.SQLITE_SELECT || arg1.contains("private_table")) {
+ return Constants.SQLITE_DENY;
+ } else {
+ return Constants.SQLITE_OK;
+ }
+ }
+
+ public void columns(String[] coldata) {}
+
+ public boolean newrow(String[] rowdata) {
+ return false;
+ }
+
+ public void types(String[] types) {}
+
+ }
+
+ class TestBusyHandler implements BusyHandler, Callback {
+
+ public boolean busy(String table, int count) {
+ return true;
+ }
+
+ public void columns(String[] coldata) {}
+
+ public boolean newrow(String[] rowdata) {
+ return false;
+ }
+
+ public void types(String[] types) {}
+ }
+
+ class TestProgressHandler implements ProgressHandler, Callback {
+
+ private boolean progressed = false;
+
+ private int counter = 0;
+
+ public int getCounts() {
+ return counter;
+ }
+
+ public boolean progress() {
+ this.progressed = true;
+ counter++;
+ return true;
+ }
+
+ public void columns(String[] coldata) {}
+
+ public boolean newrow(String[] rowdata) {
+ return false;
+ }
+
+ public void types(String[] types) {}
+ }
+
+ /**
+ * This method creates a Runnable that executes insert operation for the first table
+ */
+ private static Runnable createTask2Interrupt(final int id,
+ final String dbName, final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ Database db = new Database();
+ try {
+ String value = DatabaseCreator.defaultString + id;
+
+ db.open(dbName, 0);
+ String insertQuery = "INSERT INTO "
+ + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id
+ + ", '" + value + "', " + id + ", " + id + ")";
+ db.exec(insertQuery, null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+ try {
+ db.interrupt();
+ db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1
+ + " WHERE id=" + id, null);
+ } catch (Exception e1) {
+ errorTracker.registerException(this, e1);
+ }
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes delete operation for the first table
+ */
+ private static Runnable createTask1(final int id, final String dbName,
+ final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Database db = new Database();
+ db.open(dbName, 0);
+ db.exec("DELETE FROM "
+ + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id, null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes insert operation for the first table
+ */
+ private static Runnable createTask2(final int id, final String dbName,
+ final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ try {
+ String value = DatabaseCreator.defaultString + id;
+ Database db = new Database();
+ db.open(dbName, 0);
+ String insertQuery = "INSERT INTO "
+ + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id
+ + ", '" + value + "', " + id + ", " + id + ")";
+ db.exec(insertQuery, null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes update operation for the one record of the first
+ * table
+ */
+ private static Runnable createTask3(final int oldID, final String dbName,
+ final int newID, final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ Database db = new Database();
+ try {
+ db.open(dbName, 0);
+ String value = DatabaseCreator.defaultString + newID;
+ String updateQuery = "UPDATE "
+ + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID
+ + ", field1='" + value + "', field2=" + newID
+ + ", field3=" + newID + " WHERE id=" + oldID;
+ db.exec(updateQuery, null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+ }
+ }
+ };
+ }
+
+ private class ErrorTracker {
+
+ private List<String> errors = new ArrayList<String>();
+
+ public void registerException(Runnable runnable, Exception e) {
+ System.out.println("Registered: " + e.getMessage());
+ errors.add(e.getMessage());
+ }
+
+ public List<String> getErrors() {
+ return errors;
+ }
+
+ public void reset() {
+ errors.clear();
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/SQLite/ExceptionTest.java b/luni/src/test/java/libcore/sqlite/OldExceptionTest.java
similarity index 60%
rename from luni/src/test/java/tests/SQLite/ExceptionTest.java
rename to luni/src/test/java/libcore/sqlite/OldExceptionTest.java
index fa11422..dddfd6b 100644
--- a/luni/src/test/java/tests/SQLite/ExceptionTest.java
+++ b/luni/src/test/java/libcore/sqlite/OldExceptionTest.java
@@ -14,40 +14,20 @@
* limitations under the License.
*/
-package tests.SQLite;
+package libcore.sqlite;
import SQLite.Database;
import SQLite.Exception;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import junit.framework.TestCase;
-
-@TestTargetClass(SQLite.Exception.class)
-public class ExceptionTest extends SQLiteTest {
+public final class OldExceptionTest extends OldSQLiteTest {
private Database db = null;
- public void setUp() throws java.lang.Exception {
+ @Override public void setUp() throws java.lang.Exception {
super.setUp();
db = new Database();
}
- public void tearDown() {
- super.tearDown();
- }
-
- /**
- * @tests {@link Exception#Exception(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "constructor test",
- method = "Exception",
- args = {java.lang.String.class}
- )
public void testException() {
try {
db.open(dbFile.getName(), 0);
@@ -56,5 +36,4 @@
assertNotNull(e.getMessage());
}
}
-
}
diff --git a/luni/src/test/java/tests/SQLite/FunctionContextTest.java b/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java
similarity index 67%
rename from luni/src/test/java/tests/SQLite/FunctionContextTest.java
rename to luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java
index b63b802..0924317 100644
--- a/luni/src/test/java/tests/SQLite/FunctionContextTest.java
+++ b/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.SQLite;
+package libcore.sqlite;
import SQLite.Database;
import SQLite.Exception;
@@ -22,54 +22,25 @@
import SQLite.FunctionContext;
import SQLite.Stmt;
import SQLite.TableResult;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.sql.Statement;
-
import tests.support.DatabaseCreator;
-@TestTargetClass(FunctionContext.class)
-public class FunctionContextTest extends SQLiteTest {
+public final class OldFunctionContextTest extends OldSQLiteTest {
private Database db = null;
- public void setUp() throws java.lang.Exception {
- Statement st = null;
+ @Override public void setUp() throws java.lang.Exception {
super.setUp();
db = new Database();
db.open(dbFile.getPath(), 0);
- st = conn.createStatement();
+ Statement st = conn.createStatement();
st.execute(DatabaseCreator.CREATE_TABLE2);
st.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
st.close();
}
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- public void tearDown() {
- super.tearDown();
- }
-
- /**
- * Test method for {@link SQLite.FunctionContext#set_result(java.lang.String)}.
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "indirectly tested invoking function",
- method = "set_result",
- args = {java.lang.String.class}
- )
public void testSet_resultString() throws Exception {
TestFCString testString = new TestFCString();
db.exec("insert into " + DatabaseCreator.TEST_TABLE2
@@ -83,16 +54,6 @@
assertEquals("TestInput", val);
}
- /**
- * Test method for {@link SQLite.FunctionContext#set_result(int)}.
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "method test",
- method = "set_result",
- args = {int.class}
- )
public void testSet_resultInt() throws Exception {
TestFCInt testInt = new TestFCInt();
db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
@@ -106,16 +67,6 @@
assertEquals(testInt.intVal, Integer.parseInt(val));
}
- /**
- * Test method for {@link SQLite.FunctionContext#set_result(double)}.
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "indirectly tested",
- method = "set_result",
- args = {double.class}
- )
public void testSet_resultDouble() throws Exception {
SinFunc testD = new SinFunc();
db.exec("insert into " + DatabaseCreator.TEST_TABLE2
@@ -131,16 +82,6 @@
assertTrue(testD.functionCalled);
}
- /**
- * Test method for {@link SQLite.FunctionContext#set_error(java.lang.String)}.
- * @throws Exception
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "set_error",
- args = {java.lang.String.class}
- )
public void testSet_error() throws Exception {
TestFCError testError = new TestFCError();
SinFunc testD = new SinFunc();
@@ -159,17 +100,6 @@
assertFalse(testD.functionCalled);
}
- /**
- * Test method for {@link SQLite.FunctionContext#set_result(byte[])}.
- * @throws Exception
- * @throws UnsupportedEncodingException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "set_result",
- args = {byte[].class}
- )
public void testSet_resultByteArray() throws Exception, UnsupportedEncodingException {
Stmt st = null;
TestFCByteArray testBinArrayFnc = new TestFCByteArray();
@@ -203,17 +133,8 @@
}
/**
- * Test method for {@link SQLite.FunctionContext#set_result_zeroblob(int)}.
- * @throws Exception
- * @throws UnsupportedEncodingException
+ * ZeroBlob not supported
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "set_result_zeroblob",
- args = {int.class}
- )
- @KnownFailure("ZeroBlob not supported")
public void testSet_result_zeroblob() throws Exception,
UnsupportedEncodingException {
Stmt st = null;
@@ -251,17 +172,8 @@
}
/**
- * Test method for {@link SQLite.FunctionContext#count()}.
- * @throws SQLException
- * @throws Exception
+ * Test Method results in a segmentation fault
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "count",
- args = {}
- )
- @AndroidOnly("Test Method results in a segmentation fault.")
public void testCount() throws SQLException, Exception {
TestFCCount countTest = new TestFCCount();
int inputCount = 10;
@@ -293,15 +205,8 @@
fc.set_error(errorMsg);
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
class TestFCCount implements Function {
@@ -314,15 +219,8 @@
fc.set_result(noOfRows);
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
class TestFCZeroBlob implements Function {
@@ -334,15 +232,8 @@
fc.set_result_zeroblob(numBytes);
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
class TestFCString implements Function {
@@ -355,15 +246,8 @@
fc.set_result(args[0]);
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
class TestFCInt implements Function {
@@ -376,15 +260,8 @@
fc.set_result(Integer.parseInt(args[0]));
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
class TestFCByteArray implements Function {
@@ -397,19 +274,11 @@
fc.set_result(args[0].getBytes());
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
- class SinFunc implements Function {
-
+ class SinFunc implements Function {
public Double testDouble = 3.0;
public boolean functionCalled = false;
@@ -419,15 +288,8 @@
fc.set_result(d.doubleValue());
}
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
+ public void last_step(FunctionContext fc) {}
+ public void step(FunctionContext fc, String[] args) {}
}
static final byte[] HEX_CHAR_TABLE = {
@@ -437,7 +299,7 @@
(byte)'c', (byte)'d', (byte)'e', (byte)'f'
};
- public static String getHexString(byte[] raw)
+ public static String getHexString(byte[] raw)
throws UnsupportedEncodingException {
byte[] hex = new byte[2 * raw.length];
int index = 0;
@@ -449,5 +311,4 @@
}
return new String(hex, "ASCII");
}
-
}
diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java
new file mode 100644
index 0000000..48eeab1
--- /dev/null
+++ b/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java
@@ -0,0 +1,64 @@
+/*
+ * 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 libcore.sqlite;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+/**
+ * Tests the SQLite.JDBCDriver.
+ */
+public class OldJDBCDriverFunctionalTest extends AbstractSqlTest {
+ private File dbFile = null;
+ private String connectionURL = "empty";
+
+ @Override protected void tearDown() throws SQLException {
+ super.tearDown();
+ dbFile.delete();
+ }
+
+ @Override protected String getConnectionURL() {
+ if (connectionURL.equals("empty")) {
+ String tmp = System.getProperty("java.io.tmpdir");
+ File tmpDir = new File(tmp);
+ if (tmpDir.isDirectory()) {
+ try {
+ dbFile = File.createTempFile("JDBCDriverFunctionalTest", ".db", tmpDir);
+ } catch (IOException e) {
+ System.err.println("error creating temporary DB file.");
+ }
+ dbFile.deleteOnExit();
+ } else {
+ System.err.println("java.io.tmpdir does not exist");
+ }
+
+ connectionURL = "jdbc:sqlite:/" + dbFile.getPath();
+ }
+
+ return connectionURL;
+ }
+
+ @Override protected String getDriverClassName() {
+ return "SQLite.JDBCDriver";
+ }
+
+ @Override protected int getTransactionIsolation() {
+ return Connection.TRANSACTION_SERIALIZABLE;
+ }
+}
diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java
new file mode 100644
index 0000000..ae06dc6
--- /dev/null
+++ b/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java
@@ -0,0 +1,113 @@
+/*
+ * 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 libcore.sqlite;
+
+import SQLite.JDBCDriver;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+
+
+public final class OldJDBCDriverTest extends OldJDBCDriverFunctionalTest {
+
+ /**
+ * The SQLite db file.
+ */
+ private JDBCDriver jDriver;
+
+ private Driver returnedDriver;
+
+ @Override public void setUp() throws java.lang.Exception {
+ super.setUp();
+ returnedDriver = DriverManager.getDriver(getConnectionURL());
+ if (returnedDriver instanceof JDBCDriver) {
+ this.jDriver = (JDBCDriver) returnedDriver;
+ }
+ }
+
+ public void testJDBCDriver() {
+ assertTrue(returnedDriver instanceof JDBCDriver);
+ }
+
+ public void testAcceptsURL() {
+ try {
+ if (this.jDriver != null) {
+ assertTrue(jDriver.acceptsURL(getConnectionURL()));
+ } else {
+ fail("no Driver available");
+ }
+ } catch (SQLException e) {
+ fail("Driver does not accept URL");
+ e.printStackTrace();
+ }
+ }
+
+ public void testConnect() {
+ try {
+ if (this.jDriver != null) {
+ Connection c = jDriver.connect(getConnectionURL(), null);
+ assertFalse(c.isClosed());
+ DriverManager.getConnection(getConnectionURL());
+ } else {
+ fail("no Driver available");
+ }
+ } catch (SQLException e) {
+ fail("Driver does not connect");
+ e.printStackTrace();
+ }
+ }
+
+ public void testGetMajorVersion() {
+ if (this.jDriver != null) {
+ assertTrue(jDriver.getMajorVersion() > 0);
+ } else {
+ fail("no Driver available");
+ }
+ }
+
+ public void testGetMinorVersion() {
+ if (this.jDriver != null) {
+ assertTrue(jDriver.getMinorVersion() > 0);
+ } else {
+ fail("no version information available");
+ }
+ }
+
+ public void testGetPropertyInfo() throws SQLException {
+ DriverPropertyInfo[] info = null;
+ if (this.jDriver != null) {
+ info = jDriver.getPropertyInfo(getConnectionURL(), null);
+ assertNotNull(info);
+ assertTrue(info.length > 0);
+ } else {
+ fail("no Driver available");
+ }
+
+ assertNotNull(info);
+
+ }
+
+ public void testJdbcCompliant() {
+ if (this.jDriver != null) {
+ assertFalse(jDriver.jdbcCompliant());
+ } else {
+ fail("no version information available");
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/SQLite/SQLiteTest.java b/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java
similarity index 64%
rename from luni/src/test/java/tests/SQLite/SQLiteTest.java
rename to luni/src/test/java/libcore/sqlite/OldSQLiteTest.java
index 7b64173..e6b7f22 100644
--- a/luni/src/test/java/tests/SQLite/SQLiteTest.java
+++ b/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java
@@ -14,22 +14,22 @@
* limitations under the License.
*/
-package tests.SQLite;
-
-import junit.framework.TestCase;
+package libcore.sqlite;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
-import java.sql.SQLException;
import java.util.logging.Logger;
+import junit.framework.TestCase;
-public class SQLiteTest extends TestCase {
+public abstract class OldSQLiteTest extends TestCase {
+
public static Connection conn;
+
public static File dbFile = null;
- public void setUp() throws Exception {
+ @Override public void setUp() throws Exception {
String tmp = System.getProperty("java.io.tmpdir");
File tmpDir = new File(tmp);
try {
@@ -43,32 +43,20 @@
Class.forName("SQLite.JDBCDriver").newInstance();
if (!dbFile.exists()) {
- Logger.global.severe("DB file could not be created. Tests can not be executed.");
+ Logger.global.severe("DB file could not be created. Tests can not be executed.");
} else {
- conn = DriverManager.getConnection("jdbc:sqlite:/"
- + dbFile.getPath());
+ conn = DriverManager.getConnection("jdbc:sqlite:/" + dbFile.getPath());
}
- assertNotNull("Error creating connection",conn);
+ assertNotNull("Error creating connection", conn);
} catch (IOException e) {
System.out.println("Problem creating test file in " + tmp);
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- fail("Exception: " + e.toString());
- } catch (java.lang.Exception e) {
- fail("Exception: " + e.toString());
}
-
}
- public void tearDown() {
- try {
- if (!conn.isClosed()) {
- conn.close();
- }
- } catch (SQLException e) {
- fail("Couldn't close Connection: " + e.getMessage());
+ @Override public void tearDown() throws java.lang.Exception {
+ if (!conn.isClosed()) {
+ conn.close();
}
-
+ super.tearDown();
}
-
}
diff --git a/luni/src/test/java/libcore/sqlite/OldStmtTest.java b/luni/src/test/java/libcore/sqlite/OldStmtTest.java
new file mode 100644
index 0000000..88ade34
--- /dev/null
+++ b/luni/src/test/java/libcore/sqlite/OldStmtTest.java
@@ -0,0 +1,856 @@
+/*
+ * 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 libcore.sqlite;
+
+import SQLite.Constants;
+import SQLite.Database;
+import SQLite.Exception;
+import SQLite.Stmt;
+import SQLite.TableResult;
+import java.sql.Connection;
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+
+public class OldStmtTest extends OldSQLiteTest {
+
+ private static Database db = null;
+ private static Stmt st = null;
+
+ private static final String createAllTypes = "create table type (" +
+
+ " BoolVal BOOLEAN," + " IntVal INT," + " LongVal LONG,"
+ + " Bint BIGINT," + " Tint TINYINT," + " Sint SMALLINT,"
+ + " Mint MEDIUMINT, " +
+
+ " IntegerVal INTEGER, " + " RealVal REAL, "
+ + " DoubleVal DOUBLE, " + " FloatVal FLOAT, "
+ + " DecVal DECIMAL, " +
+
+ " NumVal NUMERIC, " + " charStr CHAR(20), "
+ + " dateVal DATE, " + " timeVal TIME, " + " TS TIMESTAMP, "
+ +
+
+ " DT DATETIME, " + " TBlob TINYBLOB, " + " BlobVal BLOB, "
+ + " MBlob MEDIUMBLOB, " + " LBlob LONGBLOB, " +
+
+ " TText TINYTEXT, " + " TextVal TEXT, "
+ + " MText MEDIUMTEXT, " + " LText LONGTEXT, " +
+
+ " MaxLongVal BIGINT, MinLongVal BIGINT, "+
+
+ " validURL URL, invalidURL URL "+
+
+ ");";
+
+ static final String insertAllTypes =
+ "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
+ + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
+ + "NumVal, charStr, dateVal, timeVal, TS,"
+ + "DT, TBlob, BlobVal, MBlob, LBlob,"
+ + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal,"
+ + " validURL, invalidURL"
+ + ") "
+ + "values (1, -1, 22, 2, 33,"
+ + "3, 1, 2, 3.9, 23.2, 33.3, 44,"
+ + "5, 'test string', '1799-05-26', '12:35:45', '2007-10-09 14:28:02.0',"
+ + "'1221-09-22 10:11:55', 1, 2, 3, 4,"
+ + "'Test text message tiny', 'Test text',"
+ + " 'Test text message medium', 'Test text message long', "
+ + Long.MAX_VALUE+", "+Long.MIN_VALUE+", "
+ + "null, null "+
+ ");";
+
+ static final String allTypesTable = "type";
+
+ @Override public void setUp() throws java.lang.Exception {
+ super.setUp();
+ Support_SQL.loadDriver();
+ db = new Database();
+ db.open(dbFile.getPath(), 0);
+ db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null);
+ DatabaseCreator.fillSimpleTable1(conn);
+
+ }
+
+ @Override public void tearDown() throws java.lang.Exception {
+ if (st != null) {
+ try {
+ st.close();
+ } catch (Exception e) {
+ }
+ }
+ db.close();
+ Connection con = Support_SQL.getConnection();
+ con.close();
+ super.tearDown();
+ }
+
+ public void testStmt() throws Exception {
+ Stmt st = new Stmt();
+ assertNotNull(st);
+ Stmt actual = db.prepare("");
+ assertNotNull(st);
+
+ try {
+ st.step();
+ fail("Cannot execute non prepared Stmt");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testPrepare() throws Exception {
+ try {
+ st = db.prepare("");
+ st.prepare();
+ fail("statement is closed");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ st = new Stmt();
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ assertFalse(st.prepare());
+ st = new Stmt();
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertFalse(st.prepare());
+ st = new Stmt();
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.bind(1, 1);
+ st.bind(2, 10);
+ st.bind(3, 30);
+ assertFalse(st.prepare());
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1
+ + "; " + "delete from " + DatabaseCreator.SIMPLE_TABLE1
+ + " where id = 5; " + "insert into "
+ + DatabaseCreator.SIMPLE_TABLE1 + " values(5, 10, 20); "
+ + "select * from " + DatabaseCreator.SIMPLE_TABLE1 + ";");
+ assertTrue(st.prepare());
+ assertTrue(st.prepare());
+ assertTrue(st.prepare());
+ assertFalse(st.prepare());
+ }
+
+ public void testStep() throws Exception {
+ try {
+ st.step();
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ st = new Stmt();
+ st = db.prepare("select name from sqlite_master where type = 'table'");
+ st.step();
+ }
+
+ public void testClose() throws Exception {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.close();
+
+ try {
+ st.step();
+ fail("Test fails");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+ }
+
+ public void testReset() throws Exception {
+ db.exec("create table TEST (res integer not null)", null);
+
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, 1);
+ st.step();
+
+ // verify that parameter is still bound
+ st.reset();
+ assertEquals(1,st.bind_parameter_count());
+ st.step();
+
+ TableResult count = db.get_table("select count(*) from TEST where res=1", null);
+
+ String[] row0 = (String[]) count.rows.elementAt(0);
+ assertEquals(2, Integer.parseInt(row0[0]));
+ }
+
+ public void testClear_bindings() {
+ try {
+ st.clear_bindings();
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ public void testBindIntInt() throws Exception {
+ int input = 0;
+ int maxVal = Integer.MAX_VALUE;
+ int minVal = Integer.MIN_VALUE;
+
+ db.exec("create table TEST (res integer)", null);
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, input);
+ st.step();
+
+ st.reset();
+ st.bind(1,maxVal);
+ st.step();
+
+ st.reset();
+ st.bind(1,minVal);
+ st.step();
+
+ TableResult r = db.get_table("select * from TEST");
+
+ String[] row0 = (String[]) r.rows.elementAt(0);
+ assertEquals(input,Integer.parseInt(row0[0]));
+
+ String[] row1 = (String[]) r.rows.elementAt(1);
+ assertEquals(maxVal,Integer.parseInt(row1[0]));
+
+ String[] row2 = (String[]) r.rows.elementAt(2);
+ assertEquals(minVal,Integer.parseInt(row2[0]));
+
+ try {
+ st.close();
+ st.bind(1,Integer.MIN_VALUE);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testBindIntLong() throws Exception {
+ long input = 0;
+ long maxVal = Long.MAX_VALUE;
+ long minVal = Long.MIN_VALUE;
+
+ db.exec("create table TEST (res long)", null);
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, input);
+ st.step();
+
+ st.reset();
+ st.bind(1,maxVal);
+ st.step();
+
+ st.reset();
+ st.bind(1,minVal);
+ st.step();
+
+ TableResult r = db.get_table("select * from TEST");
+
+ String[] row0 = (String[]) r.rows.elementAt(0);
+ assertEquals(input,Long.parseLong(row0[0]));
+
+ String[] row1 = (String[]) r.rows.elementAt(1);
+ assertEquals(maxVal,Long.parseLong(row1[0]));
+
+ String[] row2 = (String[]) r.rows.elementAt(2);
+ assertEquals(minVal,Long.parseLong(row2[0]));
+
+ try {
+ st.close();
+ st.bind(1,Long.MIN_VALUE);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testBindIntDouble() throws Exception {
+ double input = 0.0;
+ double maxVal = Double.MAX_VALUE;
+ double minVal = Double.MIN_VALUE;
+ double negInf = Double.NEGATIVE_INFINITY;
+ double posInf = Double.POSITIVE_INFINITY;
+ double nan = Double.NaN;
+
+ db.exec("create table TEST (res double)", null);
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, input);
+ st.step();
+
+ st.reset();
+ st.bind(1, maxVal);
+ st.step();
+
+ st.reset();
+ st.bind(1, minVal);
+ st.step();
+
+ st.reset();
+ st.bind(1, negInf);
+ st.step();
+
+ st.reset();
+ st.bind(1, posInf);
+ st.step();
+
+ st.reset();
+ st.bind(1, nan);
+ st.step();
+
+
+ TableResult r = db.get_table("select * from TEST");
+
+ String[] row0 = (String[]) r.rows.elementAt(0);
+ assertTrue(Double.compare(input, Double.parseDouble(row0[0])) == 0);
+
+ String[] row1 = (String[]) r.rows.elementAt(1);
+ assertFalse(Double.compare(maxVal, Double.parseDouble(row1[0])) == 0);
+ assertTrue(Double.compare(maxVal, Double.parseDouble(row1[0])) < 0);
+ assertTrue(Double.isInfinite(Double.parseDouble(row1[0])));
+
+ String[] row2 = (String[]) r.rows.elementAt(2);
+ assertTrue(Double.compare(minVal, Double.parseDouble(row2[0])) == 0);
+
+ String[] row3 = (String[]) r.rows.elementAt(3);
+ assertEquals("Double.NEGATIVE_INFINITY SQLite representation",
+ "-Inf", row3[0]);
+
+ String[] row4 = (String[]) r.rows.elementAt(4);
+ assertEquals("Double.POSITIVE_INFINITY SQLite representation",
+ "Inf", row4[0]);
+
+ String[] row5 = (String[]) r.rows.elementAt(4);
+ assertEquals("Double.Nan SQLite representation", "Inf", row5[0]);
+
+ try {
+ st.close();
+ st.bind(1,0.0);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testBindIntByteArray() throws Exception {
+ String name = "Hello World";
+ byte[] b = name.getBytes();
+ String stringInHex = "";
+
+ db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
+ st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
+ + " values (:one, :two);");
+ st.bind(1, 2);
+ st.bind(2, b);
+ st.step();
+
+ //compare what was stored with input based on Hex representation
+ // since type of column is CHAR
+ TableResult r = db.get_table("select * from "
+ + DatabaseCreator.PARENT_TABLE);
+ String[] row = (String[]) r.rows.elementAt(0);
+
+ for (byte aByte : b) {
+ stringInHex += Integer.toHexString(aByte);
+ }
+ stringInHex = "X'" + stringInHex + "'";
+ assertTrue(stringInHex.equalsIgnoreCase(row[1]));
+
+ try {
+ st.close();
+ st.bind(1,name.getBytes());
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testBindIntString() throws Exception {
+ String name = "Hello World";
+ db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
+ st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
+ + " values (:one, :two);");
+ st.bind(1, 2);
+ st.bind(2, name);
+ st.step();
+
+ TableResult r = db.get_table("select * from "
+ + DatabaseCreator.PARENT_TABLE);
+ String[] row = (String[]) r.rows.elementAt(0);
+ assertEquals(name,row[1]);
+
+ try {
+ st.close();
+ st.bind(1,name);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testBindInt() throws Exception {
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.bind(4);
+ st.bind(1, 4);
+ st.bind(2, 10);
+ st.bind(3, 30);
+ st.step();
+ fail("Test failes");
+ } catch (Exception e) {
+ // What happens if null is bound to non existing variable position
+ assertEquals("parameter position out of bounds" , e.getMessage());
+ }
+
+ // functional tests
+
+ try {
+ st.reset();
+ st.bind(1);
+ st.bind(2, 10);
+ st.bind(3, 30);
+ st.step();
+ fail("Test failes");
+ } catch (Exception e) {
+ // What happens if null is bound to NON NULL field
+ assertEquals("SQL logic error or missing database", e.getMessage());
+ }
+
+ st.reset();
+ st.bind(1, 3);
+ st.bind(2);
+ st.bind(3, 30);
+ st.step();
+ }
+
+ public void testBind_zeroblob() {
+ try {
+ st.bind_zeroblob(1, 128);
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ public void testBind_parameter_count() throws Exception {
+ try {
+ st.bind_parameter_count();
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(3, st.bind_parameter_count());
+
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (?, ?, ?)");
+ assertEquals(3, st.bind_parameter_count());
+
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ assertEquals(0, st.bind_parameter_count());
+
+ try {
+ st.close();
+ st.bind_parameter_count();
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+
+ }
+
+ public void testBind_parameter_name() {
+ try {
+ st.bind_parameter_name(1);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(":one", st.bind_parameter_name(1));
+ assertEquals(":two", st.bind_parameter_name(2));
+ assertEquals(":three", st.bind_parameter_name(3));
+ st.bind_parameter_name(4);
+ fail();
+ } catch (Exception e) {
+ assertEquals("parameter position out of bounds",e.getMessage());
+ }
+ }
+
+ public void testBind_parameter_index() throws Exception {
+ try {
+ st.bind_parameter_index("");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(3, st.bind_parameter_index(":three"));
+
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(0, st.bind_parameter_index(":t"));
+
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (?, ?, ?)");
+ assertEquals(0, st.bind_parameter_index("?"));
+ }
+
+ public void testColumn_int() throws Exception {
+ db.exec(createAllTypes, null);
+ db.exec(insertAllTypes, null);
+
+ int columnObjectCastFromLong;
+ Object columnObject = null;
+ int intColumn = 0;
+ String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+
+ st = db.prepare(selectStmt);
+ st.step();
+ // select 'speed' value
+ columnObject = st.column(1);
+ intColumn = st.column_int(1);
+ assertNotNull(intColumn);
+
+ assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
+ int stSpeed = Integer.parseInt(columnObject.toString());
+ assertNotNull(stSpeed);
+ assertEquals( intColumn, stSpeed);
+ assertEquals(10,stSpeed);
+
+ selectStmt = "select TextVal from "+allTypesTable;
+
+ st = db.prepare(selectStmt);
+ st.step();
+ // select double value
+ try {
+ st.column_int(0);
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testColumn_long() throws Exception {
+ Object columnObject = null;
+ int columnObjectCastFromLong;
+ long longColumn = 0;
+ String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+ st = db.prepare(selectStmt);
+ st.step();
+ columnObject = st.column(1);
+ longColumn = st.column_long(1);
+ assertNotNull(longColumn);
+ // column declared as integer
+ assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
+ int stSpeed = Integer.parseInt(columnObject.toString());
+ assertNotNull(stSpeed);
+ assertEquals( longColumn, stSpeed);
+
+ try {
+ st.column_long(4);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+
+ try {
+ st.column_long(-1);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+ }
+
+ public void testColumn_double() throws Exception {
+ db.exec(createAllTypes, null);
+ db.exec(insertAllTypes, null);
+
+ Object columnObject = null;
+ double doubleColumn = 0;
+ double actualVal = 23.2;
+ String selectStmt = "select DoubleVal from "+allTypesTable;
+
+ st = db.prepare(selectStmt);
+ st.step();
+ // select double value
+ doubleColumn = st.column_double(0);
+ assertNotNull(doubleColumn);
+
+ assertTrue("DOUBLE".equalsIgnoreCase(st.column_decltype(0)));
+ assertNotNull(doubleColumn);
+ assertEquals( actualVal, doubleColumn);
+
+ // Exception test
+ selectStmt = "select dateVal from "+allTypesTable;
+
+ st = db.prepare(selectStmt);
+ st.step();
+ // select double value
+ try {
+ st.column_double(0);
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testColumn_bytes() throws Exception {
+ db.exec("create table B(id integer primary key, val blob)",null);
+ db.exec("insert into B values(1, zeroblob(128))", null);
+ st = db.prepare("select val from B where id = 1");
+ assertTrue(st.step());
+ try {
+ st.column_bytes(0);
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ public void testColumn_string() throws Exception {
+ db.exec(createAllTypes, null);
+ db.exec(insertAllTypes, null);
+
+ Object columnObject = null;
+ String stringColumn = "";
+ String actualVal = "test string";
+ String selectStmt = "select charStr from "+allTypesTable;
+
+ st = db.prepare(selectStmt);
+ st.step();
+ // select string value
+ stringColumn = st.column_string(0);
+ assertNotNull(stringColumn);
+
+ assertTrue("CHAR(20)".equalsIgnoreCase(st.column_decltype(0)));
+ assertNotNull(stringColumn);
+ assertEquals( actualVal, stringColumn);
+
+ // Exception test
+ selectStmt = "select DoubleVal from "+allTypesTable;
+
+ st = db.prepare(selectStmt);
+ st.step();
+ // select double value
+ try {
+ st.column_string(0);
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ public void testColumn_type() throws Exception {
+ db.exec(createAllTypes, null);
+ db.exec(insertAllTypes, null);
+ st = db.prepare("select * from " + allTypesTable);
+ st.step();
+
+ // Exception test
+ try {
+ st.column_type(100);
+ } catch (Exception e) {
+ // ok
+ }
+
+ /*
+ Dictionary
+
+ public static final int SQLITE_INTEGER = 1;
+ public static final int SQLITE_FLOAT = 2;
+ public static final int SQLITE_BLOB = 4;
+ public static final int SQLITE_NULL = 5;
+ public static final int SQLITE3_TEXT = 3;
+ public static final int SQLITE_NUMERIC = -1;
+ */
+
+ assertEquals(Constants.SQLITE3_TEXT, st.column_type(23)); // ok TEXT
+ assertEquals(Constants.SQLITE3_TEXT, st.column_type(13)); // CHAR(20)
+
+ assertEquals(Constants.SQLITE_FLOAT, st.column_type(8));
+ assertEquals(Constants.SQLITE_FLOAT, st.column_type(9));
+ assertEquals(Constants.SQLITE_FLOAT, st.column_type(10)); // FLOAT
+
+ for (int i = 0; i < 8; i++) {
+ assertEquals("Expected Integer at position " + i,
+ Constants.SQLITE_INTEGER, st.column_type(i));
+ }
+
+ assertEquals(Constants.SQLITE_NULL, st.column_type(28));
+ assertEquals(Constants.SQLITE_NULL, st.column_type(29));
+
+ // Failing tests
+ assertTrue("INTEGER".equalsIgnoreCase(st.column_decltype(12)));
+ assertEquals(Constants.SQLITE_INTEGER, st.column_type(12));
+
+ assertTrue("FLOAT".equalsIgnoreCase(st.column_decltype(11)));
+ assertEquals(Constants.SQLITE_FLOAT, st.column_type(11)); // FLOAT ->
+ // got INTEGER
+ assertTrue("BLOB".equalsIgnoreCase(st.column_decltype(19)));
+ assertEquals(Constants.SQLITE_BLOB, st.column_type(19)); // Blob got
+ // INTEGER
+
+ }
+
+ /**
+ * Wrong value is returned in case of a prepared statement to which a '*' bound
+ */
+ public void testColumn_count() throws Exception {
+ String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+ st = db.prepare(selectStmt);
+
+ assertEquals(3, st.column_count());
+
+ st.step();
+ int columnCount = st.column_count();
+ assertNotNull(columnCount);
+ assertEquals( 3, columnCount);
+
+ // actual prepared statement
+ selectStmt = "select ? from "+DatabaseCreator.SIMPLE_TABLE1;
+ st = db.prepare(selectStmt);
+
+ assertEquals(3, st.column_count());
+
+ st.bind(1, "*");
+ st.step();
+ columnCount = st.column_count();
+ assertNotNull(columnCount);
+ assertEquals( 3, columnCount);
+ }
+
+ public void testColumn() throws Exception {
+ Object columnObject = null;
+ int columnObjectCastFromLong;
+ int intColumn = 0;
+ String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+ TableResult res = db.get_table(selectStmt);
+ st = db.prepare(selectStmt);
+ st.step();
+ columnObject = st.column(1);
+ intColumn = st.column_int(1);
+ assertNotNull(intColumn);
+ assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
+ int stSpeed = Integer.parseInt(columnObject.toString());
+ assertNotNull(stSpeed);
+ assertEquals( intColumn, stSpeed);
+
+ try {
+ assertNotNull(columnObject);
+ int dummy = ((Integer) columnObject).intValue();
+ fail("Cast to Integer should fail");
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ st.column(4);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+
+ try {
+ st.column(-1);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+ }
+
+ public void testColumn_table_name() {
+ try {
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ st.column_table_name(1);
+ fail("Function is now supported.");
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ public void testColumn_database_name() {
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.column_database_name(1);
+ fail("Function is now supported.");
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ public void testColumn_decltype() throws Exception {
+ db.exec(createAllTypes, null);
+ db.exec(insertAllTypes, null);
+ st = db.prepare("select * from " + allTypesTable);
+ st.step();
+
+ // Exception test
+ try {
+ st.column_decltype(100);
+ } catch (Exception e) {
+ // ok
+ }
+
+ assertTrue(st.column_decltype(0), "BOOLEAN".equalsIgnoreCase(st
+ .column_decltype(0)));
+ assertTrue(st.column_decltype(1), "INT".equalsIgnoreCase(st
+ .column_decltype(1)));
+ assertTrue(st.column_decltype(2), "LONG".equalsIgnoreCase(st
+ .column_decltype(2)));
+ assertTrue(st.column_decltype(3), "BIGINT".equalsIgnoreCase(st
+ .column_decltype(3)));
+ assertTrue(st.column_decltype(4), "TINYINT".equalsIgnoreCase(st
+ .column_decltype(4)));
+ assertTrue(st.column_decltype(5), "SMALLINT".equalsIgnoreCase(st
+ .column_decltype(5)));
+ assertTrue(st.column_decltype(6), "MEDIUMINT".equalsIgnoreCase(st
+ .column_decltype(6)));
+ assertTrue(st.column_decltype(7), "INTEGER".equalsIgnoreCase(st
+ .column_decltype(7)));
+ assertTrue(st.column_decltype(8), "REAL".equalsIgnoreCase(st
+ .column_decltype(8)));
+ assertTrue(st.column_decltype(9), "DOUBLE".equalsIgnoreCase(st
+ .column_decltype(9)));
+ assertTrue(st.column_decltype(10), "FLOAT".equalsIgnoreCase(st
+ .column_decltype(10)));
+ assertTrue(st.column_decltype(11), "DECIMAL".equalsIgnoreCase(st
+ .column_decltype(11)));
+ assertTrue(st.column_decltype(12), "NUMERIC".equalsIgnoreCase(st
+ .column_decltype(12)));
+ assertTrue(st.column_decltype(13), "CHAR(20)".equalsIgnoreCase(st
+ .column_decltype(13)));
+
+ assertTrue(st.column_decltype(19), "BLOB".equalsIgnoreCase(st
+ .column_decltype(19)));
+
+ assertTrue(st.column_decltype(23), "TEXT".equalsIgnoreCase(st
+ .column_decltype(23)));
+ assertTrue(st.column_decltype(28), "URL".equalsIgnoreCase(st
+ .column_decltype(28)));
+ assertTrue(st.column_decltype(29), "URL".equalsIgnoreCase(st
+ .column_decltype(29)));
+ }
+
+ public void testColumn_origin_name() {
+ try {
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ st.column_origin_name(1);
+ fail("Function is now supported.");
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/xml/ExpatPullParserDtdTest.java b/luni/src/test/java/libcore/xml/ExpatPullParserDtdTest.java
deleted file mode 100644
index 5e62310..0000000
--- a/luni/src/test/java/libcore/xml/ExpatPullParserDtdTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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.xml;
-
-import org.apache.harmony.xml.ExpatPullParser;
-import org.xmlpull.v1.XmlPullParser;
-
-public class ExpatPullParserDtdTest extends PullParserDtdTest {
- @Override XmlPullParser newPullParser() {
- return new ExpatPullParser();
- }
-}
diff --git a/luni/src/test/java/libcore/xml/ExpatPullParserTest.java b/luni/src/test/java/libcore/xml/ExpatPullParserTest.java
deleted file mode 100644
index 5d1725d..0000000
--- a/luni/src/test/java/libcore/xml/ExpatPullParserTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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.xml;
-
-import org.apache.harmony.xml.ExpatPullParser;
-import org.xmlpull.v1.XmlPullParser;
-
-public final class ExpatPullParserTest extends PullParserTest {
-
- @Override XmlPullParser newPullParser() {
- return new ExpatPullParser();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/CipherTest.java b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/CipherTest.java
index f5a99c7..0507147 100644
--- a/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/CipherTest.java
+++ b/luni/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/CipherTest.java
@@ -17,15 +17,6 @@
package org.apache.harmony.crypto.tests.javax.crypto;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import org.apache.harmony.crypto.tests.support.MyCipher;
-
-import tests.support.resource.Support_Resources;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -50,7 +41,6 @@
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.RSAKeyGenParameterSpec;
import java.util.Arrays;
-
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherSpi;
@@ -61,8 +51,9 @@
import javax.crypto.ShortBufferException;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
+import org.apache.harmony.crypto.tests.support.MyCipher;
+import tests.support.resource.Support_Resources;
-@TestTargetClass(Cipher.class)
public class CipherTest extends junit.framework.TestCase {
static Key cipherKey;
@@ -92,69 +83,23 @@
}
/**
- * @tests javax.crypto.Cipher#getInstance(java.lang.String)
+ * javax.crypto.Cipher#getInstance(java.lang.String)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineSetMode",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineSetPadding",
- args = {java.lang.String.class}
- )
- })
public void test_getInstanceLjava_lang_String() throws Exception {
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
assertNotNull("Received a null Cipher instance", cipher);
try {
Cipher.getInstance("WrongAlgorithmName");
- fail("NoSuchAlgorithmException expected");
- } catch (NoSuchAlgorithmException e) {
- //expected
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
-// RI throws NoSuchAlgorithmException for wrong padding.
}
/**
- * @tests javax.crypto.Cipher#getInstance(java.lang.String,
+ * javax.crypto.Cipher#getInstance(java.lang.String,
* java.lang.String)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineSetMode",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineSetPadding",
- args = {java.lang.String.class}
- )
- })
public void test_getInstanceLjava_lang_StringLjava_lang_String()
throws Exception {
@@ -166,61 +111,31 @@
Cipher cipher = Cipher.getInstance("DES", providers[i].getName());
assertNotNull("Cipher.getInstance() returned a null value", cipher);
- // Exception case
try {
cipher = Cipher.getInstance("DoBeDoBeDo", providers[i]);
- fail("Should have thrown an NoSuchAlgorithmException");
- } catch (NoSuchAlgorithmException e) {
- // Expected
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
}
- // Exception case
try {
Cipher.getInstance("DES", (String) null);
- fail("Should have thrown an IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
+ fail();
+ } catch (IllegalArgumentException expected) {
}
- // Exception case
try {
Cipher.getInstance("DES", "IHaveNotBeenConfigured");
- fail("Should have thrown an NoSuchProviderException");
- } catch (NoSuchProviderException e) {
- // Expected
+ fail();
+ } catch (NoSuchProviderException expected) {
}
-// RI throws NoSuchAlgorithmException for wrong padding.
}
/**
- * @tests javax.crypto.Cipher#getInstance(java.lang.String,
+ * javax.crypto.Cipher#getInstance(java.lang.String,
* java.security.Provider)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineSetMode",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineSetPadding",
- args = {java.lang.String.class}
- )
- })
- public void test_getInstanceLjava_lang_StringLjava_security_Provider()
- throws Exception {
+ public void test_getInstanceLjava_lang_StringLjava_security_Provider() throws Exception {
Provider[] providers = Security.getProviders("Cipher.DES");
@@ -231,33 +146,22 @@
assertNotNull("Cipher.getInstance() returned a null value", cipher);
}
- // Exception case
try {
Cipher.getInstance("DES", (Provider) null);
- fail("Should have thrown an IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
+ fail();
+ } catch (IllegalArgumentException expected) {
}
- // Exception case
try {
Cipher.getInstance("WrongAlg", providers[0]);
- fail("NoSuchAlgorithmException expected");
- } catch (NoSuchAlgorithmException e) {
- // Expected
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
-// RI throws NoSuchAlgorithmException for wrong padding.
}
/**
- * @tests javax.crypto.Cipher#getProvider()
+ * javax.crypto.Cipher#getProvider()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProvider",
- args = {}
- )
public void test_getProvider() throws Exception {
Provider[] providers = Security.getProviders("Cipher.AES");
@@ -275,14 +179,8 @@
}
/**
- * @tests javax.crypto.Cipher#getAlgorithm()
+ * javax.crypto.Cipher#getAlgorithm()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAlgorithm",
- args = {}
- )
public void test_getAlgorithm() throws Exception {
final String algorithm = "DESede/CBC/PKCS5Padding";
@@ -292,23 +190,8 @@
}
/**
- * @tests javax.crypto.Cipher#getBlockSize()
+ * javax.crypto.Cipher#getBlockSize()
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBlockSize",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineGetBlockSize",
- args = {}
- )
- })
public void test_getBlockSize() throws Exception {
final String algorithm = "DESede/CBC/PKCS5Padding";
@@ -317,23 +200,8 @@
}
/**
- * @tests javax.crypto.Cipher#getOutputSize(int)
+ * javax.crypto.Cipher#getOutputSize(int)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOutputSize",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineGetOutputSize",
- args = {int.class}
- )
- })
public void test_getOutputSizeI() throws Exception {
SecureRandom sr = new SecureRandom();
@@ -341,9 +209,8 @@
try {
cipher.getOutputSize(25);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, sr);
@@ -358,15 +225,9 @@
}
/**
- * @tests javax.crypto.Cipher#init(int, java.security.Key)
+ * javax.crypto.Cipher#init(int, java.security.Key)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.Key.class}
- )
- public void test_initILjava_security_Key() throws Exception {
+ public void test_initWithKey() throws Exception {
Cipher cipher = Cipher.getInstance(algorithm + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
@@ -374,33 +235,16 @@
cipher = Cipher.getInstance("DES/CBC/NoPadding");
try {
cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
}
/**
- * @tests javax.crypto.Cipher#init(int, java.security.Key,
+ * javax.crypto.Cipher#init(int, java.security.Key,
* java.security.SecureRandom)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.Key.class, java.security.SecureRandom.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineInit",
- args = {int.class, java.security.Key.class, java.security.SecureRandom.class}
- )
- })
- public void test_initILjava_security_KeyLjava_security_SecureRandom()
- throws Exception {
+ public void test_initWithSecureRandom() throws Exception {
SecureRandom sr = new SecureRandom();
Cipher cipher = Cipher.getInstance(algorithm + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, sr);
@@ -408,24 +252,16 @@
cipher = Cipher.getInstance("DES/CBC/NoPadding");
try {
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, sr);
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
}
/**
- * @tests javax.crypto.Cipher#init(int, java.security.Key,
+ * javax.crypto.Cipher#init(int, java.security.Key,
* java.security.spec.AlgorithmParameterSpec)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.Key.class, java.security.spec.AlgorithmParameterSpec.class}
- )
- public void test_initILjava_security_KeyLjava_security_spec_AlgorithmParameterSpec()
- throws Exception {
+ public void test_initWithAlgorithmParameterSpec() throws Exception {
SecureRandom sr = new SecureRandom();
Cipher cipher = null;
@@ -447,9 +283,8 @@
cipher = Cipher.getInstance("DES/CBC/NoPadding");
try {
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap);
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
cipher = Cipher.getInstance("DES/CBC/NoPadding");
@@ -457,34 +292,17 @@
try {
cipher.init(Cipher.ENCRYPT_MODE, cipherKeyDES, ap);
- fail("InvalidAlgorithmParameterException expected");
- } catch (InvalidAlgorithmParameterException e) {
- //expected
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
}
}
/**
- * @tests javax.crypto.Cipher#init(int, java.security.Key,
+ * javax.crypto.Cipher#init(int, java.security.Key,
* java.security.spec.AlgorithmParameterSpec,
* java.security.SecureRandom)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.Key.class, java.security.spec.AlgorithmParameterSpec.class, java.security.SecureRandom.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineInit",
- args = {int.class, java.security.Key.class, java.security.spec.AlgorithmParameterSpec.class, java.security.SecureRandom.class}
- )
- })
- public void test_initILjava_security_KeyLjava_security_spec_AlgorithmParameterSpecLjava_security_SecureRandom()
- throws Exception {
+ public void test_initWithKeyAlgorithmParameterSpecSecureRandom() throws Exception {
SecureRandom sr = new SecureRandom();
Cipher cipher = null;
@@ -505,9 +323,8 @@
cipher = Cipher.getInstance("DES/CBC/NoPadding");
try {
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap, sr);
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
cipher = Cipher.getInstance("DES/CBC/NoPadding");
@@ -515,30 +332,14 @@
try {
cipher.init(Cipher.ENCRYPT_MODE, cipherKeyDES, ap, sr);
- fail("InvalidAlgorithmParameterException expected");
- } catch (InvalidAlgorithmParameterException e) {
- //expected
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
}
}
/**
- * @tests javax.crypto.Cipher#update(byte[], int, int)
+ * javax.crypto.Cipher#update(byte[], int, int)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineUpdate",
- args = {byte[].class, int.class, int.class}
- )
- })
public void test_update$BII() throws Exception {
for (int index = 1; index < 4; index++) {
Cipher c = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
@@ -584,26 +385,19 @@
+ index + ".plaintext");
assertTrue("Operation produced incorrect results", Arrays.equals(
plaintextBytes, decipheredCipherText));
- }// end for
+ }
Cipher cipher = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
try {
cipher.update(new byte[64], 0, 32);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
}
/**
- * @tests javax.crypto.Cipher#doFinal()
+ * javax.crypto.Cipher#doFinal()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {}
- )
public void test_doFinal() throws Exception {
for (int index = 1; index < 4; index++) {
Cipher c = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
@@ -647,7 +441,7 @@
+ ".ciphertext");
assertTrue("Operation produced incorrect results", Arrays.equals(
encryptedPlaintext, cipherText));
- }// end for
+ }
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
byte[] b1 = new byte[30];
@@ -657,17 +451,15 @@
c.update(b, 0, 10, b1, 5);
try {
c.doFinal();
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -685,46 +477,26 @@
c.update(b1, 0, 24, b, 0);
try {
c.doFinal();
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
}
- private byte[] loadBytes(String resPath) {
- try {
- File resources = Support_Resources.createTempFolder();
- Support_Resources.copyFile(resources, null, resPath);
- InputStream is = Support_Resources.getStream(resPath);
+ private byte[] loadBytes(String resPath) throws Exception {
+ File resources = Support_Resources.createTempFolder();
+ Support_Resources.copyFile(resources, null, resPath);
+ InputStream is = Support_Resources.getStream(resPath);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buff = new byte[1024];
- int readlen;
- while ((readlen = is.read(buff)) > 0) {
- out.write(buff, 0, readlen);
- }
- is.close();
- return out.toByteArray();
- } catch (IOException e) {
- return null;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buff = new byte[1024];
+ int readlen;
+ while ((readlen = is.read(buff)) > 0) {
+ out.write(buff, 0, readlen);
}
+ is.close();
+ return out.toByteArray();
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineGetParameters",
- args = {}
- )
- })
public void testGetParameters() throws Exception {
Cipher c = Cipher.getInstance("DES");
assertNull(c.getParameters());
@@ -733,21 +505,6 @@
/*
* Class under test for int update(byte[], int, int, byte[], int)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class, int.class, int.class, byte[].class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineUpdate",
- args = {byte[].class, int.class, int.class, byte[].class, int.class}
- )
- })
public void testUpdatebyteArrayintintbyteArrayint() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10};
byte[] b1 = new byte[6];
@@ -755,17 +512,15 @@
try {
c.update(b, 0, 10, b1, 5);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c.init(Cipher.ENCRYPT_MODE, cipherKey);
try {
c.update(b, 0, 10, b1, 5);
- fail("ShortBufferException expected");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
b1 = new byte[30];
@@ -775,21 +530,6 @@
/*
* Class under test for int doFinal(byte[], int, int, byte[], int)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {byte[].class, int.class, int.class, byte[].class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineDoFinal",
- args = {byte[].class, int.class, int.class, byte[].class, int.class}
- )
- })
public void testDoFinalbyteArrayintintbyteArrayint() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
byte[] b1 = new byte[30];
@@ -798,17 +538,15 @@
c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
try {
c.doFinal(b, 0, 10, b1, 5);
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal(b, 0, 10, b1, 5);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -825,9 +563,8 @@
try {
c.doFinal(b1, 0, 24, new byte[42], 0);
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
b1 = new byte[6];
@@ -835,117 +572,80 @@
c.init(Cipher.ENCRYPT_MODE, cipherKey);
try {
c.doFinal(b, 3, 6, b1, 5);
- fail("No expected ShortBufferException");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMaxAllowedKeyLength",
- args = {java.lang.String.class}
- )
- public void testGetMaxAllowedKeyLength() throws NoSuchAlgorithmException {
+ public void testGetMaxAllowedKeyLength() throws Exception {
try {
Cipher.getMaxAllowedKeyLength(null);
- fail("No expected NullPointerException");
- } catch (NullPointerException e) {
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ Cipher.getMaxAllowedKeyLength("");
+ } catch (NoSuchAlgorithmException expected) {
}
try {
Cipher.getMaxAllowedKeyLength("//CBC/PKCS5Paddin");
- fail("No expected NoSuchAlgorithmException");
- } catch (NoSuchAlgorithmException e) {
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
try {
Cipher.getMaxAllowedKeyLength("/DES/CBC/PKCS5Paddin/1");
- fail("No expected NoSuchAlgorithmException");
- } catch (NoSuchAlgorithmException e) {
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
assertTrue(Cipher.getMaxAllowedKeyLength("/DES/CBC/PKCS5Paddin") > 0);
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMaxAllowedParameterSpec",
- args = {java.lang.String.class}
- )
- public void testGetMaxAllowedParameterSpec()
- throws NoSuchAlgorithmException, Exception {
+ public void testGetMaxAllowedParameterSpec() throws Exception {
try {
Cipher.getMaxAllowedParameterSpec(null);
- fail("No expected NullPointerException");
- } catch (NullPointerException e) {
+ fail();
+ } catch (NullPointerException expected) {
}
try {
Cipher.getMaxAllowedParameterSpec("/DES//PKCS5Paddin");
- fail("No expected NoSuchAlgorithmException");
- } catch (NoSuchAlgorithmException e) {
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
try {
Cipher.getMaxAllowedParameterSpec("/DES/CBC/ /1");
- fail("No expected NoSuchAlgorithmException");
- } catch (NoSuchAlgorithmException e) {
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
Cipher.getMaxAllowedParameterSpec("DES/CBC/PKCS5Paddin");
Cipher.getMaxAllowedParameterSpec("RSA");
}
/**
- * @tests javax.crypto.Cipher#Cipher(CipherSpi cipherSpi, Provider provider,
+ * javax.crypto.Cipher#Cipher(CipherSpi cipherSpi, Provider provider,
* String transformation)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Cipher",
- args = {javax.crypto.CipherSpi.class, java.security.Provider.class, java.lang.String.class}
- )
public void test_Ctor() throws Exception {
// Regression for Harmony-1184
try {
new testCipher(null, null, "s");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // expected
+ fail();
+ } catch (NullPointerException expected) {
}
try {
new testCipher(new MyCipher(), null, "s");
fail("NullPointerException expected for 'null' provider");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
try {
new testCipher(null, new Provider("qwerty", 1.0, "qwerty") {}, "s");
fail("NullPointerException expected for 'null' cipherSpi");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineDoFinal",
- args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
- )
- })
- public void test_doFinalLjava_nio_ByteBufferLjava_nio_ByteBuffer ()
- throws NoSuchAlgorithmException, NoSuchPaddingException,
- InvalidKeyException, ShortBufferException, BadPaddingException,
- IllegalBlockSizeException, InvalidAlgorithmParameterException {
+ public void test_doFinalLjava_nio_ByteBufferLjava_nio_ByteBuffer() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
ByteBuffer bInput = ByteBuffer.allocate(64);
ByteBuffer bOutput = ByteBuffer.allocate(64);
@@ -955,17 +655,15 @@
bInput.put(b, 0, 10);
try {
c.doFinal(bInput, bOutput);
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal(bInput, bOutput);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -985,9 +683,8 @@
try {
c.doFinal(bOutput, bInput);
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -995,9 +692,8 @@
bInput.put(b, 0, 16);
try {
c.doFinal(bInput, bInput);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
+ fail();
+ } catch (IllegalArgumentException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1005,9 +701,8 @@
bInput.put(b, 0, 16);
try {
c.doFinal(bInput, bOutput.asReadOnlyBuffer());
- fail("ReadOnlyBufferException expected");
- } catch (ReadOnlyBufferException e) {
- //expected
+ fail();
+ } catch (ReadOnlyBufferException expected) {
}
bInput.rewind();
@@ -1017,21 +712,12 @@
c.init(Cipher.ENCRYPT_MODE, cipherKey);
try {
c.doFinal(bInput, bOutput);
- fail("No expected ShortBufferException");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.Key.class, java.security.AlgorithmParameters.class}
- )
- public void test_initILjava_security_KeyLjava_security_AlgorithmParameters ()
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
- InvalidAlgorithmParameterException {
+ public void test_initWithKeyAlgorithmParameters() throws Exception {
SecureRandom sr = new SecureRandom();
byte[] iv = new byte[8];
sr.nextBytes(iv);
@@ -1043,37 +729,18 @@
try {
c.init(Cipher.DECRYPT_MODE, cipherKey, ap);
- fail("InvalidKeyException e");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, cipherKeyDES, (AlgorithmParameters)null);
- fail("InvalidAlgorithmParameterException e");
- } catch (InvalidAlgorithmParameterException e) {
- //expected
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.Key.class, java.security.AlgorithmParameters.class, java.security.SecureRandom.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineInit",
- args = {int.class, java.security.Key.class, java.security.AlgorithmParameters.class, java.security.SecureRandom.class}
- )
- })
- public void test_initILjava_security_KeyLjava_security_AlgorithmParametersLjava_security_SecureRandom ()
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
- InvalidAlgorithmParameterException {
+ public void test_initWithKeyAlgorithmParametersSecureRandom() throws Exception {
SecureRandom sr = new SecureRandom();
byte[] iv = new byte[8];
sr.nextBytes(iv);
@@ -1085,31 +752,21 @@
try {
c.init(Cipher.DECRYPT_MODE, cipherKey, ap, new SecureRandom());
- fail("InvalidKeyException e");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, cipherKeyDES, (AlgorithmParameters)null, sr);
- fail("InvalidAlgorithmParameterException e");
- } catch (InvalidAlgorithmParameterException e) {
- //expected
+ fail();
+ } catch (InvalidAlgorithmParameterException expected) {
}
c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap, (SecureRandom)null);
assertNotNull(c.getParameters());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.cert.Certificate.class}
- )
- public void test_initILjava_security_cert_Certificate ()
- throws MalformedURLException, IOException, CertificateException,
- NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
+ public void test_initWithCertificate() throws Exception {
/* Certificate creation notes: certificate should be valid 37273 starting
* from 13 Nov 2008
@@ -1126,6 +783,7 @@
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
+ is.close();
Cipher c = Cipher.getInstance("RSA");
@@ -1133,21 +791,12 @@
c = Cipher.getInstance("DES/CBC/PKCS5Padding");
try {
c.init(Cipher.ENCRYPT_MODE, cert);
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {int.class, java.security.cert.Certificate.class, java.security.SecureRandom.class}
- )
- public void test_initILjava_security_cert_Certificate_java_security_SecureRandom ()
- throws MalformedURLException, IOException, CertificateException,
- NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
+ public void test_initWithCertificateSecureRandom() throws Exception {
/* Certificate creation notes: certificate should be valid 37273 starting
* from 13 Nov 2008
@@ -1164,6 +813,7 @@
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
+ is.close();
Cipher c = Cipher.getInstance("RSA");
@@ -1171,30 +821,12 @@
c = Cipher.getInstance("DES/CBC/PKCS5Padding");
try {
c.init(Cipher.ENCRYPT_MODE, cert, new SecureRandom());
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unwrap",
- args = {byte[].class, java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineUnwrap",
- args = {byte[].class, java.lang.String.class, int.class}
- )
- })
- public void test_unwrap$BLjava_lang_StringI () throws NoSuchAlgorithmException,
- NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
- IllegalBlockSizeException {
+ public void test_unwrap$BLjava_lang_StringI() throws Exception {
SecureRandom sr = new SecureRandom();
byte[] iv = new byte[8];
sr.nextBytes(iv);
@@ -1208,9 +840,8 @@
try {
c.unwrap(arDES, "DES", Cipher.SECRET_KEY);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c.init(Cipher.UNWRAP_MODE, cipherKeyDES, ap, sr);
@@ -1219,39 +850,20 @@
try {
c.unwrap(arDES, "RSA38", Cipher.PUBLIC_KEY);
- fail("NoSuchAlgorithmException expected");
- } catch (NoSuchAlgorithmException e) {
- //expected
+ fail();
+ } catch (NoSuchAlgorithmException expected) {
}
c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
c.init(Cipher.UNWRAP_MODE, cipherKey, ap, sr);
try {
c.unwrap(arDES, "DESede", Cipher.SECRET_KEY);
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineUpdate",
- args = {java.nio.ByteBuffer.class, java.nio.ByteBuffer.class}
- )
- })
- public void test_updateLjava_nio_ByteBufferLjava_nio_ByteBuffer () throws
- NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
- ShortBufferException, InvalidAlgorithmParameterException {
+ public void test_updateLjava_nio_ByteBufferLjava_nio_ByteBuffer() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
ByteBuffer bInput = ByteBuffer.allocate(256);
ByteBuffer bOutput = ByteBuffer.allocate(256);
@@ -1266,9 +878,8 @@
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.update(bInput, bOutput);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1294,9 +905,8 @@
bInput.rewind();
try {
c.update(bInput, bInput);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
+ fail();
+ } catch (IllegalArgumentException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1306,9 +916,8 @@
bOutput.rewind();
try {
c.update(bInput, bOutput.asReadOnlyBuffer());
- fail("ReadOnlyBufferException expected");
- } catch (ReadOnlyBufferException e) {
- //expected
+ fail();
+ } catch (ReadOnlyBufferException expected) {
}
bInput.rewind();
@@ -1319,9 +928,8 @@
c.init(Cipher.ENCRYPT_MODE, cipherKey);
try {
c.update(bInput, bOutput);
- fail("No expected ShortBufferException");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
}
@@ -1340,25 +948,7 @@
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "wrap",
- args = {java.security.Key.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineWrap",
- args = {java.security.Key.class}
- )
- })
- public void test_wrap_java_security_Key () throws NoSuchAlgorithmException,
- NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
- InvalidAlgorithmParameterException, MalformedURLException, IOException,
- CertificateException {
+ public void test_wrap_java_security_Key() throws Exception {
SecureRandom sr = new SecureRandom();
byte[] iv = new byte[8];
sr.nextBytes(iv);
@@ -1380,35 +970,26 @@
c.init(Cipher.WRAP_MODE, cipherKeyDES, ap, sr);
try {
assertNotNull(c.wrap(cert.getPublicKey()));
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap, sr);
try {
c.wrap(cipherKeyDES);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c.init(Cipher.WRAP_MODE, cipherKeyDES, ap, sr);
try {
c.wrap(new Mock_Key());
- fail("InvalidKeyException expected");
- } catch (InvalidKeyException e) {
- //expected
+ fail();
+ } catch (InvalidKeyException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {byte[].class, int.class}
- )
public void test_doFinal$BI() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
byte[] b1 = new byte[30];
@@ -1418,17 +999,15 @@
c.update(b, 0, 10);
try {
c.doFinal(b1, 5);
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal(b1, 5);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1447,9 +1026,8 @@
c.update(b1, 0, 24);
try {
c.doFinal(b, 0);
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
b1 = new byte[6];
@@ -1458,18 +1036,11 @@
c.update(b, 3, 6);
try {
c.doFinal(b1, 5);
- fail("No expected ShortBufferException");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {byte[].class}
- )
public void test_doFinal$B() throws Exception {
byte[] b1 = new byte[32];
byte[] bI1 = {1,2,3,4,5,6,7,8,9,10};
@@ -1481,17 +1052,15 @@
c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
try {
c.doFinal(bI1);
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal(bI1);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1510,27 +1079,11 @@
try {
c.doFinal(b1);
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {byte[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = CipherSpi.class,
- method = "engineDoFinal",
- args = {byte[].class, int.class, int.class}
- )
- })
public void test_doFinal$BII() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
byte[] b1 = new byte[30];
@@ -1539,17 +1092,15 @@
c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
try {
c.doFinal(b, 0, 10);
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal(b, 0, 10);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1568,18 +1119,11 @@
try {
c.doFinal(b1, 0, 24);
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doFinal",
- args = {byte[].class, int.class, int.class, byte[].class}
- )
public void test_doFinal$BII$B() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
byte[] b1 = new byte[30];
@@ -1588,17 +1132,15 @@
c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
try {
c.doFinal(b, 0, 10, b1);
- fail("IllegalBlockSizeException expected");
- } catch (IllegalBlockSizeException e) {
- //expected
+ fail();
+ } catch (IllegalBlockSizeException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
try {
c.doFinal(b, 0, 10, b1);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1615,9 +1157,8 @@
try {
c.doFinal(b1, 0, 24, new byte[42]);
- fail("BadPaddingException expected");
- } catch (BadPaddingException e) {
- //expected
+ fail();
+ } catch (BadPaddingException expected) {
}
b1 = new byte[6];
@@ -1625,34 +1166,20 @@
c.init(Cipher.ENCRYPT_MODE, cipherKey);
try {
c.doFinal(b, 3, 6, b1);
- fail("No expected ShortBufferException");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks exception",
- method = "update",
- args = {byte[].class}
- )
public void test_update$B() throws Exception {
Cipher cipher = Cipher.getInstance("DESEDE/CBC/PKCS5Padding");
try {
cipher.update(new byte[64]);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class, int.class, int.class, byte[].class}
- )
public void test_() throws Exception {
byte[] b = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
byte[] b1 = new byte[30];
@@ -1661,9 +1188,8 @@
try {
c.update(b, 0, 10, b1);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
+ fail();
+ } catch (IllegalStateException expected) {
}
c = Cipher.getInstance("DES/CBC/NoPadding");
@@ -1674,9 +1200,8 @@
try {
c.update(b, 3, 15, b1);
- fail("No expected ShortBufferException");
- } catch (ShortBufferException e) {
- //expected
+ fail();
+ } catch (ShortBufferException expected) {
}
}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java
index 67a81cf..04d2d41 100644
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java
@@ -20,7 +20,7 @@
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
-
+import java.nio.charset.UnsupportedCharsetException;
import junit.framework.TestCase;
import tests.support.Support_Configuration;
@@ -53,6 +53,7 @@
URLEncoder.encode("str", "unknown_enc");
fail("Assert 0: Should throw UEE for invalid encoding");
} catch (UnsupportedEncodingException e) {
+ } catch (UnsupportedCharsetException e) {
// expected
}
@@ -60,8 +61,8 @@
try {
URLEncoder.encode(null, "harmony");
fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // expected
+ } catch (NullPointerException expected) {
+ } catch (UnsupportedCharsetException expected) {
}
}
}
diff --git a/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java b/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
index 9dafd23..ffbdf9e 100644
--- a/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
+++ b/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
@@ -27,22 +27,6 @@
import org.apache.harmony.testframework.serialization.SerializationTest;
import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(
- value = Pattern.class,
- untestedMethods= {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "finalize is hard to test since the implementation only calls a native function",
- method = "finalize",
- args = {}
- )
- }
-)
public class PatternTest extends TestCase {
String[] testPatterns = {
"(a|b)*abb",
@@ -85,12 +69,6 @@
final static int DEFAULT_FLAGS = 0;
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "",
- method = "!",
- args = {}
- )
public void testMatcher() {
// some very simple test
Pattern p = Pattern.compile("a");
@@ -98,15 +76,6 @@
assertNotSame(p.matcher("a"), p.matcher("a"));
}
- /*
- * Class under test for String[] split(CharSequence, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of splitsplit(java.lang.String, int) method.",
- method = "split",
- args = {CharSequence.class, int.class}
- )
public void testSplitCharSequenceint() {
// splitting CharSequence which ends with pattern
// bug6193
@@ -181,15 +150,6 @@
assertEquals(s.length, 5);
}
- /*
- * Class under test for String[] split(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of splitsplit(java.lang.String) method.",
- method = "split",
- args = {CharSequence.class}
- )
public void testSplitCharSequence() {
String s[];
Pattern pat = Pattern.compile("b");
@@ -209,12 +169,6 @@
// bug6544
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the functionality of pattern() method.",
- method = "pattern",
- args = {}
- )
public void testPattern() {
/* Positive assertion test. */
for (String aPattern : testPatterns) {
@@ -227,12 +181,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testCompile() {
/* Positive assertion test. */
for (String aPattern : testPatterns) {
@@ -265,12 +213,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method for different flags.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFlags() {
String baseString;
String testString;
@@ -443,13 +385,6 @@
* Check default flags when they are not specified in pattern. Based on RI
* since could not find that info
*/
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of flags() method for default flags.",
- method = "flags",
- args = {}
- )
public void testFlagsCompileDefault() {
for (String pat : testPatternsAlt) {
try {
@@ -466,21 +401,6 @@
* simple implementation that does not use flags combinations. Need to
* improve.
*/
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & flags() methods. Checks that compilation was corect.",
- method = "flags",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & flags() methods. Checks that compilation was corect.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- )
- })
public void testFlagsCompileValid() {
for (String pat : testPatternsAlt) {
for (int flags : flagsSet) {
@@ -494,16 +414,6 @@
}
}
- /*
- * Class under test for Pattern compile(String, int)
- */
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.Checks that correct exceptions were thrown.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testCompileStringint() {
/*
* these tests are needed to verify that appropriate exceptions are
@@ -559,12 +469,6 @@
/*
* Class under test for Pattern compile(String)
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.Checks that correct exceptions were thrown.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testQuantCompileNeg() {
String[] patterns = { "5{,2}", "{5asd", "{hgdhg", "{5,hjkh", "{,5hdsh",
"{5,3shdfkjh}" };
@@ -587,12 +491,6 @@
assertNotNull(Pattern.compile(pattern));
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testQuantCompilePos() {
String[] patterns = {/* "(abc){1,3}", */"abc{2,}", "abc{5}" };
for (String element : patterns) {
@@ -600,12 +498,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile() method. Also tested methods from matcher: matches(), start(int), group(int)",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testQuantComposition() {
String pattern = "(a{1,3})aab";
java.util.regex.Pattern pat = java.util.regex.Pattern.compile(pattern);
@@ -615,12 +507,6 @@
mat.group(1);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
public void testMatches() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
@@ -649,12 +535,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exception",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
public void testMatchesException() {
/* Negative assertion test. */
for (String aPattern : wrongTestPatterns) {
@@ -669,12 +549,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of matches(java.lang.String,java.lang.CharSequence) method.",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
public void testTimeZoneIssue() {
Pattern p = Pattern.compile("GMT(\\+|\\-)(\\d+)(:(\\d+))?");
Matcher m = p.matcher("GMT-9:45");
@@ -687,12 +561,6 @@
// BEGIN android-changed
// Removed one pattern that is buggy on the JDK. We don't want to duplicate that.
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of matches(java.lang.String,java.lang.CharSequence) method.",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
public void testCompileRanges() {
String[] correctTestPatterns = { "[^]*abb]*", /* "[^a-d[^m-p]]*abb", */
"[a-d\\d]*abb", "[abc]*abb", "[a-e&&[de]]*abb", "[^abc]*abb",
@@ -726,12 +594,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of matches(java.lang.String,java.lang.CharSequence) method for ranged patterns.",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
public void testRangesSpecialCases() {
String neg_patterns[] = { "[a-&&[b-c]]", "[a-\\w]", "[b-a]", "[]" };
@@ -755,22 +617,10 @@
}
// END android-changed
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of matches(java.lang.String,java.lang.CharSequence) method.",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
-public void testZeroSymbols() {
+ public void testZeroSymbols() {
assertTrue(Pattern.matches("[\0]*abb", "\0\0\0\0\0\0abb"));
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of matcher(java.lang.String) method.",
- method = "matcher",
- args = {CharSequence.class}
- )
public void testEscapes() {
Pattern pat = Pattern.compile("\\Q{]()*?");
Matcher mat = pat.matcher("{]()*?");
@@ -778,22 +628,10 @@
assertTrue(mat.matches());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testBug181() {
Pattern.compile("[\\t-\\r]");
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testOrphanQuantifiers() {
try {
Pattern.compile("+++++");
@@ -802,12 +640,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testOrphanQuantifiers2() {
try {
Pattern pat = Pattern.compile("\\d+*");
@@ -816,21 +648,6 @@
}
}
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
- })
public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
@@ -856,13 +673,6 @@
}
}
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
@@ -881,12 +691,6 @@
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
@@ -895,12 +699,6 @@
assertEquals("a\n", mat.group());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
@@ -909,12 +707,6 @@
assertEquals("aA", mat.group());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
@@ -923,12 +715,6 @@
assertEquals("aA", mat.group());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
@@ -937,12 +723,6 @@
assertEquals("A", mat.group());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
@@ -954,12 +734,6 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
@@ -971,20 +745,6 @@
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
@@ -1002,20 +762,6 @@
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
@@ -1026,40 +772,13 @@
assertEquals(2, counter);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationGolden",
- args = {}
- )
- })
+
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
@@ -1073,20 +792,6 @@
SerializationTest.verifySelf(pat, comparator);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
@@ -1098,12 +803,6 @@
assertEquals(3, counter);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
@@ -1112,31 +811,11 @@
}
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
@@ -1206,12 +885,6 @@
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
@@ -1230,40 +903,12 @@
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
@@ -1332,20 +977,6 @@
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
@@ -1357,32 +988,12 @@
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies split method for empty string.",
- method = "split",
- args = {java.lang.CharSequence.class}
- )
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of compile(java.lang.String) & split(java.lang.CharSequence, int) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of compile(java.lang.String) & split(java.lang.CharSequence, int) methods.",
- method = "split",
- args = {java.lang.CharSequence.class, int.class}
- )
- })
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
@@ -1391,30 +1002,10 @@
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of matches(java.lang.String), java.lang.CharSequence) method for case insensitive flags.",
- method = "matches",
- args = {java.lang.String.class, java.lang.CharSequence.class}
- )
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
@@ -1429,20 +1020,6 @@
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) methods.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- )
- })
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
@@ -1461,20 +1038,6 @@
assertTrue(isCompiled);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
@@ -1507,12 +1070,6 @@
assertTrue(mat.matches());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testAltWithFlags() {
boolean isCompiled = false;
@@ -1525,21 +1082,7 @@
assertTrue(isCompiled);
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
-public void testRestoreFlagsAfterGroup() {
+ public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
@@ -1552,12 +1095,6 @@
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) method.",
- method = "compile",
- args = {java.lang.String.class}
- )
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
@@ -1879,20 +1416,6 @@
// */}
// END android-removed
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
@@ -1959,20 +1482,6 @@
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
@@ -2011,24 +1520,6 @@
assertTrue(mat.find());
}
- /**
- * s original test was fixed to pass on RI
- */
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
@@ -2130,26 +1621,6 @@
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
@@ -2186,15 +1657,6 @@
assertTrue(mat.matches());
}
- /**
- * s java.util.regex.Pattern.quote(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "quote",
- args = {java.lang.String.class}
- )
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
@@ -2211,25 +1673,6 @@
}
}
- /**
- * s java.util.regex.Pattern.matcher(String, CharSequence)
- * coped from test for matches method
- */
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
@@ -2258,20 +1701,6 @@
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
@@ -2284,20 +1713,6 @@
assertTrue(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
@@ -2318,26 +1733,6 @@
assertFalse(mat.matches());
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the functionality of compile(java.lang.String) & compile(java.lang.String, int) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
@@ -2357,32 +1752,12 @@
/*
* Regression test for HARMONY-688
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "compile",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies the functionality of compile(java.lang.String) & matcher(java.lang.CharSequence) methods.",
- method = "matcher",
- args = {java.lang.CharSequence.class}
- )
- })
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test doesn't verify Matcher and should be moved to PatterTest.",
- method = "split",
- args = {java.lang.CharSequence.class, int.class}
- )
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
@@ -2392,12 +1767,6 @@
assertEquals("", s[0]);
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderTest.java
index b85dad0..911ede3 100644
--- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderTest.java
+++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/ProviderTest.java
@@ -36,12 +36,11 @@
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.Map;
+import java.util.Locale;
import java.util.Set;
import java.util.Map.Entry;
import junit.framework.TestCase;
-import dalvik.annotation.KnownFailure;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
@@ -371,10 +370,24 @@
public final void testService1() {
p.put("MessageDigest.SHA-1", "AnotherClassName");
Provider.Service s = p.getService("MessageDigest", "SHA-1");
-
assertEquals("AnotherClassName", s.getClassName());
}
+ public final void testGetServiceCaseSensitivity() {
+ p.put("i.I", "foo");
+
+ Locale defaultLocale = Locale.getDefault();
+ Locale.setDefault(new Locale("tr", "TR"));
+ try {
+ assertEquals("foo", p.getService("i", "i").getClassName());
+ assertEquals("foo", p.getService("i", "I").getClassName());
+ assertNull(p.getService("\u0130", "\u0130")); // Turkish dotless i and dotted I
+ assertNull(p.getService("\u0131", "\u0131"));
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
// Regression for HARMONY-2760.
@TestTargetNew(
level = TestLevel.PARTIAL_COMPLETE,
diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/SecurityTest.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/SecurityTest.java
index ba96158..bb54aed 100644
--- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/SecurityTest.java
+++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/SecurityTest.java
@@ -22,27 +22,22 @@
package org.apache.harmony.security.tests.java.security;
-import dalvik.annotation.KnownFailure;
+import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-
import java.security.InvalidParameterException;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
-
-
-
import junit.framework.TestCase;
+
+
@TestTargetClass(Security.class)
-/**
- * Tests for <code>Security</code> constructor and methods
- */
public class SecurityTest extends TestCase {
/**
@@ -272,7 +267,6 @@
args = {java.lang.String.class}
)
public void test_getProvidersLjava_lang_String() {
-
try {
Security.getProviders("");
fail("No expected InvalidParameterException");
@@ -285,6 +279,17 @@
} catch (NullPointerException e) {
}
+ testGetProviders(Locale.US);
+ testGetProviders(new Locale("tr", "TR"));
+ }
+
+ /**
+ * Test that Security.getProviders does case sensitive operations
+ * independent of its locale.
+ */
+ private void testGetProviders(Locale locale) {
+ Locale defaultLocale = Locale.getDefault();
+ Locale.setDefault(locale);
Provider p = new MyProvider();
try {
Security.addProvider(p);
@@ -307,6 +312,9 @@
filter = "MyService.MyAlgorithm ATTribute:attributeVALUE";
assertTrue(filter, Arrays.equals(new Provider[] { p }, Security
.getProviders(filter)));
+ filter = "MyService.MyAlgorithm \u0130mPLemented\u0131n:softWARE"; // Turkish dotless i
+ assertTrue(filter, Arrays.equals(new Provider[] { p }, Security
+ .getProviders(filter)));
// Regression for HARMONY-2761
filter = "MyService.NoKeySize KeySize:512";
@@ -319,6 +327,7 @@
assertNull(filter, Security.getProviders(filter));
} finally { // clean up
Security.removeProvider(p.getName());
+ Locale.setDefault(defaultLocale);
}
}
diff --git a/luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
similarity index 76%
rename from luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
rename to luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
index 54ac0b7..3378a9c 100644
--- a/luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
+++ b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
@@ -16,20 +16,20 @@
package org.apache.harmony.xnet.provider.jsse;
-import junit.framework.TestCase;
-
-import javax.net.ssl.SSLSession;
import java.util.Enumeration;
-import java.util.Set;
import java.util.HashSet;
+import java.util.Set;
+import javax.net.ssl.SSLSession;
+import junit.framework.TestCase;
+import libcore.javax.net.ssl.FakeSSLSession;
-public class ClientSessionContextTest extends TestCase {
+public final class ClientSessionContextTest extends TestCase {
public void testGetSessionById() {
- ClientSessionContext context = new ClientSessionContext(null, null);
+ ClientSessionContext context = new ClientSessionContext();
- SSLSession a = new FakeSession("a");
- SSLSession b = new FakeSession("b");
+ SSLSession a = new ValidSSLSession("a");
+ SSLSession b = new ValidSSLSession("b");
context.putSession(a);
context.putSession(b);
@@ -40,7 +40,7 @@
assertSame(a, context.getSession("a", 443));
assertSame(b, context.getSession("b", 443));
- assertEquals(2, context.sessions.size());
+ assertEquals(2, context.size());
Set<SSLSession> sessions = new HashSet<SSLSession>();
Enumeration ids = context.getIds();
@@ -56,12 +56,12 @@
}
public void testTrimToSize() {
- ClientSessionContext context = new ClientSessionContext(null, null);
+ ClientSessionContext context = new ClientSessionContext();
- FakeSession a = new FakeSession("a");
- FakeSession b = new FakeSession("b");
- FakeSession c = new FakeSession("c");
- FakeSession d = new FakeSession("d");
+ ValidSSLSession a = new ValidSSLSession("a");
+ ValidSSLSession b = new ValidSSLSession("b");
+ ValidSSLSession c = new ValidSSLSession("c");
+ ValidSSLSession d = new ValidSSLSession("d");
context.putSession(a);
context.putSession(b);
@@ -83,4 +83,12 @@
assertEquals(expected, sessions);
}
+ static class ValidSSLSession extends FakeSSLSession {
+ ValidSSLSession(String host) {
+ super(host);
+ }
+ @Override public boolean isValid() {
+ return true;
+ }
+ }
}
diff --git a/luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
similarity index 86%
rename from luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
rename to luni/src/test/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
index ee50863a..9714cc3 100644
--- a/luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
+++ b/luni/src/test/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
@@ -16,10 +16,10 @@
package org.apache.harmony.xnet.provider.jsse;
-import junit.framework.TestCase;
-
import java.io.File;
import java.io.IOException;
+import junit.framework.TestCase;
+import libcore.javax.net.ssl.FakeSSLSession;
public class FileClientSessionCacheTest extends TestCase {
@@ -40,17 +40,16 @@
@Override
public void run() {
for (int i = 0; i < iterations; i++) {
- cache.putSessionData(new FakeSession(id + "." + i),
- new byte[10]);
+ cache.putSessionData(new FakeSSLSession(id + "" + i), new byte[10]);
}
}
};
}
- for (int i = 0; i < threads.length; i++) {
- threads[i].start();
+ for (Thread thread : threads) {
+ thread.start();
}
- for (int i = 0; i < threads.length; i++) {
- threads[i].join();
+ for (Thread thread : threads) {
+ thread.join();
}
assertEquals(FileClientSessionCache.MAX_SIZE, cacheDir.list().length);
}
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 b40c6c8..20c8314 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,25 +107,28 @@
NativeCrypto.SSL_CTX_free(c);
}
- private static final PrivateKeyEntry SERVER_PRIVATE_KEY_ENTRY
- = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
- private static final byte[] SERVER_PRIVATE_KEY
- = SERVER_PRIVATE_KEY_ENTRY.getPrivateKey().getEncoded();
+ private static final PrivateKeyEntry SERVER_PRIVATE_KEY_ENTRY;
+ private static final byte[] SERVER_PRIVATE_KEY;
private static final byte[][] SERVER_CERTIFICATES;
-
- private static final PrivateKeyEntry CLIENT_PRIVATE_KEY_ENTRY
- = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
- private static final byte[] CLIENT_PRIVATE_KEY
- = CLIENT_PRIVATE_KEY_ENTRY.getPrivateKey().getEncoded();
+ private static final PrivateKeyEntry CLIENT_PRIVATE_KEY_ENTRY;
+ private static final byte[] CLIENT_PRIVATE_KEY;
private static final byte[][] CLIENT_CERTIFICATES;
static {
try {
- CLIENT_CERTIFICATES = NativeCrypto.encodeCertificates(
- CLIENT_PRIVATE_KEY_ENTRY.getCertificateChain());
+ SERVER_PRIVATE_KEY_ENTRY
+ = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
+ SERVER_PRIVATE_KEY
+ = SERVER_PRIVATE_KEY_ENTRY.getPrivateKey().getEncoded();
SERVER_CERTIFICATES = NativeCrypto.encodeCertificates(
SERVER_PRIVATE_KEY_ENTRY.getCertificateChain());
- } catch (CertificateEncodingException e) {
+ CLIENT_PRIVATE_KEY_ENTRY
+ = TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
+ CLIENT_PRIVATE_KEY
+ = CLIENT_PRIVATE_KEY_ENTRY.getPrivateKey().getEncoded();
+ CLIENT_CERTIFICATES = NativeCrypto.encodeCertificates(
+ CLIENT_PRIVATE_KEY_ENTRY.getCertificateChain());
+ } catch (Exception e) {
throw new RuntimeException(e);
}
}
diff --git a/luni/src/test/java/tests/AllTests.java b/luni/src/test/java/tests/AllTests.java
index fb4d0e3..8cd498b 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.concurrent.AllTests.suite());
suite.addTest(tests.dom.AllTests.suite());
suite.addTest(tests.luni.AllTestsIo.suite());
suite.addTest(tests.luni.AllTestsLang.suite());
@@ -43,8 +42,6 @@
suite.addTest(tests.math.AllTests.suite());
suite.addTest(tests.regex.AllTests.suite());
suite.addTest(tests.security.AllTests.suite());
- suite.addTest(tests.sql.AllTests.suite());
- suite.addTest(tests.SQLite.AllTests.suite());
suite.addTest(tests.suncompat.AllTests.suite());
suite.addTest(tests.xml.AllTests.suite());
suite.addTest(tests.api.org.apache.harmony.kernel.dalvik.AllTests.suite());
diff --git a/luni/src/test/java/tests/SQLite/AllTests.java b/luni/src/test/java/tests/SQLite/AllTests.java
deleted file mode 100644
index ea8b841..0000000
--- a/luni/src/test/java/tests/SQLite/AllTests.java
+++ /dev/null
@@ -1,39 +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 tests.SQLite;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-public class AllTests {
-
- //All tests executed with sqlite3 only
- public static Test suite() {
- TestSuite suite = new TestSuite("Tests for SQLite");
- //$JUnit-BEGIN$
- suite.addTestSuite(DatabaseTest.class);
- suite.addTestSuite(JDBCDriverFunctionalTest.class);
- suite.addTestSuite(JDBCDriverTest.class);
- suite.addTestSuite(BlobTest.class);
- suite.addTestSuite(StmtTest.class);
- suite.addTestSuite(ExceptionTest.class);
- suite.addTestSuite(FunctionContextTest.class);
- //$JUnit-END$
- return suite;
- }
-
-}
diff --git a/luni/src/test/java/tests/SQLite/BlobTest.java b/luni/src/test/java/tests/SQLite/BlobTest.java
deleted file mode 100644
index 353916f..0000000
--- a/luni/src/test/java/tests/SQLite/BlobTest.java
+++ /dev/null
@@ -1,229 +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 tests.SQLite;
-
-import SQLite.Blob;
-import SQLite.Database;
-import SQLite.Exception;
-import SQLite.Stmt;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
-
-import tests.support.DatabaseCreator;
-import tests.support.Support_SQL;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-@TestTargetClass(Blob.class)
-public class BlobTest extends SQLiteTest {
-
- private static Blob testBlob = null;
-
- private byte[] blobInput= null;
-
- private static InputStream file = null;
-
- private static Database db = null;
-
- private static Stmt st = null;
-
- public class MockBlob extends Blob {
- public void finalize() {
- try {
- super.finalize();
- } catch (Throwable exception) {
- fail("Test activity faild!");
- }
- }
- }
-
- public void setUp() throws java.lang.Exception {
- super.setUp();
- testBlob = new Blob();
-
- super.setUp();
- Support_SQL.loadDriver();
- db = new Database();
- db.open(dbFile.getPath(), 0);
-
- db.exec("create table B(id integer primary key, val blob)",null);
- db.exec("insert into B values(1, zeroblob(128))", null);
- db.exec("insert into B values(2, zeroblob(128))", null);
- db.exec("insert into B values(3, zeroblob(128))", null);
-
- // can not fill Blob with data at this point...
- /*
- File resources = Support_Resources.createTempFolder();
- BufferedReader r = null;
- try {
- Class c = Class.forName(this.getClass().getName());
- assertNotNull(c);
- file = Class.forName(this.getClass().getName())
- .getResourceAsStream("/blob.c");
- r = new BufferedReader(new InputStreamReader(file));
- } catch (NullPointerException e) {
- fail("Should not throw NullPointerException reading file"
- + e.getMessage());
- }
- OutputStream out = testBlob.getOutputStream();
- String s = null;
- while ((s = r.readLine()) != null) {
- out.write(r.readLine().getBytes());
- }
- out.flush();
- out.close();
- testBlob.close();
- */
- }
-
- public void tearDown() {
-
- testBlob.close();
- super.tearDown();
- }
-
- /**
- * @throws Exception
- * @throws IOException
- * @tests Blob#Blob()
- */
- @TestTargets ( {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "db.open_blob is not supported also for Stmt, therefore cannot test Blobs",
- method = "Blob",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "functional test",
- method = "getOutputStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "functional test",
- method = "getInputStream",
- args = {}
- )
- })
- @KnownFailure("db.open_blob is not supported.")
- public void testBlob() throws Exception, IOException {
- byte[] b = new byte[4];
- byte[] b128 = new byte[128];
- for (int i = 0; i < b128.length; i++) {
- b128[i] = (byte) i;
- }
- Blob blob = db.open_blob(dbFile.getPath(), "B", "val", 1, true);
- try {
-
- OutputStream os = blob.getOutputStream();
- os.write(b128);
- os.close();
-
- InputStream is = blob.getInputStream();
- is.skip(96);
- assertEquals(4,is.read(b));
- is.close();
- } finally {
- blob.close();
- }
- }
-
- /**
- * @tests Blob#finalize()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Can not be checked. Should be tested in DX test package.",
- method = "finalize",
- args = {}
- )
- public void testFinalize() {
-
- }
-
- /**
- * @tests Blob.getInputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exception test",
- method = "getInputStream",
- args = {}
- )
- public void testGetInputStream() {
- InputStream in = testBlob.getInputStream();
-
- try {
- in.read();
- fail("Exception not thrown for invalid Blob.");
- } catch (Throwable e) {
- //ok
- }
- }
-
- /**
- * @tests Blob#getOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exception test",
- method = "getOutputStream",
- args = {}
- )
- public void testGetOutputStream() {
- OutputStream out = testBlob.getOutputStream();
-
- try {
- out.write(null);
- fail("Write operation unsupported");
- } catch (Throwable e) {
- assertEquals("Write operation unsupported", e.getMessage());
- }
- }
-
- /**
- * @tests Blob#close()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not clear from spec what should happen when Blob is closed.",
- method = "close",
- args = {}
- )
-// @KnownFailure("Blob does not clean up inputStream.")
- public void testClose() {
- assertNotNull(testBlob);
-
- testBlob.close();
- // inputStream either null or some error occurs
- try {
- // TODO This does look a bit weird. Revisit later.
- assertNull(testBlob.getInputStream());
- } catch (Throwable e) {
- //ok
- }
- }
-}
diff --git a/luni/src/test/java/tests/SQLite/DatabaseTest.java b/luni/src/test/java/tests/SQLite/DatabaseTest.java
deleted file mode 100644
index f04266b..0000000
--- a/luni/src/test/java/tests/SQLite/DatabaseTest.java
+++ /dev/null
@@ -1,2038 +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 tests.SQLite;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import tests.support.DatabaseCreator;
-import tests.support.MockFunction;
-import tests.support.ThreadPool;
-import tests.support.resource.Support_Resources;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URL;
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import SQLite.Authorizer;
-import SQLite.Blob;
-import SQLite.BusyHandler;
-import SQLite.Callback;
-import SQLite.Constants;
-import SQLite.Database;
-import SQLite.Exception;
-import SQLite.Function;
-import SQLite.FunctionContext;
-import SQLite.ProgressHandler;
-import SQLite.Stmt;
-import SQLite.TableResult;
-import SQLite.Trace;
-import SQLite.Vm;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.logging.Logger;
-
-@TestTargetClass(Database.class)
-public class DatabaseTest extends SQLiteTest {
-
- /**
- * The SQLite db file.
- */
-// protected final File dbFile = new File("sqliteTest.db");
-//
-// private final String connectionURL = "jdbc:sqlite:/" + dbFile.getPath();
-//
-// private final String classname = "SQLite.JDBCDriver";
-//
-// private static Connection conn = null;
-
- private static ErrorTracker tracker = null;
-
- private Statement statement;
-
- private Database db = null;
-
- private static final int numThreads = 10;
-
- private static final int numOfRecords = 30;
-
- public void setUp() throws java.lang.Exception {
- try {
- super.setUp();
- assertNotNull("Could not establish DB connection",conn);
- tracker = new ErrorTracker();
-
- statement = conn.createStatement();
-
- //Cleanup tables if necessary
-
- DatabaseMetaData meta = conn.getMetaData();
- assertNotNull(meta);
- if (meta != null) {
- ResultSet userTab = meta.getTables(null, null, null, null);
- while (userTab.next()) {
- String tableName = userTab.getString("TABLE_NAME");
- this.statement.execute("drop table "+tableName);
- }
- }
-
- // Create default test table
-// statement = conn.createStatement();
- statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
- statement.close();
-
- try {
- db = new Database();
- db.open(dbFile.getPath(), 0);
- db.busy_handler(null);
- } catch (Exception e) {
- System.out.println("2: Error opening File: Dir "+dbFile.getPath()+" Name: "+dbFile.getPath());
- } catch (java.lang.Exception e) {
- System.err.println("Non SQLException "+e.getMessage());
- }
- } catch (Exception e) {
- System.out.println("Database setup fails: "+e.getMessage());
- e.printStackTrace();
- }
-
- }
-
- public void tearDown() {
-
- try {
- db.close();
- }catch (Exception e) {
- if (! (e.getMessage().equals("database already closed"))) {
- System.err.println("Error closing DB "+dbFile.getPath());
- }
- }
-// conn.close();
-// dbFile.delete();
- tracker.reset();
- super.tearDown();
- }
-
- /**
- * @tests Database#Database()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "constructor test",
- method = "Database",
- args = {}
- )
- public void testDatabase() {
- // db closed
- Database db2 = new Database();
- try {
- db.close();
- db2 = new Database();
- db2.open(dbFile.getPath(), 0);
- db2.close();
- db.open(dbFile.getPath(), 0);
- } catch (Exception e) {
- fail("Database object could not be created "+e.getMessage());
- e.printStackTrace();
- }
- //db is open
- try {
- db2.open(dbFile.getPath(), 0);
- db2.close();
- } catch (Exception e) {
- fail("Second Database object could not be created "+e.getMessage());
- e.printStackTrace();
- }
- }
-
- /**
- * @tests Database#finalize()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "method test",
- method = "finalize",
- args = {}
- )
- public void testFinalize() {
- }
-
- /**
- * @tests {@link Database#open(String, int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test. Test fails.",
- method = "open",
- args = {java.lang.String.class, int.class}
- )
- public void testOpen() {
- try {
- db.close();
- db.open(dbFile.getPath(), 0);
- } catch (Exception e) {
- fail("Database object could not be opened: " + e.getMessage());
- e.printStackTrace();
- }
- // open second db while db1 still open
- Database db2 = new Database();
- try {
- db2.open(dbFile.getPath(), 0);
- db2.open(dbFile.getPath(), 0);
- db2.close();
- } catch (Exception e) {
- fail("Database object could not be opened: " + e.getMessage());
- e.printStackTrace();
- }
- // open non db file
- File tempDir = Support_Resources.createTempFolder();
- final String resourceName = "blob.c";
- try {
- URL file = Class.forName(this.getClass().getName())
- .getResource("/blob.c");
- db2.open(file.getPath(), 0);
- fail("Should not be able to open non db file");
- } catch (Exception e) {
- assertEquals("unknown error in open", e.getMessage());
- } catch (java.lang.Exception e) {
- fail("Error in setup " + e.getMessage());
- e.printStackTrace();
- }
-
- }
-
- /**
- * @tests Database#open_aux_file(String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported",
- method = "open_aux_file",
- args = {java.lang.String.class}
- )
- public void testOpen_aux_file() {
- File temp = null;
- try {
- db.open_aux_file("");
- fail("open should fail");
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
-
- /*
- try {
- temp = File.createTempFile("openAuxMethod", ".db");
- db.open_aux_file("");
- db.exec("create table AUX_TABLE", null);
- db.close();
- } catch (Exception e) {
- temp.delete();
- fail("Error handling temporary file "+e.getMessage());
- e.printStackTrace();
- } catch (IOException e) {
- temp.delete();
- fail("Could not create temporary File");
- e.printStackTrace();
- }
- try {
- db.open(dbFile.getPath(),0);
- db.exec("select * from AUX_TABLE", null);
- fail("Statement should fail");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- temp.delete();
- */
- }
-
- /**
- * @tests Database#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "close",
- args = {}
- )
- public void testClose() {
- try {
- db.close();
- db.get_table("test");
- } catch (Exception e) {
- assertTrue(e.getMessage().equals("database already closed"));
- try {
- db.open(dbFile.getPath(), 0);
- } catch (Exception e1) {
- fail("Database object could not be reopened after 'close': "
- + e.getMessage());
- e1.printStackTrace();
- }
- }
-
- try {
- db.close();
- db.close();
- } catch (Exception e) {
- assertTrue(e.getMessage().equals("database already closed"));
- try {
- db.open(dbFile.getPath(), 0);
- } catch (Exception e1) {
- fail("Database object could not be reopened after 'close': "
- + e.getMessage());
- e1.printStackTrace();
- }
- }
- }
-
- /**
- * @tests Database#exec(String, Callback)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "exec",
- args = {java.lang.String.class, Callback.class}
- )
- public void testExecStringCallback() {
- TableResult res = new TableResult();
- try {
- db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(1, 10, 20)", null);
- db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
- db
- .exec("delete from " + DatabaseCreator.SIMPLE_TABLE1
- + " where 1", null);
- } catch (Exception e) {
- fail("Database error");
- e.printStackTrace();
- }
- String row[] = (String[]) res.rows.elementAt(0);
- assertEquals(Integer.parseInt(row[0]), 1);
- assertEquals(Integer.parseInt(row[1]), 10);
- assertEquals(Integer.parseInt(row[2]), 20);
- }
-
- /**
- * @tests Database#exec(String, Callback, String[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "exec",
- args = {java.lang.String.class, Callback.class, java.lang.String[].class}
- )
- public void testExecStringCallbackStringArray() {
- TableResult res = new TableResult();
- String args[] = new String[1];
- args[0] = "table";
- try {
- db.exec("select name from sqlite_master where type = '%q';", res,
- args);
- String[] s = (String[]) res.rows.elementAt(0);
- assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
- } catch (Exception e) {
- fail("DB Error occurred");
- e.printStackTrace();
- }
-
- try {
- db.exec("select name from sqlite_master where type = ", res, args);
- fail("Testmethod should fail");
- } catch (Exception e) {
- // Ok
- }
- }
-
- /**
- * @tests {@link Database#last_insert_rowid()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "last_insert_rowid",
- args = {}
- )
- public void testLast_insert_rowid() {
- assertEquals(0, db.last_insert_rowid());
- try {
- db
- .exec(
- "create table TEST5(id integer, firstname text, lastname text);",
- null);
- db.exec("insert into TEST5 values (1,'James','Bond');", null);
- db.exec("insert into TEST5 values (2,'Fiona','Apple');", null);
- } catch (Exception e) {
- fail("Error in test setup: " + e.getMessage());
- e.printStackTrace();
- }
- assertEquals(2, db.last_insert_rowid());
- assertEquals(db.last_insert_rowid(), db.last_insert_rowid());
-
- try {
- db.exec("drop table TEST5;", null);
- } catch (Exception e) {
- fail("Error in test setup: " + e.getMessage());
- e.printStackTrace();
- }
- assertEquals(2, db.last_insert_rowid());
- }
-
- /**
- * @throws Exception
- * @tests {@link Database#interrupt()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "interrupt",
- args = {}
- )
- @KnownFailure("Reason for failure unknown: Database should be locked. " +
- "Specification of interrupt is scarce.")
- public void testInterrupt() throws Exception {
- ThreadPool threadPool = new ThreadPool(numThreads);
-
- // initialization
- ResultSet userTabs;
- try {
- userTabs = conn.getMetaData().getTables(null, null, null, null);
- while (userTabs.next()) {
- String tableName = userTabs.getString("TABLE_NAME");
- if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
- statement.execute(DatabaseCreator.DROP_TABLE1);
- }
- }
- db.exec(DatabaseCreator.CREATE_TABLE3, null);
- db.exec(DatabaseCreator.CREATE_TABLE1, null);
- } catch (SQLException e1) {
- fail("Error initializing test " + e1.toString());
- e1.printStackTrace();
- } catch (Exception e) {
- fail("Error initializing test " + e.getMessage());
- e.printStackTrace();
- }
-
- int id1 = numOfRecords - 3;
- threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
- // should not be able to do any other insertions since task 1 holds lock
- int id2 = numOfRecords + 3;
- threadPool
- .runTask(createTask2Interrupt(id2, dbFile.getPath(), tracker));
-
- threadPool.join();
-
- List<String> errors = tracker.getErrors();
- System.out.println("Last error: " + db.error_message());
- if (errors.size() > 0) {
- assertEquals(errors.get(0), db
- .error_string(Constants.SQLITE_LOCKED));
- for (String s : errors) {
- Logger.global.info("INTERRUPT Error: " + s);
- }
-
- } else {
- fail("Should have one exception: database should be locked.");
- }
-
- // reset
-
- db
- .exec(
- "delete from " + DatabaseCreator.TEST_TABLE1
- + " where 1", null);
- db
- .exec(
- "delete from " + DatabaseCreator.TEST_TABLE3
- + " where 1", null);
-
- }
-
- /**
- * @tests {@link Database#changes()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test fails",
- method = "changes",
- args = {}
- )
- @KnownFailure("Returns wrong number for updates: returns value > 1 for select.")
- public void testChanges() {
- TableResult res = new TableResult();
- try {
- assertTrue(db.changes() == 0);
- db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(2, 5, 7);", null);
- int rows = (int) db.changes();
- assertEquals(1,db.changes());
- db.exec("update " + DatabaseCreator.SIMPLE_TABLE1
- + " set speed = 7, size= 5 where id = 2;", null);
- assertEquals(1,db.changes());
- db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
- assertEquals(0,db.changes());
- db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(8, 5, 7);", null);
- db.exec("Update "+DatabaseCreator.SIMPLE_TABLE1+" set speed = 10;",null);
- assertTrue(db.changes() > 2);
- } catch (Exception e) {
- fail("Could not get changes: " + e.getMessage());
- e.printStackTrace();
- }
- }
-
- /**
- * @throws SQLException
- * @throws Exception
- * @tests {@link Database#busy_handler(BusyHandler)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "method test fails once in a while. Cannot be sure that exception is thrown every time.",
- method = "busy_handler",
- args = {BusyHandler.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "method test fails once in a while. Cannot be sure that exception is thrown every time.",
- method = "busy",
- clazz = BusyHandler.class,
- args = {java.lang.String.class, int.class}
- )
- })
- @KnownFailure("method test fails once in a while. "+
- "Cannot be sure that exception is thrown in every test execution.")
- public void testBusy_handler() throws SQLException, Exception {
- TestBusyHandler bh = new TestBusyHandler();
- db.busy_handler(bh);
- int counter = 0;
- ThreadPool threadPool = new ThreadPool(numThreads);
-
- // initialization
- ResultSet userTabs;
- try {
- userTabs = conn.getMetaData().getTables(null, null, null, null);
- while (userTabs.next()) {
- String tableName = userTabs.getString("TABLE_NAME");
- if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
- statement.execute(DatabaseCreator.DROP_TABLE1);
- }
- }
- db.exec(DatabaseCreator.CREATE_TABLE3, null);
- db.exec(DatabaseCreator.CREATE_TABLE1, null);
- } catch (SQLException e1) {
- fail("Error initializing test " + e1.toString());
- e1.printStackTrace();
- } catch (Exception e) {
- fail("Error initializing test " + e.getMessage());
- e.printStackTrace();
- }
-
-
-// try {
-// DatabaseCreator.fillTestTable1(conn, numOfRecords);
- // set to fail immediately if table is locked.
-// db.busy_handler(bh);
-// db.busy_timeout(0);
- try {
- conn.setAutoCommit(false);
- int id1 = numOfRecords - 3;
- threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
- int id2 = numOfRecords + 3;
- threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
- int oldID = 5;
- int newID = 100;
- threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID,
- tracker));
-
- threadPool.join();
-
- List<String> errors = tracker.getErrors();
- if (errors.size() > 0) {
-// assertEquals(errors.get(0),
-// db.error_string(Constants.SQLITE_LOCKED));
- for (String s: errors) {
- System.out.println("Round 2 Error: "+s);
- }
- } else {
- fail("No error happened");
- }
-
- // reset
-
-
- db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
- null);
- db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
- null);
-//
-// // increase timeout for retry
-// db.busy_timeout(1000);
-// db.busy_handler(bh);
-// tracker.reset();
-
-// threadPool = new ThreadPool(numThreads);
-//
-// threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
-// threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
-//
-// threadPool.join();
-//
-// errors = tracker.getErrors();
-// if (errors.size() > 0) {
-// // assertEquals(errors.get(0),
-// // db.error_string(Constants.SQLITE_LOCKED));
-// for (String s: errors) {
-// System.out.println("Round 2 Error"+s);
-// }
-// } else {
-// // ok
-// System.out.println("BUSY: No Error!");
-// }
-//
-//
- } catch (Exception e) {
- fail("Error in test setup " + e.getMessage());
- try {
- db.get_table("select * from " + DatabaseCreator.TEST_TABLE1,
- null).toString();
- } catch (Exception e1) {
-
- e1.printStackTrace();
- }
- e.printStackTrace();
-// } catch (SQLException e2) {
-// System.out.println("Error in test setup "+e2.toString());
-// try {
-// db.get_table("select * from "+DatabaseCreator.TEST_TABLE1,null).
-// toString();
-// } catch (Exception e1) {
-// e2.printStackTrace();
-// }
- } finally {
- conn.setAutoCommit(true);
- db.exec(DatabaseCreator.DROP_TABLE1, null);
- db.exec(DatabaseCreator.DROP_TABLE3, null);
- }
- }
-
- /**
- * @throws Exception
- * @throws SQLException
- * @tests {@link Database#busy_timeout(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "test fails. Cannot be sure that exception is thrown every time.",
- method = "busy_timeout",
- args = {int.class}
- )
- @KnownFailure("Database does not lock values")
- public void testBusy_timeout() throws Exception, SQLException {
- int counter = 0;
- ThreadPool threadPool = new ThreadPool(numThreads);
-
- // initialization
- ResultSet userTabs;
- try {
- userTabs = conn.getMetaData().getTables(null, null, null, null);
- while (userTabs.next()) {
- String tableName = userTabs.getString("TABLE_NAME");
- if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
- statement.execute(DatabaseCreator.DROP_TABLE1);
- }
- }
- db.exec(DatabaseCreator.CREATE_TABLE3, null);
- db.exec(DatabaseCreator.CREATE_TABLE1, null);
- } catch (SQLException e1) {
- fail("Error initializing test " + e1.toString());
- e1.printStackTrace();
- } catch (Exception e) {
- fail("Error initializing test " + e.getMessage());
- e.printStackTrace();
- }
-
-
- // test run
- try {
- conn.setAutoCommit(false);
-
-// DatabaseCreator.fillTestTable1(conn, numOfRecords);
- // set to fail immediately if table is locked.
- db.busy_handler(null);
- db.busy_timeout(0);
- int id1 = numOfRecords - 3;
-
- threadPool.runTask(createTask2(id1, dbFile.getPath(), tracker));
- int id2 = numOfRecords + 3;
- threadPool.runTask(createTask1(id2, dbFile.getPath(), tracker));
- int oldID = 5;
- int newID = 100;
- threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID,
- tracker));
-
- threadPool.join();
-
- List<String> errors = tracker.getErrors();
- assertTrue("No error occurred on DB but should have",errors.size() > 0);
-
- assertEquals(errors.get(0),
- db.error_string(Constants.SQLITE_LOCKED));
- assertEquals(errors.get(0), "database is locked");
-
- // reset
-
- db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
- null);
- db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
- null);
-
- // increase timeout for retry
- db.busy_timeout(10000);
- db.busy_handler(null);
- tracker.reset();
- threadPool = new ThreadPool(numThreads);
-
- threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker));
- threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker));
-
- threadPool.join();
-
- errors = tracker.getErrors();
- if (errors.size() > 0) {
- fail("busy timeout should prevent from lock exception!");
- for (String s: errors) {
- System.out.println("Round 2 Error"+s);
- }
- } else {
- // ok
- }
-
-
- } catch (Exception e) {
- fail("Error in test setup " + e.getMessage());
- try {
- db.get_table("select * from " + DatabaseCreator.TEST_TABLE1,
- null).toString();
- } catch (Exception e1) {
-
- e1.printStackTrace();
- }
- e.printStackTrace();
- } finally {
- conn.setAutoCommit(true);
- // cleanup
- db.exec(DatabaseCreator.DROP_TABLE1, null);
- db.exec(DatabaseCreator.DROP_TABLE3, null);
- }
- }
-
- /**
- * @tests {@link Database#get_table(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "get_table",
- args = {java.lang.String.class}
- )
- public void testGet_tableString() {
- TableResult emptyTable = new TableResult();
- try {
- //select from empty table
- TableResult res = db.get_table("select * from "
- + DatabaseCreator.SIMPLE_TABLE1);
- assertEquals(res.toString(), emptyTable.toString());
- //fill table-> t
-// DatabaseCreator.fillSimpleTable1(conn);
-// res = db.get_table("select * from "
-// + DatabaseCreator.SIMPLE_TABLE1);
-// assertFalse(emptyTable.toString().equals(res.toString()));
-
- try {
- db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " VALUES(1, 10, 20)", null);
- res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- db
- .exec("delete from " + DatabaseCreator.SIMPLE_TABLE1
- + " where 1", null);
- } catch (Exception e) {
- fail("Database error");
- e.printStackTrace();
- }
- String row[] = (String[]) res.rows.elementAt(0);
- assertEquals(Integer.parseInt(row[0]), 1);
- assertEquals(Integer.parseInt(row[1]), 10);
- assertEquals(Integer.parseInt(row[2]), 20);
- } catch (Exception e) {
- fail("Error getting table " + e.getMessage());
- e.printStackTrace();
-// } catch (SQLException e) {
-// fail("Error initialising table " + e.getMessage());
-// e.printStackTrace();
- }
- }
-
- /**
- * @tests {@link Database#get_table(String, String[])}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "get_table",
- args = {java.lang.String.class, java.lang.String[].class}
- )
- public void testGet_tableStringStringArray() {
- String args[] = new String[1];
- args[0] = "table";
- String argsFail[] = new String[1];
- try {
- TableResult res = db.get_table(
- "select name from sqlite_master where type = ", argsFail);
- fail("Testmethod should fail");
- } catch (Exception e) {
- try {
- TableResult res = db.get_table(
- "select name from sqlite_master where type = '%q'",
- args);
- String[] s = (String[]) res.rows.elementAt(0);
- assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
- } catch (Exception e2) {
- fail("Testmethod failed: " + e2.getMessage());
- e.printStackTrace();
- }
- }
-
- }
-
- /**
- * @tests {@link Database#get_table(String, String[], TableResult)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "get_table",
- args = {java.lang.String.class, java.lang.String[].class, TableResult.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "toString",
- clazz = TableResult.class,
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "types",
- clazz = TableResult.class,
- args = {String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "TableResult",
- clazz = TableResult.class,
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "method test",
- method = "columns",
- clazz = TableResult.class,
- args = {String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "method test",
- method = "newrow",
- clazz = TableResult.class,
- args = {String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "method test",
- method = "clear",
- clazz = TableResult.class,
- args = {}
- )
-
- })
- public void testGet_tableStringStringArrayTableResult() {
- String args[] = new String[1];
- String argsFail[] = new String[1];
- TableResult res = new TableResult();
- TableResult defaultTableRes = new TableResult();
- args[0] = "table";
-
- try {
- db.get_table("select name from sqlite_master where type = '%q'",
- argsFail, res);
- assertEquals(defaultTableRes.toString(), res.toString());
- } catch (Exception e) {
- try {
- db.get_table(
- "select name from sqlite_master where type = '%q'",
- args, res);
- String[] s = (String[]) res.rows.elementAt(0);
- assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
- String[] types = res.types;
- System.out
- .println("DatabaseTest.testGet_tableStringStringArrayTableResult() "+types.toString());
- } catch (Exception e2) {
- fail("Testmethod failed: " + e2.getMessage());
- e.printStackTrace();
- }
- }
- }
-
-
- /**
- * @tests {@link Database#complete(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "complete",
- args = {java.lang.String.class}
- )
- public void testComplete() {
- assertFalse(db.complete("create"));
- assertTrue(db.complete("create table TEST (res double);"));
- }
-
- /**
- * @tests {@link Database#version()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "version",
- args = {}
- )
- public void testVersion() {
- String version = db.version();
- if (version != null) {
- assertTrue(Integer.parseInt(db.version().substring(0,1)) > 0);
- assertEquals(db.version(), db.version());
- } else {
- fail("DB version info missing");
- }
-
- }
-
- /**
- * @tests {@link Database#dbversion()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "dbversion",
- args = {}
- )
- public void testDbversion() {
- String verNo = "";
- try {
- verNo = db.dbversion();
- db.close();
- assertEquals(db.dbversion(),"unknown");
- db.open(dbFile.getPath(), 0);
- assertEquals(verNo,db.dbversion());
- } catch (Exception e) {
- try {
- db.open(dbFile.getPath(), 0);
- } catch (Exception e1) {
- fail("error in db setup "+e.getMessage());
- e.printStackTrace();
- }
- fail("error in db setup "+e.getMessage());
- e.printStackTrace();
- }
-
- assertTrue(Integer.parseInt(verNo.substring(0, 1))>= 3 );
-
- }
-
- /**
- * @tests {@link Database#create_function(String, int, Function)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "create_function",
- args = {java.lang.String.class, int.class, Function.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "create_function",
- args = {java.lang.String.class, int.class, Function.class}
- )
- })
- public void testCreate_function() {
- try {
- double input = 1.0;
- db.exec("create table TEST (res double)", null);
- db.exec("insert into TEST values (" + Double.toString(input) + ")",
- null);
- TableResult res = new TableResult();
- Function sinFunc = (Function) new SinFunc();
- db.create_function("sin", 1, sinFunc);
- db.exec("select sin(res) from TEST WHERE res = "
- + Double.toString(input), res);
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
- double sinusVal = Double.parseDouble(val);
- double funcVal = Math.sin(input);
-
- assertTrue(Math.round(funcVal) == Math.round(sinusVal));
- } catch (Exception e) {
- fail("Error happened creating function:" + e.getMessage());
- e.printStackTrace();
- }
- }
-
- /**
- * @tests {@link Database#create_aggregate(String, int, Function)}
- */
- @TestTargets({
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "create_aggregate",
- args = {java.lang.String.class, int.class, Function.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "step",
- clazz = Function.class,
- args = {FunctionContext.class, String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "last_step",
- clazz = Function.class,
- args = {FunctionContext.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "function",
- clazz = Function.class,
- args = {FunctionContext.class, String[].class}
- )
- })
- @KnownFailure("Aggregation function not called")
- public void testCreate_aggregate() {
- TestTrace t = new TestTrace();
-
- MockFunction aggFunction = new MockFunction();
-
- try {
- db
- .exec(
- "create table TEST(id integer, firstname text, lastname text)",
- null);
- db.exec("insert into TEST values(3, 'James', 'Bond'); ", null);
- db.exec("insert into TEST values(4, 'Fiona', 'Apple'); ", null);
- db.trace((Trace) t);
- db.create_aggregate("myaggfunc", 1, aggFunction);
- db.function_type("myaggfunc", Constants.SQLITE3_TEXT);
- db.exec("PRAGMA show_datatypes = on", null);
-
- assertFalse(aggFunction.functionCalled);
- assertFalse(aggFunction.stepCalled);
- assertFalse(aggFunction.lastStepCalled);
- db.exec("select myaggfunc(TEST.firstname) from TEST", t);
- assertTrue(aggFunction.stepCalled);
- assertTrue(aggFunction.lastStepCalled);
- assertTrue(aggFunction.functionCalled);
-
- assertEquals("James Fiona ",aggFunction.getAggValue());
- db.exec("drop table TEST", null);
- } catch (Exception e) {
- System.out.println(t.getTrace());
- fail("Error in test setup: " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- db.create_aggregate("myaggfunc", 0, null);
- } catch (Throwable e) {
- assertEquals("null SQLite.Function not allowed",e.getMessage());
- }
-
- try {
- db.create_aggregate("myaggfunc", 0, aggFunction);
- } catch (Throwable e) {
- assertEquals("wrong number of arguments to function myaggfunc()",e.getMessage());
- }
-
- }
-
- /**
- * @throws Exception
- * @tests {@link Database#function_type(String, int)}
- * This method does not make sense
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Method does not make sense: for functions, return type is already set.",
- method = "function_type",
- args = {java.lang.String.class, int.class}
- )
- public void testFunction_type() throws Exception {
-
- double input = 1.0;
- TableResult res = new TableResult();
- Function sinFunc = (Function) new SinFunc();
-
- db.exec("PRAGMA show_datatypes = on", null);
- db.exec("create table TEST (res double)", null);
- db.exec("insert into TEST values (" + Double.toString(input) + ")",
- null);
-
- db.create_function("sin", 1, sinFunc);
- db.function_type("sin", Constants.SQLITE_FLOAT);
- res = db.get_table("select sin(res) from TEST WHERE res = "
- + Double.toString(input));
-
- String row[] = (String[]) res.rows.elementAt(0);
- String val = row[0];
- assertTrue("double".equalsIgnoreCase(res.types[0]));
- assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val)));
-
- // function determines return type: test that Double type is returned.
- db.function_type("sin", Constants.SQLITE_BLOB);
- Stmt s = db.prepare("select sin(res) from TEST WHERE res = ?");
- s.bind(1,input);
- s.step();
-
- res = db.get_table("select sin(res) from TEST WHERE res = "
- + Double.toString(input));
- assertTrue("double".equalsIgnoreCase(res.types[0]));
- row = (String[]) res.rows.elementAt(0);
- val = row[0];
- assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val)));
-
-
-
-
- }
-
- /**
- * @tests {@link Database#last_error()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "last_error",
- args = {}
- )
- public void testLast_error() {
- assertEquals(db.last_error(), Constants.SQLITE_OK);
- try {
- db.exec("create table TEST (res double)",null);
- db.exec("create table TEST (res double)",null);
- fail("Error should have happened");
- } catch (Exception e) {
- assertEquals(db.last_error(),db.last_error());
- assertEquals(db.last_error(),Constants.SQLITE_ERROR);
- }
-
- }
-
- /**
- * @tests {@link Database#set_last_error(int)}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "don't now which other errors may occur from black-box approach.",
- method = "set_last_error",
- args = {int.class}
- )
- public void testSet_last_error() {
- assertEquals(db.last_error(), Constants.SQLITE_OK);
-
- try {
- db.exec("sel from test;", null);
- } catch (Exception e) {
- assertEquals(Constants.SQLITE_ERROR,db.last_error());
- }
- }
-
- /**
- * @tests {@link Database#error_message()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "error_message",
- args = {}
- )
- public void testError_message() {
- String statement = "create table TEST (res double)";
- try {
- db.exec(statement,null);
- db.exec(statement,null);
- fail("DB Error expected");
- } catch (Exception e) {
- String dbError = db.error_message();
- assertTrue(e.getMessage().equals(dbError));
-
- }
- }
-
- /**
- * @tests {@link Database#error_string(int)}
- */
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "error_string",
- args = {int.class}
- )
- public void testError_string() {
- TestTrace t = new TestTrace();
- assertEquals(db.last_error(), Constants.SQLITE_OK);
- String errorString = db.error_string(Constants.SQLITE_ERROR);
- try {
- db.trace((Trace) t);
- db.exec("create table TEST (res double)", t);
- db.exec("create table TEST (res double)", t);
- } catch (Exception e) {
- assertEquals(db.last_error(), Constants.SQLITE_ERROR);
- if (db.is3()) {
- assertEquals("Unsupported Method (sqlite 3): error_string", db
- .error_string(db.last_error()), errorString);
- }
- }
- }
-
- /**
- * @throws UnsupportedEncodingException
- * @tests {@link Database#set_encoding(String)}
- * Method unsupported? -> tests fail
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test fails.",
- method = "set_encoding",
- args = {java.lang.String.class}
- )
- @KnownFailure("ASCII encoding does not work: a UTF encoded val is returned. Spec is not sufficient. "
- + "Might be that test impl is wrong or String constructor for the ASCII encoding.")
- public void testSet_encoding() throws UnsupportedEncodingException {
- String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana?
- TableResult res = new TableResult();
- String refOutput = null;
- Stmt stat = null;
-
- // DB setup
- try {
- db.exec("create table encodingTest (encoded text DEFAULT NULL);",
- null);
- stat = db
- .prepare("insert into encodingTest(encoded) values(:one);");
- stat.bind(1, input);
- stat.step();
- // stat.close();
- db.exec("select * from encodingTest;", res);
- String[] encInput = (String[]) res.rows.elementAt(0);
- String output = encInput[0];
- assertEquals(input, output);
- // db.exec("delete from encodingTest where 1", null);
- } catch (Exception e1) {
- fail("Error in test setup: " + e1.getMessage());
- e1.printStackTrace();
- }
-
- // tests for different encoding schemes
- String[] charsetNames = {"UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE"};
- for (int i = 0; i < charsetNames.length; i++) {
- try {
- byte[] encInput = input.getBytes(charsetNames[i]);
- db.set_encoding(charsetNames[i]);
- db.exec("select * from encodingTest;", res);
- String[] encOutput = (String[]) res.rows.elementAt(0);
- String inputAsString = new String(encInput,charsetNames[i]);
- assertEquals(inputAsString, encOutput[0]);
- } catch (Exception e4) {
- fail("Error setting the encoding." + e4.getMessage());
- e4.printStackTrace();
- } catch (UnsupportedEncodingException e2) {
- fail(e2.getMessage());
- e2.printStackTrace();
- }
- }
-
- // Default tests
- try {
- db.set_encoding("UTF-16");
- db.exec("select * from encodingTest;", res);
- String[] encOutput1 = (String[]) res.rows.elementAt(0);
- assertEquals("Got "+encOutput1[0]+" as UTF-16",input,encOutput1[0]);
-
- db.set_encoding("US-ASCII");
- db.exec("select * from encodingTest;", res);
- String[] encOutput2 = (String[]) res.rows.elementAt(0);
- assertEquals(new String(input.getBytes(),"US-ASCII"),encOutput2[0]);
- } catch (Exception e) {
- fail("Error setting the encoding." + e.getMessage());
- e.printStackTrace();
- }
-
-
- // DB teardown
- try {
- stat.close();
- db.exec("delete from encodingTest", null);
- // reset encoding
- } catch (Exception e3) {
- fail("Error in teardown of encoding environment");
- e3.printStackTrace();
- }
-
- // Default tests
- try {
- db.set_encoding("");
- fail("invalid input should fail");
- } catch (Exception e) {
- //ok
- }
-
- }
-
- /**
- * Test fails -> implemented correctly?
- * @tests {@link Database#set_authorizer(Authorizer)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test fails.",
- method = "set_authorizer",
- args = {Authorizer.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test fails.",
- method = "authorize",
- clazz = Authorizer.class,
- args = {int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- })
- @KnownFailure("Callback never made for authorization. "+
- "Results of private table are returned withouth furhter checks.")
- public void testSet_authorizer() {
-
- TableResult resPriv = null;
- TableResult resPub = null;
- TableResult emptyTable = new TableResult();
- String insertPublic = "insert into public_table values(1,2)";
- String insertPrivate = "insert into private_table values(1,2)";
- try {
- // prepare, authorizer is not activated yet
- db.exec("create table public_table(c1 integer, c2 integer);", null);
- db.exec("create table private_table(c1 integer, c2 integer);", null);
- // inserts
- db.exec(insertPublic, null);
- db.exec(insertPrivate, null);
- // selects
- resPriv = db.get_table("select * from private_table");
- resPub = db.get_table("select * from public_table");
-
-// db.exec("delete from public_table where 1", null);
-// TableResult emptyPubTable = db.exec("select * from public");
-
- // set Authorizer (positive case): denies private table
- AuthorizerCallback cb = new AuthorizerCallback();
- db.set_authorizer(cb);
- //select
-
- db.exec("select * from private_table", cb);
- assertTrue(cb.wasCalled());
-
- /*
- TableResult res = db.get_table("select * from private_table");
- assertEquals(emptyTable.toString(),res.toString());
- assertFalse(emptyTable.equals(resPriv));
-
- res = db.get_table("select * from public_table");
- assertEquals(resPub,res);
- */
- } catch (Exception e) {
- fail("Error testing authorization: "+e.getMessage());
- }
-
- // Try insert
- try {
- db.exec(insertPublic, null);
- fail("authorization failed");
- } catch (Exception e) {
- try {
- db.exec(insertPrivate, null);
- fail("authorization failed");
- } catch (Exception e1) {
- // ok
- }
- }
-
- }
-
- /**
- * @tests {@link Database#trace(Trace)}
- */
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "trace",
- args = {Trace.class}
- )
- public void testTrace() {
- String stmt = "create table TEST (res double);";
- TestTrace t = new TestTrace();
- assertFalse(t.traceCalled);
- assertEquals(db.last_error(),Constants.SQLITE_OK);
- try {
- db.trace((Trace) t);
- db.exec(stmt,t);
- assertTrue(t.traceCalled);
- assertEquals(t.getTrace(),stmt);
- } catch (Exception e) {
- fail("Error testing traces: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- db.close();
- db.exec(stmt,t);
- fail("Exception Expected");
- } catch (Exception e) {
- //ok
- }
-
-
- }
-
- /**
- * @tests {@link Database#compile(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "compile",
- args = {java.lang.String.class}
- )
- public void testCompileString() {
- try {
- db.compile("select name from sqlite_master;");
- } catch (Exception e) {
- fail("Error compiling sql statement " + e.getMessage());
- e.printStackTrace();
- }
- try {
- db.compile("test");
- fail("Compiling of inaccurate statement does not fail.");
- } catch (Exception e) {
-
- }
- }
-
- /**
- * @tests {@link Database#compile(String, String[])}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "compile",
- args = {java.lang.String.class, java.lang.String[].class}
- )
- public void testCompileStringStringArray() {
- String args[] = new String[1];
- args[0] = "table";
- try {
- db.compile("select name from sqlite_master where type = '%q';",args);
- } catch (Exception e) {
- fail("Error compiling sql statement " + e.getMessage());
- e.printStackTrace();
- }
- try {
- db.compile("test",null);
- fail("Compiling of inaccurate statement does not fail.");
- } catch (Exception e) {
-
- }
- }
-
- /**
- * @tests {@link Database#prepare(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "prepare",
- args = {java.lang.String.class}
- )
- public void testPrepare() {
- Stmt st = null;
- Stmt st2 = null;
- // test empty statement
- try {
- st = db.prepare("");
- assertEquals(0, st.bind_parameter_count());
- st.step();
- fail("stmt should not be prepared");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- // test statement with unbound arguments
- try {
- st2 = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(3, st2.bind_parameter_count());
- assertEquals(3, st2.bind_parameter_index(":three"));
- assertEquals(":two", st2.bind_parameter_name(2));
- } catch (Exception e) {
- fail("error in prepare method: " + e.getMessage());
- e.printStackTrace();
- } finally {
- try {
- st2.close();
- } catch (Exception e) {
- fail("error in prepare method cleanup: " + e.getMessage());
- e.printStackTrace();
- }
- }
-
- try {
- db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values(:one,:two,:three,:four);");
- } catch (Exception e) {
- assertEquals("table " + DatabaseCreator.SIMPLE_TABLE1
- + " has 3 columns but 4 values were supplied", e
- .getMessage());
- }
-
- try {
- db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values(5, '10, 20);");
- } catch (Exception e) {
- assertEquals("unrecognized token: \"'10, 20);\"", e.getMessage());
- }
-
- try {
- db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values(5, 10 20);");
- } catch (Exception e) {
- assertEquals("near \"20\": syntax error", e.getMessage());
- }
-
- }
-
- /**
- * @throws Exception
- * @throws java.lang.Exception
- * @tests {@link Database#open_blob(String, String, String, long, boolean)}
- * unsupported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "open_blob",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, long.class, boolean.class}
- )
- @KnownFailure("not supported")
- public void testOpen_blob() throws Exception, java.lang.Exception {
- Stmt statement2;
- Blob blobInput = new Blob();
-
-
- // Create test input Blob
- InputStream inStream = null;
- byte[] in = {(byte) 1, (byte) 2, (byte) 3, (byte) 4};
-
- // setup test input
- db.exec("create table TEST (res blob)",null);
- inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c");
- assertNotNull(inStream);
-
-
- // insert byte array in db
- try {
- statement2 = db.prepare("insert into TEST(res) values (?)");
- statement2.bind(1, in);
- statement2.step();
- statement2.close();
- } catch (Exception e) {
- fail("Error happened inserting blob" + e.getMessage());
- e.printStackTrace();
- }
-
- // read from db
- byte[] output = null;
- Blob blob;
-
- blob = db.open_blob(dbFile.getPath(), "TEST", "res", 1, true);
- if (blob == null) {
- fail("Blob could not be retrieved");
- }
- //read from blob and compare values (positive case)
- InputStream is = blob.getInputStream();
-
- int i = 0;
- int outByte = 0;
- byte[] out = new byte[4];
- while ((outByte = is.read()) > -1) {
- out[i] = (byte) outByte;
- i++;
- }
- is.close();
-
- blob.close();
-
- assertTrue(Arrays.equals(in, out));
-
- //read from blob and compare values (default blob)
- db.exec("insert into TEST values(zeroblob(128))", null);
- Blob blob2 = db.open_blob(dbFile.getPath(), "TEST", "res", 2, true);
- is = blob2.getInputStream();
- for (i = 0; i < 128; i++) {
- assertEquals(0, is.read());
- }
- is.close();
- }
-
- /**
- * @tests {@link Database#is3()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "is3",
- args = {}
- )
- public void testIs3() {
- int ver = Integer.parseInt(db.version().substring(0,1));
- if (db.is3()) {
- assertTrue( ver == 3);
- } else {
- assertTrue(ver != 3);
- }
- }
-
- /**
- * @tests {@link Database#progress_handler(int, ProgressHandler)}
- */
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "progress_handler",
- args = {int.class, ProgressHandler.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "progress",
- clazz = ProgressHandler.class,
- args = {}
- )
- })
- public void testProgress_handler() {
- int inputVal = 3;
- TestProgressHandler prog = new TestProgressHandler();
- try {
- db.exec("create table TEST5(id integer, firstname text, lastname text)",null);
- Vm vm = db.compile("select * from TEST5; "
- + "insert into TEST5 values(3, 'James', 'Bond'); "
- + "delete from TEST5 where id = 3; "
- + "select * from TEST5");
- int stmt = 0;
- do {
- ++stmt;
- if (stmt > inputVal) {
- db.progress_handler(inputVal, prog);
- } else {
- assertEquals(0, prog.getCounts());
- }
- while (vm.step(prog)) {
- }
- } while (vm.compile());
- assertEquals(inputVal,prog.getCounts());
- } catch (Exception e) {
- fail("Error in test setup: "+e.getMessage());
- e.printStackTrace();
- }
-
- // Boundary value test
- inputVal = 0;
- TestProgressHandler progBoundary = new TestProgressHandler();
- db.progress_handler(inputVal, progBoundary);
- try {
- Vm vm2 = db.compile("select * from TEST5; "
- + "insert into TEST5 values(3, 'James', 'Bond'); "
- + "delete from TEST5 where id = 3; "
- + "select * from TEST5");
- do {
- vm2.step(progBoundary);
- } while (vm2.compile());
- assertEquals(inputVal, progBoundary.getCounts());
- }catch (Exception e) {
- fail("Error in test setup: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- db.exec("drop table TEST5",null);
- } catch (Exception e) {
- System.out.println(e.getMessage());
- e.printStackTrace();
- }
- }
-
-
-
- class SinFunc implements Function {
-
-
- public void function(FunctionContext fc, String args[]) {
- Double d = new Double(args[0]);
- fc.set_result(Math.sin(d.doubleValue()));
- }
-
- public void last_step(FunctionContext fc) {
- // TODO Auto-generated method stub
-
- }
-
- public void step(FunctionContext fc, String[] args) {
- // TODO Auto-generated method stub
-
- }
- }
-
- @TestTargetClass(Trace.class)
- class TestTrace implements Trace,Callback {
-
- private StringBuffer buf = new StringBuffer();
-
- public boolean traceCalled = false;
-
- public String getTrace() {
- return buf.toString();
- }
-
- public void trace(String stmt) {
- traceCalled = true;
- buf.append(stmt);
- }
-
- public void columns(String[] coldata) {
- // TODO Auto-generated method stub
-
- }
-
- public boolean newrow(String[] rowdata) {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void types(String[] types) {
- // TODO Auto-generated method stub
-
- }
- }
-
- @TestTargetClass(Authorizer.class)
- class AuthorizerCallback implements Authorizer,Callback {
- private boolean isAuthorizing = false;
-
- public boolean wasCalled() {
- return isAuthorizing;
- }
-
- public int authorize(int action, String arg1, String arg2, String arg3,
- String arg4) {
- Logger.global.info("DB authorization callback "+action+" "+arg1+" "+arg2+" "+arg3+" "+arg4+" ");
- this.isAuthorizing = true;
- if (action != Constants.SQLITE_SELECT || arg1.contains("private_table")) {
- return Constants.SQLITE_DENY;
- } else {
- return Constants.SQLITE_OK;
- }
- }
-
- public void columns(String[] coldata) {
- // TODO Auto-generated method stub
-
- }
-
- public boolean newrow(String[] rowdata) {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void types(String[] types) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- class TestBusyHandler implements BusyHandler, Callback {
-
- public boolean busy(String table, int count) {
- System.out.println("BUSY!");
- return true;
- }
-
- public void columns(String[] coldata) {
- // TODO Auto-generated method stub
-
- }
-
- public boolean newrow(String[] rowdata) {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void types(String[] types) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- class TestProgressHandler implements ProgressHandler,Callback {
-
- private boolean progressed = false;
-
- private int counter = 0;
-
- public boolean isProgressed() {
- return progressed;
- }
-
- public int getCounts() {
- return counter;
- }
-
- public boolean progress() {
- this.progressed = true;
- counter++;
- return true;
- }
-
- public void columns(String[] coldata) {
- // TODO Auto-generated method stub
-
- }
-
- public boolean newrow(String[] rowdata) {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void types(String[] types) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
-// class dbBusyThread implements Runnable {
-//
-// String dbName = "sqliteTest.db";
-//
-// Thread runner;
-// public dbBusyThread() {
-// }
-// public dbBusyThread(String threadName) {
-// runner = new Thread(this, threadName); // (1) Create a new thread.
-// System.out.println(runner.getName());
-// runner.start(); // (2) Start the thread.
-// }
-// public void run() {
-// insert(3000);
-// }
-//
-// public void runNoDelay() {
-// insert(0);
-// }
-//
-// synchronized private void insert(long delay) {
-// Database db2 = new Database();
-// try {
-// db2.open(dbName, 0);
-// db2.exec("insert into TEST5 values (4,'Anglina','Jolie');",
-// null);
-// wait(delay);
-// } catch (Exception e) {
-// System.out.println("Error in Thread " + e.getMessage());
-// e.printStackTrace();
-// } catch (InterruptedException e2) {
-// System.out.println("Error in Thread " + e2.getMessage());
-// e2.printStackTrace();
-// } finally {
-// try {
-// db2.close();
-// } catch (Exception e) {
-// // We do not handle this case
-// }
-// }
-// }
-// }
-
- /**
- * This method creates a Runnable that executes insert operation for the
- * first table
- */
- private static Runnable createTask2Interrupt(final int id,
- final String dbName, final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- Database db = new Database();
- try {
- String value = DatabaseCreator.defaultString + id;
-
- db.open(dbName, 0);
- String insertQuery = "INSERT INTO "
- + DatabaseCreator.TEST_TABLE1
- + " (id, field1, field2, field3) VALUES(" + id
- + ", '" + value + "', " + id + ", " + id + ")";
- db.exec(insertQuery, null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
- try {
- db.interrupt();
- db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1
- + " WHERE id=" + id, null);
- } catch (Exception e1) {
- errorTracker.registerException(this, e1);
- }
- }
- }
- };
- }
-
- /**
- * This method creates a Runnable that executes delete operation for the
- * first table
- */
- private static Runnable createTask1(final int id,final String dbName, final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- try {
- Database db = new Database();
- db.open(dbName, 0);
- db.exec("DELETE FROM "
- + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id,null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
- }
- }
- };
- }
-
- /**
- * This method creates a Runnable that executes insert operation for the
- * first table
- */
- private static Runnable createTask2(final int id, final String dbName, final ErrorTracker errorTracker ) {
- return new Runnable() {
- public void run() {
- try {
- String value = DatabaseCreator.defaultString + id;
- Database db = new Database();
- db.open(dbName, 0);
- String insertQuery = "INSERT INTO "
- + DatabaseCreator.TEST_TABLE1
- + " (id, field1, field2, field3) VALUES(" + id
- + ", '" + value + "', " + id + ", " + id + ")";
- db.exec(insertQuery,null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
-
- }
- }
- };
- }
-
- /**
- * This method creates a Runnable that executes update operation for the one
- * record of the first table
- */
- private static Runnable createTask3(final int oldID, final String dbName,
- final int newID, final ErrorTracker errorTracker) {
- return new Runnable() {
- public void run() {
- Database db = new Database();
- try {
- db.open(dbName, 0);
- String value = DatabaseCreator.defaultString + newID;
- String updateQuery = "UPDATE "
- + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID
- + ", field1='" + value + "', field2=" + newID
- + ", field3=" + newID + " WHERE id=" + oldID;
- db.exec(updateQuery, null);
- } catch (Exception e) {
- errorTracker.registerException(this, e);
- }
- }
- };
- }
-
- private class ErrorTracker {
- private List<String> errors = new ArrayList<String>();
-
- public void registerException(Runnable runnable, Exception e) {
- System.out.println("Registered: "+e.getMessage());
- errors.add(e.getMessage());
- }
-
- public List<String> getErrors() {
- return errors;
- }
-
- public void reset() {
- errors.clear();
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java b/luni/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java
deleted file mode 100644
index 89fb77b..0000000
--- a/luni/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java
+++ /dev/null
@@ -1,110 +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.SQLite;
-
-import SQLite.Exception;
-import SQLite.JDBCDriver;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.SQLException;
-
-
-/**
- * Tests the SQLite.JDBCDriver.
- */
-@TestTargetClass(JDBCDriver.class)
-public class JDBCDriverFunctionalTest extends AbstractSqlTest {
-
-
-
- /**
- * The SQLite db file.
- */
- private File dbFile = null;
-
- private String connectionURL = "empty";
-
- /**
- * Sets up an unit test by loading the SQLite.JDBCDriver, getting two
- * connections and calling the setUp method of the super class.
- * @throws Exception
- * @throws IllegalAccessException
- * @throws InstantiationException
- * @throws Exception
- * @throws Exception
- * @throws Exception
- * @throws Exception
- * @throws Exception
- */
- @Override
- public void setUp() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, Exception { // the Exception class needs to be fully
- // qualified since there is an Exception
- // class in the SQLite package.
-
- super.setUp();
- }
-
- /**
- * Tears down an unit test by calling the tearDown method of the super class
- * and deleting the SQLite test db file.
- */
- @Override
- protected void tearDown() throws SQLException {
- super.tearDown();
- dbFile.delete();
- }
-
-
- @Override
- protected String getConnectionURL() {
- if (connectionURL.equals("empty")) {
- String tmp = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(tmp);
- if (tmpDir.isDirectory()) {
- try {
- dbFile = File.createTempFile("JDBCDriverFunctionalTest",
- ".db", tmpDir);
- } catch (IOException e) {
- System.err.println("error creating temporary DB file.");
- }
- dbFile.deleteOnExit();
- } else {
- System.err.println("java.io.tmpdir does not exist");
- }
-
- connectionURL = "jdbc:sqlite:/" + dbFile.getPath();
-
- }
-
- return connectionURL;
- }
-
- @Override
- protected String getDriverClassName() {
- return "SQLite.JDBCDriver";
- }
-
- @Override
- protected int getTransactionIsolation() {
- return Connection.TRANSACTION_SERIALIZABLE;
- }
-
-
-}
diff --git a/luni/src/test/java/tests/SQLite/JDBCDriverTest.java b/luni/src/test/java/tests/SQLite/JDBCDriverTest.java
deleted file mode 100644
index aac8f16..0000000
--- a/luni/src/test/java/tests/SQLite/JDBCDriverTest.java
+++ /dev/null
@@ -1,272 +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 tests.SQLite;
-
-import SQLite.Exception;
-import SQLite.JDBCDriver;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.DriverPropertyInfo;
-import java.sql.SQLException;
-
-
-@TestTargetClass(JDBCDriver.class)
-public class JDBCDriverTest extends JDBCDriverFunctionalTest {
-
- /**
- * The SQLite db file.
- */
- private JDBCDriver jDriver;
-
- private Driver returnedDriver;
-
- public void setUp() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, Exception {
-
- try {
- super.setUp();
- returnedDriver = DriverManager.getDriver(getConnectionURL());
- if (returnedDriver instanceof JDBCDriver) {
- this.jDriver = (JDBCDriver) returnedDriver;
- }
- } catch (SQLException e) {
- System.out.println("Cannot get driver");
- e.printStackTrace();
- } catch (Exception e) {
- System.out.println("DB Setup failed");
- e.printStackTrace();
- }
- }
-
- /**
- * @tests JDBCDriver#JDBCDriver()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "constructor test",
- method = "JDBCDriver",
- args = {}
- )
- public void testJDBCDriver() {
- assertTrue(returnedDriver instanceof JDBCDriver);
- }
-
- /**
- * @tests JDBCDriver#acceptsURL(String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "constructor test",
- method = "acceptsURL",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "constructor test",
- // we have to list the Driver target explicitly, since SQLite
- // is not part of the target packages
- clazz = Driver.class,
- method = "acceptsURL",
- args = {java.lang.String.class}
- )
- })
- public void testAcceptsURL() {
- try {
- if (this.jDriver != null) {
- assertTrue(jDriver.acceptsURL(getConnectionURL()));
- } else {
- fail("no Driver available");
- }
- } catch (SQLException e) {
- fail("Driver does not accept URL");
- e.printStackTrace();
- }
- }
-
- /**
- * @tests JDBCDriver#connect(String, java.util.Properties)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "connect",
- args = {java.lang.String.class, java.util.Properties.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- // we have to list the Driver target explicitly, since SQLite
- // is not part of the target packages
- clazz = Driver.class,
- notes = "method test",
- method = "connect",
- args = {java.lang.String.class, java.util.Properties.class}
- )
- })
- public void testConnect() {
- try {
- if (this.jDriver != null) {
- Connection c = jDriver.connect(getConnectionURL(), null);
- assertFalse(c.isClosed());
- DriverManager.getConnection(getConnectionURL());
- } else {
- fail("no Driver available");
- }
- } catch (SQLException e) {
- fail("Driver does not connect");
- e.printStackTrace();
- }
- }
-
- /**
- * @tests JDBCDriver#getMajorVersion()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "getMajorVersion",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- // we have to list the Driver target explicitly, since SQLite
- // is not part of the target packages
- clazz = Driver.class,
- notes = "method test",
- method = "getMajorVersion",
- args = {}
- )
- })
- public void testGetMajorVersion() {
- if (this.jDriver != null) {
- assertTrue(jDriver.getMajorVersion() > 0);
- } else {
- fail("no Driver available");
- }
- }
-
- /**
- * @tests JDBCDriver#getMinorVersion()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "getMinorVersion",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- // we have to list the Driver target explicitly, since SQLite
- // is not part of the target packages
- clazz = Driver.class,
- method = "getMinorVersion",
- args = {}
- )
- })
- public void testGetMinorVersion() {
- if (this.jDriver != null) {
- assertTrue(jDriver.getMinorVersion() > 0);
- } else {
- fail("no version information available");
- }
- }
-
- /**
- * @tests JDBCDriver#getPropertyInfo(String, java.util.Properties)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "getPropertyInfo",
- args = {java.lang.String.class, java.util.Properties.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- // we have to list the Driver target explicitly, since SQLite
- // is not part of the target packages
- clazz = Driver.class,
- method = "getPropertyInfo",
- args = {java.lang.String.class, java.util.Properties.class}
- )
- })
- public void testGetPropertyInfo() {
- DriverPropertyInfo[] info = null;
- try {
- if (this.jDriver != null) {
- info = jDriver.getPropertyInfo(getConnectionURL(), null);
- assertNotNull(info);
- assertTrue(info.length > 0);
- } else {
- fail("no Driver available");
- }
- } catch (SQLException e) {
- fail("Driver property details not available");
- e.printStackTrace();
- }
-
- assertNotNull(info);
-
- }
-
- /**
- * @tests JDBCDriver#jdbcCompliant()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "jdbcCompliant",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- // we have to list the Driver target explicitly, since SQLite
- // is not part of the target packages
- clazz = Driver.class,
- notes = "method test",
- method = "jdbcCompliant",
- args = {}
- )
- })
- public void testJdbcCompliant() {
- if (this.jDriver != null) {
- assertFalse(jDriver.jdbcCompliant());
- } else {
- fail("no version information available");
- }
- }
- /**
- * Tears down an unit test by calling the tearDown method of the super class
- * and deleting the SQLite test db file.
- */
- @Override
- protected void tearDown() throws SQLException {
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/tests/SQLite/ShellTest.java b/luni/src/test/java/tests/SQLite/ShellTest.java
deleted file mode 100644
index f0f4f7c..0000000
--- a/luni/src/test/java/tests/SQLite/ShellTest.java
+++ /dev/null
@@ -1,147 +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 tests.SQLite;
-
-import SQLite.Shell;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.io.PrintStream;
-import java.io.PrintWriter;
-
-@TestTargetClass(Shell.class)
-public class ShellTest extends TestCase {
-
- /**
- * Test method for {@link SQLite.Shell#Shell(java.io.PrintWriter, java.io.PrintWriter)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "Shell",
- args = {PrintWriter.class, PrintWriter.class}
- )
- public void testShellPrintWriterPrintWriter() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link SQLite.Shell#Shell(java.io.PrintStream, java.io.PrintStream)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "Shell",
- args = {PrintStream.class, PrintStream.class}
- )
- public void testShellPrintStreamPrintStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link SQLite.Shell#clone()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void testClone() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link SQLite.Shell#sql_quote_dbl(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "sql_quote_dbl",
- args = {String.class}
- )
- public void testSql_quote_dbl() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link SQLite.Shell#sql_quote(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "sql_quote",
- args = {String.class}
- )
- public void testSql_quote() {
- fail("Not yet implemented");
- }
-
-
- /**
- * Test method for {@link SQLite.Shell#columns(java.lang.String[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "columns",
- args = {String[].class}
- )
- public void testColumns() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link SQLite.Shell#types(java.lang.String[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "types",
- args = {String[].class}
- )
- public void testTypes() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link SQLite.Shell#newrow(java.lang.String[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "newrow",
- args = {String[].class}
- )
- public void testNewrow() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "main",
- args = {String[].class}
- )
- public void testMain() {
-
- }
-
-}
diff --git a/luni/src/test/java/tests/SQLite/StmtTest.java b/luni/src/test/java/tests/SQLite/StmtTest.java
deleted file mode 100644
index 1dc8552..0000000
--- a/luni/src/test/java/tests/SQLite/StmtTest.java
+++ /dev/null
@@ -1,1250 +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 tests.SQLite;
-
-import SQLite.Constants;
-import SQLite.Database;
-import SQLite.Exception;
-import SQLite.Stmt;
-import SQLite.TableResult;
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-
-import tests.support.DatabaseCreator;
-import tests.support.Support_SQL;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-
-@TestTargetClass(Stmt.class)
-public class StmtTest extends SQLiteTest {
-
- private static Database db = null;
-
- private static Stmt st = null;
-
- private static final String createAllTypes =
- "create table type (" +
-
- " BoolVal BOOLEAN," + " IntVal INT," + " LongVal LONG,"
- + " Bint BIGINT," + " Tint TINYINT," + " Sint SMALLINT,"
- + " Mint MEDIUMINT, " +
-
- " IntegerVal INTEGER, " + " RealVal REAL, "
- + " DoubleVal DOUBLE, " + " FloatVal FLOAT, "
- + " DecVal DECIMAL, " +
-
- " NumVal NUMERIC, " + " charStr CHAR(20), "
- + " dateVal DATE, " + " timeVal TIME, " + " TS TIMESTAMP, "
- +
-
- " DT DATETIME, " + " TBlob TINYBLOB, " + " BlobVal BLOB, "
- + " MBlob MEDIUMBLOB, " + " LBlob LONGBLOB, " +
-
- " TText TINYTEXT, " + " TextVal TEXT, "
- + " MText MEDIUMTEXT, " + " LText LONGTEXT, " +
-
- " MaxLongVal BIGINT, MinLongVal BIGINT, "+
-
- " validURL URL, invalidURL URL "+
-
- ");";
-
- static final String insertAllTypes =
- "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
- + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
- + "NumVal, charStr, dateVal, timeVal, TS,"
- + "DT, TBlob, BlobVal, MBlob, LBlob,"
- + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal,"
- + " validURL, invalidURL"
- + ") "
- + "values (1, -1, 22, 2, 33,"
- + "3, 1, 2, 3.9, 23.2, 33.3, 44,"
- + "5, 'test string', '1799-05-26', '12:35:45', '2007-10-09 14:28:02.0',"
- + "'1221-09-22 10:11:55', 1, 2, 3, 4,"
- + "'Test text message tiny', 'Test text',"
- + " 'Test text message medium', 'Test text message long', "
- + Long.MAX_VALUE+", "+Long.MIN_VALUE+", "
- + "null, null "+
- ");";
-
- static final String allTypesTable = "type";
-
- public void setUp() throws java.lang.Exception {
- super.setUp();
- Support_SQL.loadDriver();
- db = new Database();
- db.open(dbFile.getPath(), 0);
- db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null);
- DatabaseCreator.fillSimpleTable1(conn);
-
- }
-
- public void tearDown() {
- if (st != null) {
- try {
- st.close();
- } catch (Exception e) {
-
- }
- }
- try {
- db.close();
- Connection con = Support_SQL.getConnection();
- con.close();
-// dbFile.delete();
- } catch (Exception e) {
- fail("Exception in tearDown: "+e.getMessage());
- } catch (SQLException e) {
- fail("SQLException in tearDown: "+e.getMessage());
- }
- super.tearDown();
- }
-
- /**
- * @tests {@link Stmt#Stmt()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "constructor test",
- method = "Stmt",
- args = {}
- )
- public void testStmt() {
- Stmt st = new Stmt();
- assertNotNull(st);
- try {
- Stmt actual = db.prepare("");
- assertNotNull(st);
- // no black box test assertEquals(actual.error_code,st.error_code);
- } catch (Exception e) {
- fail("Statement setup fails: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.step();
- fail("Cannot execute non prepared Stmt");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#finalize()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "method test",
- method = "finalize",
- args = {}
- )
- public void testFinalize() {
-
- }
-
- /**
- * @tests {@link Stmt#prepare()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "prepare",
- args = {}
- )
- public void testPrepare() {
- try {
- st = db.prepare("");
- st.prepare();
- fail("statement is closed");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- try {
- st = new Stmt();
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- assertFalse(st.prepare());
- st = new Stmt();
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertFalse(st.prepare());
- st = new Stmt();
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.bind(1, 1);
- st.bind(2, 10);
- st.bind(3, 30);
- assertFalse(st.prepare());
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1
- + "; " + "delete from " + DatabaseCreator.SIMPLE_TABLE1
- + " where id = 5; " + "insert into "
- + DatabaseCreator.SIMPLE_TABLE1 + " values(5, 10, 20); "
- + "select * from " + DatabaseCreator.SIMPLE_TABLE1 + ";");
- assertTrue(st.prepare());
- assertTrue(st.prepare());
- assertTrue(st.prepare());
- assertFalse(st.prepare());
- } catch (Exception e) {
- fail("statement should be ready for execution: "
- + e.getMessage());
- e.printStackTrace();
- }
- }
-
- /**
- * @tests {@link Stmt#step()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "step",
- args = {}
- )
- public void testStep() {
- try {
- st.step();
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- try {
- st = new Stmt();
- st = db.prepare("select name from sqlite_master where type = 'table'");
- st.step();
- } catch (Exception e) {
- fail("test fails");
- }
-
- }
-
- /**
- * @tests {@link Stmt#close()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "close",
- args = {}
- )
- public void testClose() {
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.close();
- } catch (Exception e) {
- fail("Test fails");
- e.printStackTrace();
- }
-
- try {
- st.step();
- fail("Test fails");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#reset()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "reset",
- args = {}
- )
- public void testReset() throws Exception {
- db.exec("create table TEST (res integer not null)", null);
-
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, 1);
- st.step();
-
- // verify that parameter is still bound
- st.reset();
- assertEquals(1,st.bind_parameter_count());
- st.step();
-
- TableResult count = db.get_table("select count(*) from TEST where res=1", null);
-
- String[] row0 = (String[]) count.rows.elementAt(0);
- assertEquals(2, Integer.parseInt(row0[0]));
- }
-
- /**
- * @tests {@link Stmt#clear_bindings()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported",
- method = "clear_bindings",
- args = {}
- )
- public void testClear_bindings() {
- try {
- st.clear_bindings();
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
- }
-
- /**
- * @tests {@link Stmt#bind(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind",
- args = {int.class, int.class}
- )
- public void testBindIntInt() {
- try {
- int input = 0;
- int maxVal = Integer.MAX_VALUE;
- int minVal = Integer.MIN_VALUE;
-
- db.exec("create table TEST (res integer)", null);
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, input);
- st.step();
-
- st.reset();
- st.bind(1,maxVal);
- st.step();
-
- st.reset();
- st.bind(1,minVal);
- st.step();
-
- TableResult r = db.get_table("select * from TEST");
-
- String[] row0 = (String[]) r.rows.elementAt(0);
- assertEquals(input,Integer.parseInt(row0[0]));
-
- String[] row1 = (String[]) r.rows.elementAt(1);
- assertEquals(maxVal,Integer.parseInt(row1[0]));
-
- String[] row2 = (String[]) r.rows.elementAt(2);
- assertEquals(minVal,Integer.parseInt(row2[0]));
-
- } catch (Exception e) {
- fail("Error in test setup: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.close();
- st.bind(1,Integer.MIN_VALUE);
- fail("Exception expected");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#bind(int, long)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind",
- args = {int.class, long.class}
- )
- public void testBindIntLong() {
- try {
- long input = 0;
- long maxVal = Long.MAX_VALUE;
- long minVal = Long.MIN_VALUE;
-
- db.exec("create table TEST (res long)", null);
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, input);
- st.step();
-
- st.reset();
- st.bind(1,maxVal);
- st.step();
-
- st.reset();
- st.bind(1,minVal);
- st.step();
-
- TableResult r = db.get_table("select * from TEST");
-
- String[] row0 = (String[]) r.rows.elementAt(0);
- assertEquals(input,Long.parseLong(row0[0]));
-
- String[] row1 = (String[]) r.rows.elementAt(1);
- assertEquals(maxVal,Long.parseLong(row1[0]));
-
- String[] row2 = (String[]) r.rows.elementAt(2);
- assertEquals(minVal,Long.parseLong(row2[0]));
-
- } catch (Exception e) {
- fail("Error in test setup: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.close();
- st.bind(1,Long.MIN_VALUE);
- fail("Exception expected");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#bind(int, double)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind",
- args = {int.class, double.class}
- )
- public void testBindIntDouble() {
- try {
- double input = 0.0;
- double maxVal = Double.MAX_VALUE;
- double minVal = Double.MIN_VALUE;
- double negInf = Double.NEGATIVE_INFINITY;
- double posInf = Double.POSITIVE_INFINITY;
- double nan = Double.NaN;
-
- db.exec("create table TEST (res double)", null);
- st = db.prepare("insert into TEST values (:one);");
- st.bind(1, input);
- st.step();
-
- st.reset();
- st.bind(1, maxVal);
- st.step();
-
- st.reset();
- st.bind(1, minVal);
- st.step();
-
- st.reset();
- st.bind(1, negInf);
- st.step();
-
- st.reset();
- st.bind(1, posInf);
- st.step();
-
- st.reset();
- st.bind(1, nan);
- st.step();
-
-
- TableResult r = db.get_table("select * from TEST");
-
- String[] row0 = (String[]) r.rows.elementAt(0);
- assertTrue(Double.compare(input, Double.parseDouble(row0[0])) == 0);
-
- String[] row1 = (String[]) r.rows.elementAt(1);
- assertFalse(Double.compare(maxVal, Double.parseDouble(row1[0])) == 0);
- assertTrue(Double.compare(maxVal, Double.parseDouble(row1[0])) < 0);
- assertTrue(Double.isInfinite(Double.parseDouble(row1[0])));
-
- String[] row2 = (String[]) r.rows.elementAt(2);
- assertTrue(Double.compare(minVal, Double.parseDouble(row2[0])) == 0);
-
- String[] row3 = (String[]) r.rows.elementAt(3);
- assertEquals("Double.NEGATIVE_INFINITY SQLite representation",
- "-Inf", row3[0]);
-
- String[] row4 = (String[]) r.rows.elementAt(4);
- assertEquals("Double.POSITIVE_INFINITY SQLite representation",
- "Inf", row4[0]);
-
- String[] row5 = (String[]) r.rows.elementAt(4);
- assertEquals("Double.Nan SQLite representation", "Inf", row5[0]);
-
- } catch (Exception e) {
- fail("Error in test setup: " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.close();
- st.bind(1,0.0);
- fail("Exception expected");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#bind(int, byte[])}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {int.class, byte[].class}
- )
- public void testBindIntByteArray() {
-
- String name = "Hello World";
-
- try {
- byte[] b = new byte[name.getBytes().length];
- b = name.getBytes();
- String stringInHex = "";
-
- db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
- st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
- + " values (:one, :two);");
- st.bind(1, 2);
- st.bind(2, b);
- st.step();
-
- //compare what was stored with input based on Hex representation
- // since type of column is CHAR
- TableResult r = db.get_table("select * from "
- + DatabaseCreator.PARENT_TABLE);
- String[] row = (String[]) r.rows.elementAt(0);
-
- for (byte aByte : b) {
- stringInHex += Integer.toHexString(aByte);
- }
- stringInHex = "X'" + stringInHex + "'";
- assertTrue(stringInHex.equalsIgnoreCase(row[1]));
-
- } catch (Exception e) {
- fail("Error in test setup: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.close();
- st.bind(1,name.getBytes());
- fail("Exception expected");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#bind(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind",
- args = {int.class, java.lang.String.class}
- )
- public void testBindIntString() {
- String name = "Hello World";
-
- try {
-
- db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
- st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
- + " values (:one, :two);");
- st.bind(1, 2);
- st.bind(2, name);
- st.step();
-
- TableResult r = db.get_table("select * from "
- + DatabaseCreator.PARENT_TABLE);
- String[] row = (String[]) r.rows.elementAt(0);
- assertEquals(name,row[1]);
-
- } catch (Exception e) {
- fail("Error in test setup: "+e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.close();
- st.bind(1,name);
- fail("Exception expected");
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#bind(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind",
- args = {int.class}
- )
- public void testBindInt() {
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- st.bind(4);
- st.bind(1, 4);
- st.bind(2, 10);
- st.bind(3, 30);
- st.step();
- fail("Test failes");
- } catch (Exception e) {
- // What happens if null is bound to non existing variable position
- assertEquals("parameter position out of bounds" , e.getMessage());
- }
-
- // functional tests
-
- try {
- st.reset();
- st.bind(1);
- st.bind(2, 10);
- st.bind(3, 30);
- st.step();
- fail("Test failes");
- } catch (Exception e) {
- // What happens if null is bound to NON NULL field
- assertEquals("SQL logic error or missing database", e.getMessage());
- }
-
- try {
- st.reset();
- st.bind(1, 3);
- st.bind(2);
- st.bind(3, 30);
- st.step();
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- }
-
- }
-
- /**
- * @tests {@link Stmt#bind_zeroblob(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "bind_zeroblob",
- args = {int.class, int.class}
- )
- public void testBind_zeroblob() {
- try {
- st.bind_zeroblob(1, 128);
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
- }
-
- /**
- * @tests {@link Stmt#bind_parameter_count()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind_parameter_count",
- args = {}
- )
- public void testBind_parameter_count() {
- try {
- st.bind_parameter_count();
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(3, st.bind_parameter_count());
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (?, ?, ?)");
- assertEquals(3, st.bind_parameter_count());
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- assertEquals(0, st.bind_parameter_count());
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.close();
- st.bind_parameter_count();
- fail("Exception expected");
- } catch (Exception e) {
- //ok
- }
-
- }
-
- /**
- * @tests {@link Stmt#bind_parameter_name(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind_parameter_name",
- args = {int.class}
- )
- public void testBind_parameter_name() {
- try {
- st.bind_parameter_name(1);
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(":one", st.bind_parameter_name(1));
- assertEquals(":two", st.bind_parameter_name(2));
- assertEquals(":three", st.bind_parameter_name(3));
- String name = st.bind_parameter_name(4);
- } catch (Exception e) {
- assertEquals("parameter position out of bounds",e.getMessage());
- }
- }
-
- /**
- * @tests {@link Stmt#bind_parameter_index(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "bind_parameter_index",
- args = {java.lang.String.class}
- )
- public void testBind_parameter_index() {
-
- try {
- st.bind_parameter_index("");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("stmt already closed", e.getMessage());
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(3, st.bind_parameter_index(":three"));
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- assertEquals(0, st.bind_parameter_index(":t"));
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (?, ?, ?)");
- assertEquals(0, st.bind_parameter_index("?"));
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column_int(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "column_int",
- args = {int.class}
- )
- public void testColumn_int() throws Exception {
- db.exec(createAllTypes, null);
- db.exec(insertAllTypes, null);
-
- int columnObjectCastFromLong;
- Object columnObject = null;
- int intColumn = 0;
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
-
- st = db.prepare(selectStmt);
- st.step();
- // select 'speed' value
- columnObject = st.column(1);
- intColumn = st.column_int(1);
- assertNotNull(intColumn);
-
- assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
- int stSpeed = Integer.parseInt(columnObject.toString());
- assertNotNull(stSpeed);
- assertEquals( intColumn, stSpeed);
- assertEquals(10,stSpeed);
-
- selectStmt = "select TextVal from "+allTypesTable;
-
- st = db.prepare(selectStmt);
- st.step();
- // select double value
- try {
- st.column_int(0);
- } catch (Exception e) {
- //ok
- }
- }
-
- /**
- * @tests {@link Stmt#column_long(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "column_long",
- args = {int.class}
- )
- public void testColumn_long() {
- Object columnObject = null;
- int columnObjectCastFromLong;
- long longColumn = 0;
- try {
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- st = db.prepare(selectStmt);
- st.step();
- columnObject = st.column(1);
- longColumn = st.column_long(1);
- assertNotNull(longColumn);
- // column declared as integer
- assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
- int stSpeed = Integer.parseInt(columnObject.toString());
- assertNotNull(stSpeed);
- assertEquals( longColumn, stSpeed);
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- st.column_long(4);
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals( "column out of bounds" , e.getMessage());
- }
-
- try {
- st.column_long(-1);
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals( "column out of bounds" , e.getMessage());
- }
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column_double(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "column_double",
- args = {int.class}
- )
- public void testColumn_double() throws Exception {
- db.exec(createAllTypes, null);
- db.exec(insertAllTypes, null);
-
- Object columnObject = null;
- double doubleColumn = 0;
- double actualVal = 23.2;
- String selectStmt = "select DoubleVal from "+allTypesTable;
-
- st = db.prepare(selectStmt);
- st.step();
- // select double value
- doubleColumn = st.column_double(0);
- assertNotNull(doubleColumn);
-
- assertTrue("DOUBLE".equalsIgnoreCase(st.column_decltype(0)));
- assertNotNull(doubleColumn);
- assertEquals( actualVal, doubleColumn);
-
- // Exception test
- selectStmt = "select dateVal from "+allTypesTable;
-
- st = db.prepare(selectStmt);
- st.step();
- // select double value
- try {
- st.column_double(0);
- } catch (Exception e) {
- //ok
- }
-
-
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column_bytes(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "column_bytes",
- args = {int.class}
- )
- public void testColumn_bytes() throws Exception {
-
- db.exec("create table B(id integer primary key, val blob)",null);
- db.exec("insert into B values(1, zeroblob(128))", null);
- st = db.prepare("select val from B where id = 1");
- assertTrue(st.step());
- try {
- st.column_bytes(0);
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column_string(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "column_string",
- args = {int.class}
- )
- public void testColumn_string() throws Exception {
- db.exec(createAllTypes, null);
- db.exec(insertAllTypes, null);
-
- Object columnObject = null;
- String stringColumn = "";
- String actualVal = "test string";
- String selectStmt = "select charStr from "+allTypesTable;
-
- st = db.prepare(selectStmt);
- st.step();
- // select string value
- stringColumn = st.column_string(0);
- assertNotNull(stringColumn);
-
- assertTrue("CHAR(20)".equalsIgnoreCase(st.column_decltype(0)));
- assertNotNull(stringColumn);
- assertEquals( actualVal, stringColumn);
-
- // Exception test
- selectStmt = "select DoubleVal from "+allTypesTable;
-
- st = db.prepare(selectStmt);
- st.step();
- // select double value
- try {
- st.column_string(0);
- } catch (Exception e) {
- //ok
- }
- }
-
- public void testColumn_type() throws Exception {
- db.exec(createAllTypes, null);
- db.exec(insertAllTypes, null);
- st = db.prepare("select * from " + allTypesTable);
- st.step();
-
- // Exception test
- try {
- st.column_type(100);
- } catch (Exception e) {
- // ok
- }
-
- /*
- Dictionary
-
- public static final int SQLITE_INTEGER = 1;
- public static final int SQLITE_FLOAT = 2;
- public static final int SQLITE_BLOB = 4;
- public static final int SQLITE_NULL = 5;
- public static final int SQLITE3_TEXT = 3;
- public static final int SQLITE_NUMERIC = -1;
- */
-
- assertEquals(Constants.SQLITE3_TEXT, st.column_type(23)); // ok TEXT
- assertEquals(Constants.SQLITE3_TEXT, st.column_type(13)); // CHAR(20)
-
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(8));
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(9));
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(10)); // FLOAT
-
- for (int i = 0; i < 8; i++) {
- assertEquals("Expected Integer at position " + i,
- Constants.SQLITE_INTEGER, st.column_type(i));
- }
-
- assertEquals(Constants.SQLITE_NULL, st.column_type(28));
- assertEquals(Constants.SQLITE_NULL, st.column_type(29));
-
- // Failing tests
- assertTrue("INTEGER".equalsIgnoreCase(st.column_decltype(12)));
- assertEquals(Constants.SQLITE_INTEGER, st.column_type(12));
-
- assertTrue("FLOAT".equalsIgnoreCase(st.column_decltype(11)));
- assertEquals(Constants.SQLITE_FLOAT, st.column_type(11)); // FLOAT ->
- // got INTEGER
- assertTrue("BLOB".equalsIgnoreCase(st.column_decltype(19)));
- assertEquals(Constants.SQLITE_BLOB, st.column_type(19)); // Blob got
- // INTEGER
-
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column_count() )}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "column_count",
- args = {}
- )
- @KnownFailure("Wrong value is returned in case of a prepared statment to "+
- "which a '*' bound ")
- public void testColumn_count() throws Exception {
-
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- st = db.prepare(selectStmt);
-
- assertEquals(3, st.column_count());
-
- st.step();
- int columnCount = st.column_count();
- assertNotNull(columnCount);
- assertEquals( 3, columnCount);
-
- // actual prepared statement
- selectStmt = "select ? from "+DatabaseCreator.SIMPLE_TABLE1;
- st = db.prepare(selectStmt);
-
- assertEquals(3, st.column_count());
-
- st.bind(1, "*");
- st.step();
- columnCount = st.column_count();
- assertNotNull(columnCount);
- assertEquals( 3, columnCount);
-
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column(int) )}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "method test",
- method = "column",
- args = {int.class}
- )
- public void testColumn() throws Exception {
- Object columnObject = null;
- int columnObjectCastFromLong;
- int intColumn = 0;
- try {
- String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- TableResult res = db.get_table(selectStmt);
- st = db.prepare(selectStmt);
- st.step();
- columnObject = st.column(1);
- intColumn = st.column_int(1);
- assertNotNull(intColumn);
- assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
- int stSpeed = Integer.parseInt(columnObject.toString());
- assertNotNull(stSpeed);
- assertEquals( intColumn, stSpeed);
- } catch (Exception e) {
- fail("Error in test setup : " + e.getMessage());
- e.printStackTrace();
- }
-
- try {
- assertNotNull(columnObject);
- int dummy = ((Integer) columnObject).intValue();
- fail("Cast to Integer should fail");
- } catch (ClassCastException e) {
- assertEquals("java.lang.Long", e.getMessage());
- }
-
- try {
- st.column(4);
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals( "column out of bounds" , e.getMessage());
- }
-
- try {
- st.column(-1);
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals( "column out of bounds" , e.getMessage());
- }
- }
-
- /**
- * @tests {@link Stmt#column_table_name(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "column_table_name",
- args = {int.class}
- )
- public void testColumn_table_name() {
- try {
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- String name = st.column_table_name(1);
- fail("Function is now supported.");
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
- }
-
- /**
- * @tests {@link Stmt#column_database_name(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "column_database_name",
- args = {int.class}
- )
- public void testColumn_database_name() {
- try {
- st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
- + " values (:one,:two,:three)");
- String name = st.column_database_name(1);
- fail("Function is now supported.");
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
-
- }
-
- /**
- * @throws Exception
- * @tests {@link Stmt#column_decltype(int)}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "method test",
- method = "column_decltype",
- args = {int.class}
- )
- public void testColumn_decltype() throws Exception {
- db.exec(createAllTypes, null);
- db.exec(insertAllTypes, null);
- st = db.prepare("select * from " + allTypesTable);
- st.step();
-
- // Exception test
- try {
- st.column_decltype(100);
- } catch (Exception e) {
- // ok
- }
-
- assertTrue(st.column_decltype(0), "BOOLEAN".equalsIgnoreCase(st
- .column_decltype(0)));
- assertTrue(st.column_decltype(1), "INT".equalsIgnoreCase(st
- .column_decltype(1)));
- assertTrue(st.column_decltype(2), "LONG".equalsIgnoreCase(st
- .column_decltype(2)));
- assertTrue(st.column_decltype(3), "BIGINT".equalsIgnoreCase(st
- .column_decltype(3)));
- assertTrue(st.column_decltype(4), "TINYINT".equalsIgnoreCase(st
- .column_decltype(4)));
- assertTrue(st.column_decltype(5), "SMALLINT".equalsIgnoreCase(st
- .column_decltype(5)));
- assertTrue(st.column_decltype(6), "MEDIUMINT".equalsIgnoreCase(st
- .column_decltype(6)));
- assertTrue(st.column_decltype(7), "INTEGER".equalsIgnoreCase(st
- .column_decltype(7)));
- assertTrue(st.column_decltype(8), "REAL".equalsIgnoreCase(st
- .column_decltype(8)));
- assertTrue(st.column_decltype(9), "DOUBLE".equalsIgnoreCase(st
- .column_decltype(9)));
- assertTrue(st.column_decltype(10), "FLOAT".equalsIgnoreCase(st
- .column_decltype(10)));
- assertTrue(st.column_decltype(11), "DECIMAL".equalsIgnoreCase(st
- .column_decltype(11)));
- assertTrue(st.column_decltype(12), "NUMERIC".equalsIgnoreCase(st
- .column_decltype(12)));
- assertTrue(st.column_decltype(13), "CHAR(20)".equalsIgnoreCase(st
- .column_decltype(13)));
-
- assertTrue(st.column_decltype(19), "BLOB".equalsIgnoreCase(st
- .column_decltype(19)));
-
- assertTrue(st.column_decltype(23), "TEXT".equalsIgnoreCase(st
- .column_decltype(23)));
- assertTrue(st.column_decltype(28), "URL".equalsIgnoreCase(st
- .column_decltype(28)));
- assertTrue(st.column_decltype(29), "URL".equalsIgnoreCase(st
- .column_decltype(29)));
- }
-
- /**
- * @tests {@link Stmt#column_origin_name(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "column_origin_name",
- args = {int.class}
- )
- public void testColumn_origin_name() {
- try {
- st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
- String name = st.column_origin_name(1);
- fail("Function is now supported.");
- } catch (Exception e) {
- assertEquals("unsupported", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
index 35cb92d..932315c 100644
--- a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
+++ b/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
@@ -17,10 +17,6 @@
package tests.api.java.lang.reflect;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -34,17 +30,6 @@
import java.util.HashSet;
import java.util.Set;
-@TestTargetClass(
- value = Constructor.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "isSynthetic",
- args = {},
- notes = "Since code which relies on synthetic members is not " +
- "portable, this should not be tested"
- )
- })
public class ConstructorTest extends junit.framework.TestCase {
@@ -118,15 +103,6 @@
// }
// }
- /**
- * @tests java.lang.reflect.Constructor#getDeclaredAnnotations()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameterAnnotations",
- args = {}
- )
public void test_getParameterAnnotations() throws Exception {
Constructor<ConstructorTestHelper> ctor1 = ConstructorTestHelper.class
.getConstructor(Object.class);
@@ -147,15 +123,6 @@
}
- /**
- * @tests java.lang.reflect.Constructor#getDeclaredAnnotations()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
public void test_getDeclaredAnnotations() throws Exception {
Constructor<ConstructorTestHelper> ctor1 = null;
ctor1 = ConstructorTestHelper.class.getConstructor(new Class[0]);
@@ -172,15 +139,6 @@
.contains(ConstructorTestAnnotationRuntime1.class));
}
- /**
- * @tests java.lang.reflect.Constructor#isVarargs()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isVarArgs",
- args = {}
- )
public void test_isVarArgs() throws Exception {
Constructor<ConstructorTestHelper> varArgCtor = ConstructorTestHelper.class
.getConstructor(String[].class);
@@ -192,15 +150,6 @@
nonVarArgCtor.isVarArgs());
}
- /**
- * @tests java.lang.reflect.Constructor#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
public void test_hashCode() throws Exception {
Constructor<ConstructorTestHelper> constructor = ConstructorTestHelper.class
.getConstructor();
@@ -210,16 +159,7 @@
.hashCode());
}
- /**
- * @tests java.lang.reflect.Constructor#toGenericString()
- */
@SuppressWarnings("unchecked")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toGenericString",
- args = {}
- )
public void test_toGenericString() throws Exception {
Constructor<GenericConstructorTestHelper> genericCtor = GenericConstructorTestHelper.class
.getConstructor(Object.class, Object.class);
@@ -235,15 +175,6 @@
ctor.toGenericString());
}
- /**
- * @tests java.lang.reflect.Constructor#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
public void test_equalsLjava_lang_Object() {
Constructor<ConstructorTestHelper> ctor1 = null, ctor2 = null;
try {
@@ -256,15 +187,6 @@
assertTrue("Different Contructors returned equal", !ctor1.equals(ctor2));
}
- /**
- * @tests java.lang.reflect.Constructor#getDeclaringClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
public void test_getDeclaringClass() {
boolean val = false;
try {
@@ -277,15 +199,6 @@
assertTrue("Returned incorrect declaring class", val);
}
- /**
- * @tests java.lang.reflect.Constructor#getExceptionTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getExceptionTypes",
- args = {}
- )
public void test_getExceptionTypes() {
// Test for method java.lang.Class []
// java.lang.reflect.Constructor.getExceptionTypes()
@@ -304,15 +217,6 @@
assertTrue("Returned incorrect exception", exceptions[0].equals(ex));
}
- /**
- * @tests java.lang.reflect.Constructor#getModifiers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getModifiers",
- args = {}
- )
public void test_getModifiers() {
// Test for method int java.lang.reflect.Constructor.getModifiers()
int mod = 0;
@@ -350,15 +254,6 @@
}
}
- /**
- * @tests java.lang.reflect.Constructor#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
public void test_getName() {
// Test for method java.lang.String
// java.lang.reflect.Constructor.getName()
@@ -376,15 +271,6 @@
}
}
- /**
- * @tests java.lang.reflect.Constructor#getParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameterTypes",
- args = {}
- )
public void test_getParameterTypes() {
// Test for method java.lang.Class []
// java.lang.reflect.Constructor.getParameterTypes()
@@ -413,15 +299,6 @@
assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
}
- /**
- * @tests java.lang.reflect.Constructor#getGenericParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void test_getGenericParameterTypes() {
Type[] types = null;
@@ -463,15 +340,6 @@
((TypeVariable)types[1]).getName());
}
- /**
- * @tests java.lang.reflect.Constructor#getGenericParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGenericExceptionTypes",
- args = {}
- )
@SuppressWarnings("unchecked")
public void test_getGenericExceptionTypes() {
Type[] types = null;
@@ -504,16 +372,6 @@
}
-
- /**
- * @tests java.lang.reflect.Constructor#newInstance(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newInstance",
- args = {java.lang.Object[].class}
- )
public void test_newInstance$Ljava_lang_Object() {
// Test for method java.lang.Object
// java.lang.reflect.Constructor.newInstance(java.lang.Object [])
@@ -529,15 +387,6 @@
assertEquals("improper instance created", 99, test.check());
}
- /**
- * @tests java.lang.reflect.Constructor#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
public void test_toString() {
// Test for method java.lang.String
// java.lang.reflect.Constructor.toString()
@@ -559,15 +408,6 @@
"public tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper(java.lang.Object)"));
}
- /**
- * @tests java.lang.reflect.Constructor#getConstructor((Class[]) null)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConstructor",
- args = {}
- )
public void test_getConstructor() throws Exception {
// Passing new Class[0] should be equivalent to (Class[]) null.
Class<ConstructorTestHelper> c2 = ConstructorTestHelper.class;
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java
deleted file mode 100644
index a8db7ad..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java
+++ /dev/null
@@ -1,666 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.math.BigInteger;
-import java.security.*;
-
-public class AbstractExecutorServiceTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AbstractExecutorServiceTest.class);
- }
-
- /**
- * A no-frills implementation of AbstractExecutorService, designed
- * to test the submit methods only.
- */
- static class DirectExecutorService extends AbstractExecutorService {
- public void execute(Runnable r) { r.run(); }
- public void shutdown() { shutdown = true; }
- public List<Runnable> shutdownNow() { shutdown = true; return Collections.EMPTY_LIST; }
- public boolean isShutdown() { return shutdown; }
- public boolean isTerminated() { return isShutdown(); }
- public boolean awaitTermination(long timeout, TimeUnit unit) { return isShutdown(); }
- private volatile boolean shutdown = false;
- }
-
- /**
- * execute(runnable) runs it to completion
- */
- public void testExecuteRunnable() throws Exception {
- ExecutorService e = new DirectExecutorService();
- TrackedShortRunnable task = new TrackedShortRunnable();
- assertFalse(task.done);
- Future<?> future = e.submit(task);
- future.get();
- assertTrue(task.done);
- }
-
-
- /**
- * Completed submit(callable) returns result
- */
- public void testSubmitCallable() throws Exception {
- ExecutorService e = new DirectExecutorService();
- Future<String> future = e.submit(new StringTask());
- String result = future.get();
- assertSame(TEST_STRING, result);
- }
-
- /**
- * Completed submit(runnable) returns successfully
- */
- public void testSubmitRunnable() throws Exception {
- ExecutorService e = new DirectExecutorService();
- Future<?> future = e.submit(new NoOpRunnable());
- future.get();
- assertTrue(future.isDone());
- }
-
- /**
- * Completed submit(runnable, result) returns result
- */
- public void testSubmitRunnable2() throws Exception {
- ExecutorService e = new DirectExecutorService();
- Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
- String result = future.get();
- assertSame(TEST_STRING, result);
- }
-
-
- /**
- * A submitted privileged action runs to completion
- */
- public void testSubmitPrivilegedAction() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- ExecutorService e = new DirectExecutorService();
- Future future = e.submit(Executors.callable(new PrivilegedAction() {
- public Object run() {
- return TEST_STRING;
- }}));
-
- assertSame(TEST_STRING, future.get());
- }};
-
- runWithPermissions(r,
- new RuntimePermission("getClassLoader"),
- new RuntimePermission("setContextClassLoader"),
- new RuntimePermission("modifyThread"));
- }
-
- /**
- * A submitted privileged exception action runs to completion
- */
- public void testSubmitPrivilegedExceptionAction() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- ExecutorService e = new DirectExecutorService();
- Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
- public Object run() {
- return TEST_STRING;
- }}));
-
- assertSame(TEST_STRING, future.get());
- }};
-
- runWithPermissions(r);
- }
-
- /**
- * A submitted failed privileged exception action reports exception
- */
- public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- ExecutorService e = new DirectExecutorService();
- Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
- public Object run() throws Exception {
- throw new IndexOutOfBoundsException();
- }}));
-
- try {
- future.get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
- }}};
-
- runWithPermissions(r);
- }
-
- /**
- * execute(null runnable) throws NPE
- */
- public void testExecuteNullRunnable() {
- try {
- ExecutorService e = new DirectExecutorService();
- e.submit((Runnable) null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * submit(null callable) throws NPE
- */
- public void testSubmitNullCallable() {
- try {
- ExecutorService e = new DirectExecutorService();
- e.submit((Callable) null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * submit(runnable) throws RejectedExecutionException if
- * executor is saturated.
- */
- public void testExecute1() {
- ThreadPoolExecutor p =
- new ThreadPoolExecutor(1, 1,
- 60, TimeUnit.SECONDS,
- new ArrayBlockingQueue<Runnable>(1));
- try {
- for (int i = 0; i < 2; ++i)
- p.submit(new MediumRunnable());
- for (int i = 0; i < 2; ++i) {
- try {
- p.submit(new MediumRunnable());
- shouldThrow();
- } catch (RejectedExecutionException success) {}
- }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * submit(callable) throws RejectedExecutionException
- * if executor is saturated.
- */
- public void testExecute2() {
- ThreadPoolExecutor p =
- new ThreadPoolExecutor(1, 1,
- 60, TimeUnit.SECONDS,
- new ArrayBlockingQueue<Runnable>(1));
- try {
- for (int i = 0; i < 2; ++i)
- p.submit(new MediumRunnable());
- for (int i = 0; i < 2; ++i) {
- try {
- p.submit(new SmallCallable());
- shouldThrow();
- } catch (RejectedExecutionException success) {}
- }
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * Blocking on submit(callable) throws InterruptedException if
- * caller interrupted.
- */
- public void testInterruptedSubmit() throws InterruptedException {
- final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws Exception {
- p.submit(new CheckedCallable<Object>() {
- public Object realCall()
- throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- return null;
- }}).get();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- joinPool(p);
- }
-
- /**
- * get of submitted callable throws InterruptedException if callable
- * interrupted
- */
- public void testSubmitIE() throws InterruptedException {
- final ThreadPoolExecutor p =
- new ThreadPoolExecutor(1, 1,
- 60, TimeUnit.SECONDS,
- new ArrayBlockingQueue<Runnable>(10));
-
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws Exception {
- p.submit(new SmallCallable()).get();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- joinPool(p);
- }
-
- /**
- * get of submit(callable) throws ExecutionException if callable
- * throws exception
- */
- public void testSubmitEE() throws InterruptedException {
- ThreadPoolExecutor p =
- new ThreadPoolExecutor(1, 1,
- 60, TimeUnit.SECONDS,
- new ArrayBlockingQueue<Runnable>(10));
-
- Callable c = new Callable() {
- public Object call() { return 5/0; }};
-
- try {
- p.submit(c).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof ArithmeticException);
- }
- joinPool(p);
- }
-
- /**
- * invokeAny(null) throws NPE
- */
- public void testInvokeAny1()
- throws InterruptedException, ExecutionException {
- ExecutorService e = new DirectExecutorService();
- try {
- e.invokeAny(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(empty collection) throws IAE
- */
- public void testInvokeAny2()
- throws InterruptedException, ExecutionException {
- ExecutorService e = new DirectExecutorService();
- try {
- e.invokeAny(new ArrayList<Callable<String>>());
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws NPE if c has null elements
- */
- public void testInvokeAny3() throws Exception {
- ExecutorService e = new DirectExecutorService();
- List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
- l.add(new Callable<Integer>() {
- public Integer call() { return 5/0; }});
- l.add(null);
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws ExecutionException if no task in c completes
- */
- public void testInvokeAny4() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) returns result of some task in c if at least one completes
- */
- public void testInvokeAny5() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(null) throws NPE
- */
- public void testInvokeAll1() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- try {
- e.invokeAll(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(empty collection) returns empty collection
- */
- public void testInvokeAll2() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) throws NPE if c has null elements
- */
- public void testInvokeAll3() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of returned element of invokeAll(c) throws exception on failed task
- */
- public void testInvokeAll4() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- }
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) returns results of all completed tasks in c
- */
- public void testInvokeAll5() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
-
- /**
- * timed invokeAny(null) throws NPE
- */
- public void testTimedInvokeAny1() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(null time unit) throws NPE
- */
- public void testTimedInvokeAnyNullTimeUnit() throws Exception {
- ExecutorService e = new DirectExecutorService();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(empty collection) throws IAE
- */
- public void testTimedInvokeAny2() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAny3() throws Exception {
- ExecutorService e = new DirectExecutorService();
- List<Callable<Integer>> l = new ArrayList<Callable<Integer>>();
- l.add(new Callable<Integer>() {
- public Integer call() { return 5/0; }});
- l.add(null);
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws ExecutionException if no task completes
- */
- public void testTimedInvokeAny4() throws Exception {
- ExecutorService e = new DirectExecutorService();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) returns result of some task in c
- */
- public void testTimedInvokeAny5() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(null) throws NPE
- */
- public void testTimedInvokeAll1() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- try {
- e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(null time unit) throws NPE
- */
- public void testTimedInvokeAllNullTimeUnit() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(empty collection) returns empty collection
- */
- public void testTimedInvokeAll2() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAll3() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of returned element of invokeAll(c) throws exception on failed task
- */
- public void testTimedInvokeAll4() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- }
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) returns results of all completed tasks in c
- */
- public void testTimedInvokeAll5() throws Exception {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll cancels tasks not completed by timeout
- */
- public void testTimedInvokeAll6() throws InterruptedException {
- ExecutorService e = new DirectExecutorService();
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, SMALL_DELAY_MS, MILLISECONDS);
- assertEquals(3, futures.size());
- Iterator<Future<String>> it = futures.iterator();
- Future<String> f1 = it.next();
- Future<String> f2 = it.next();
- Future<String> f3 = it.next();
- assertTrue(f1.isDone());
- assertFalse(f1.isCancelled());
- assertTrue(f2.isDone());
- assertTrue(f3.isDone());
- assertTrue(f3.isCancelled());
- } finally {
- joinPool(e);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java
deleted file mode 100644
index 9bb206b..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.concurrent.locks.*;
-import java.io.*;
-
-public class AbstractQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AbstractQueueTest.class);
- }
-
- static class Succeed extends AbstractQueue<Integer> {
- public boolean offer(Integer x) {
- if (x == null) throw new NullPointerException();
- return true;
- }
- public Integer peek() { return one; }
- public Integer poll() { return one; }
- public int size() { return 0; }
- public Iterator iterator() { return null; } // not needed
- }
-
- static class Fail extends AbstractQueue<Integer> {
- public boolean offer(Integer x) {
- if (x == null) throw new NullPointerException();
- return false;
- }
- public Integer peek() { return null; }
- public Integer poll() { return null; }
- public int size() { return 0; }
- public Iterator iterator() { return null; } // not needed
- }
-
- /**
- * add returns true if offer succeeds
- */
- public void testAddS() {
- Succeed q = new Succeed();
- assertTrue(q.add(two));
- }
-
- /**
- * add throws ISE true if offer fails
- */
- public void testAddF() {
- Fail q = new Fail();
- try {
- q.add(one);
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * add throws NPE if offer does
- */
- public void testAddNPE() {
- Succeed q = new Succeed();
- try {
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove returns normally if poll succeeds
- */
- public void testRemoveS() {
- Succeed q = new Succeed();
- q.remove();
- }
-
- /**
- * remove throws NSEE if poll returns null
- */
- public void testRemoveF() {
- Fail q = new Fail();
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
-
- /**
- * element returns normally if peek succeeds
- */
- public void testElementS() {
- Succeed q = new Succeed();
- q.element();
- }
-
- /**
- * element throws NSEE if peek returns null
- */
- public void testElementF() {
- Fail q = new Fail();
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- Succeed q = new Succeed();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- Succeed q = new Succeed();
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- Succeed q = new Succeed();
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- Succeed q = new Succeed();
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll throws ISE if an add fails
- */
- public void testAddAll4() {
- try {
- Fail q = new Fail();
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueuedLongSynchronizerTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueuedLongSynchronizerTest.java
deleted file mode 100644
index 43a4bd1..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueuedLongSynchronizerTest.java
+++ /dev/null
@@ -1,1025 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.locks.*;
-import java.io.*;
-
-public class AbstractQueuedLongSynchronizerTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AbstractQueuedLongSynchronizerTest.class);
- }
-
- /**
- * A simple mutex class, adapted from the
- * AbstractQueuedLongSynchronizer javadoc. Exclusive acquire tests
- * exercise this as a sample user extension. Other
- * methods/features of AbstractQueuedLongSynchronizerTest are tested
- * via other test classes, including those for ReentrantLock,
- * ReentrantReadWriteLock, and Semaphore
- */
- static class Mutex extends AbstractQueuedLongSynchronizer {
- // Use value > 32 bits for locked state
- static final long LOCKED = 1 << 48;
- public boolean isHeldExclusively() {
- return getState() == LOCKED;
- }
-
- public boolean tryAcquire(long acquires) {
- return compareAndSetState(0, LOCKED);
- }
-
- public boolean tryRelease(long releases) {
- if (getState() == 0) throw new IllegalMonitorStateException();
- setState(0);
- return true;
- }
-
- public AbstractQueuedLongSynchronizer.ConditionObject newCondition() { return new AbstractQueuedLongSynchronizer.ConditionObject(); }
-
- }
-
-
- /**
- * A simple latch class, to test shared mode.
- */
- static class BooleanLatch extends AbstractQueuedLongSynchronizer {
- public boolean isSignalled() { return getState() != 0; }
-
- public long tryAcquireShared(long ignore) {
- return isSignalled()? 1 : -1;
- }
-
- public boolean tryReleaseShared(long ignore) {
- setState(1 << 62);
- return true;
- }
- }
-
- /**
- * A runnable calling acquireInterruptibly that does not expect to
- * be interrupted.
- */
- class InterruptibleSyncRunnable extends CheckedRunnable {
- final Mutex sync;
- InterruptibleSyncRunnable(Mutex l) { sync = l; }
- public void realRun() throws InterruptedException {
- sync.acquireInterruptibly(1);
- }
- }
-
-
- /**
- * A runnable calling acquireInterruptibly that expects to be
- * interrupted.
- */
- class InterruptedSyncRunnable extends CheckedInterruptedRunnable {
- final Mutex sync;
- InterruptedSyncRunnable(Mutex l) { sync = l; }
- public void realRun() throws InterruptedException {
- sync.acquireInterruptibly(1);
- }
- }
-
- /**
- * isHeldExclusively is false upon construction
- */
- public void testIsHeldExclusively() {
- Mutex rl = new Mutex();
- assertFalse(rl.isHeldExclusively());
- }
-
- /**
- * acquiring released sync succeeds
- */
- public void testAcquire() {
- Mutex rl = new Mutex();
- rl.acquire(1);
- assertTrue(rl.isHeldExclusively());
- rl.release(1);
- assertFalse(rl.isHeldExclusively());
- }
-
- /**
- * tryAcquire on an released sync succeeds
- */
- public void testTryAcquire() {
- Mutex rl = new Mutex();
- assertTrue(rl.tryAcquire(1));
- assertTrue(rl.isHeldExclusively());
- rl.release(1);
- }
-
- /**
- * hasQueuedThreads reports whether there are waiting threads
- */
- public void testhasQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertFalse(sync.hasQueuedThreads());
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThreads());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThreads());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThreads());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThreads());
- t1.join();
- t2.join();
- }
-
- /**
- * isQueued(null) throws NPE
- */
- public void testIsQueuedNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.isQueued(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * isQueued reports whether a thread is queued.
- */
- public void testIsQueued() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertFalse(sync.isQueued(t1));
- assertFalse(sync.isQueued(t2));
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.isQueued(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.isQueued(t1));
- assertTrue(sync.isQueued(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.isQueued(t1));
- assertTrue(sync.isQueued(t2));
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.isQueued(t1));
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.isQueued(t2));
- t1.join();
- t2.join();
- }
-
- /**
- * getFirstQueuedThread returns first waiting thread or null if none
- */
- public void testGetFirstQueuedThread() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertNull(sync.getFirstQueuedThread());
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(t1, sync.getFirstQueuedThread());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(t1, sync.getFirstQueuedThread());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(t2, sync.getFirstQueuedThread());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertNull(sync.getFirstQueuedThread());
- t1.join();
- t2.join();
- }
-
-
- /**
- * hasContended reports false if no thread has ever blocked, else true
- */
- public void testHasContended() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertFalse(sync.hasContended());
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueuedThreads includes waiting threads
- */
- public void testGetQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertTrue(sync.getQueuedThreads().isEmpty());
- sync.acquire(1);
- assertTrue(sync.getQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getQueuedThreads().contains(t1));
- assertTrue(sync.getQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.getQueuedThreads().contains(t1));
- assertTrue(sync.getQueuedThreads().contains(t2));
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * getExclusiveQueuedThreads includes waiting threads
- */
- public void testGetExclusiveQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
- sync.acquire(1);
- assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
- assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.getExclusiveQueuedThreads().contains(t1));
- assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * getSharedQueuedThreads does not include exclusively waiting threads
- */
- public void testGetSharedQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- sync.acquire(1);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * tryAcquireNanos is interruptible.
- */
- public void testInterruptedException2() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.tryAcquireNanos(1, MILLISECONDS.toNanos(MEDIUM_DELAY_MS));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * TryAcquire on exclusively held sync fails
- */
- public void testTryAcquireWhenSynced() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(sync.tryAcquire(1));
- }});
-
- t.start();
- t.join();
- sync.release(1);
- }
-
- /**
- * tryAcquireNanos on an exclusively held sync times out
- */
- public void testAcquireNanos_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- long nanos = MILLISECONDS.toNanos(SHORT_DELAY_MS);
- assertFalse(sync.tryAcquireNanos(1, nanos));
- }});
-
- t.start();
- t.join();
- sync.release(1);
- }
-
-
- /**
- * getState is true when acquired and false when not
- */
- public void testGetState() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- assertTrue(sync.isHeldExclusively());
- sync.release(1);
- assertFalse(sync.isHeldExclusively());
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- Thread.sleep(SMALL_DELAY_MS);
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.isHeldExclusively());
- t.join();
- assertFalse(sync.isHeldExclusively());
- }
-
-
- /**
- * acquireInterruptibly is interruptible.
- */
- public void testAcquireInterruptibly1() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new InterruptedSyncRunnable(sync));
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- sync.release(1);
- t.join();
- }
-
- /**
- * acquireInterruptibly succeeds when released, else is interruptible
- */
- public void testAcquireInterruptibly2() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquireInterruptibly(1);
- Thread t = new Thread(new InterruptedSyncRunnable(sync));
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- assertTrue(sync.isHeldExclusively());
- t.join();
- }
-
- /**
- * owns is true for a condition created by sync else false
- */
- public void testOwns() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- assertTrue(sync.owns(c));
- assertFalse(sync2.owns(c));
- }
-
- /**
- * Calling await without holding sync throws IllegalMonitorStateException
- */
- public void testAwait_IllegalMonitor() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- try {
- c.await();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * Calling signal without holding sync throws IllegalMonitorStateException
- */
- public void testSignal_IllegalMonitor() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- try {
- c.signal();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * awaitNanos without a signal times out
- */
- public void testAwaitNanos_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- sync.acquire(1);
- long t = c.awaitNanos(100);
- assertTrue(t <= 0);
- sync.release(1);
- }
-
- /**
- * Timed await without a signal times out
- */
- public void testAwait_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- sync.acquire(1);
- assertFalse(c.await(SHORT_DELAY_MS, MILLISECONDS));
- sync.release(1);
- }
-
- /**
- * awaitUntil without a signal times out
- */
- public void testAwaitUntil_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- sync.acquire(1);
- java.util.Date d = new java.util.Date();
- assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
- sync.release(1);
- }
-
- /**
- * await returns when signalled
- */
- public void testAwait() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- c.signal();
- sync.release(1);
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
-
-
- /**
- * hasWaiters throws NPE if null
- */
- public void testHasWaitersNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.hasWaiters(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * getWaitQueueLength throws NPE if null
- */
- public void testGetWaitQueueLengthNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.getWaitQueueLength(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * getWaitingThreads throws NPE if null
- */
- public void testGetWaitingThreadsNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.getWaitingThreads(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * hasWaiters throws IAE if not owned
- */
- public void testHasWaitersIAE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- try {
- sync2.hasWaiters(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * hasWaiters throws IMSE if not synced
- */
- public void testHasWaitersIMSE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- try {
- sync.hasWaiters(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitQueueLength throws IAE if not owned
- */
- public void testGetWaitQueueLengthIAE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- try {
- sync2.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitQueueLength throws IMSE if not synced
- */
- public void testGetWaitQueueLengthIMSE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- try {
- sync.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitingThreads throws IAE if not owned
- */
- public void testGetWaitingThreadsIAE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- try {
- sync2.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitingThreads throws IMSE if not synced
- */
- public void testGetWaitingThreadsIMSE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- try {
- sync.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
-
- /**
- * hasWaiters returns true when a thread is waiting, else false
- */
- public void testHasWaiters() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertFalse(sync.hasWaiters(c));
- threadAssertEquals(0, sync.getWaitQueueLength(c));
- c.await();
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertTrue(sync.hasWaiters(c));
- assertEquals(1, sync.getWaitQueueLength(c));
- c.signal();
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertFalse(sync.hasWaiters(c));
- assertEquals(0, sync.getWaitQueueLength(c));
- sync.release(1);
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * getWaitQueueLength returns number of waiting threads
- */
- public void testGetWaitQueueLength() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertFalse(sync.hasWaiters(c));
- threadAssertEquals(0, sync.getWaitQueueLength(c));
- c.await();
- sync.release(1);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertTrue(sync.hasWaiters(c));
- threadAssertEquals(1, sync.getWaitQueueLength(c));
- c.await();
- sync.release(1);
- }});
-
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertTrue(sync.hasWaiters(c));
- assertEquals(2, sync.getWaitQueueLength(c));
- c.signalAll();
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertFalse(sync.hasWaiters(c));
- assertEquals(0, sync.getWaitQueueLength(c));
- sync.release(1);
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * getWaitingThreads returns only and all waiting threads
- */
- public void testGetWaitingThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertTrue(sync.getWaitingThreads(c).isEmpty());
- c.await();
- sync.release(1);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertFalse(sync.getWaitingThreads(c).isEmpty());
- c.await();
- sync.release(1);
- }});
-
- sync.acquire(1);
- assertTrue(sync.getWaitingThreads(c).isEmpty());
- sync.release(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertTrue(sync.hasWaiters(c));
- assertTrue(sync.getWaitingThreads(c).contains(t1));
- assertTrue(sync.getWaitingThreads(c).contains(t2));
- c.signalAll();
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertFalse(sync.hasWaiters(c));
- assertTrue(sync.getWaitingThreads(c).isEmpty());
- sync.release(1);
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
-
-
- /**
- * awaitUninterruptibly doesn't abort on interrupt
- */
- public void testAwaitUninterruptibly() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- sync.acquire(1);
- c.awaitUninterruptibly();
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- sync.acquire(1);
- c.signal();
- sync.release(1);
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * await is interruptible
- */
- public void testAwait_Interrupt() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitNanos is interruptible
- */
- public void testAwaitNanos_Interrupt() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.awaitNanos(MILLISECONDS.toNanos(LONG_DELAY_MS));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitUntil is interruptible
- */
- public void testAwaitUntil_Interrupt() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- java.util.Date d = new java.util.Date();
- c.awaitUntil(new java.util.Date(d.getTime() + 10000));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * signalAll wakes up all threads
- */
- public void testSignalAll() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedLongSynchronizer.ConditionObject c = sync.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- sync.release(1);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- sync.release(1);
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- c.signalAll();
- sync.release(1);
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
-
- /**
- * toString indicates current state
- */
- public void testToString() {
- Mutex sync = new Mutex();
- String us = sync.toString();
- assertTrue(us.indexOf("State = 0") >= 0);
- sync.acquire(1);
- String ls = sync.toString();
- assertTrue(ls.indexOf("State = " + Mutex.LOCKED) >= 0);
- }
-
- /**
- * A serialized AQS deserializes with current state
- */
- public void testSerialization() throws Exception {
- Mutex l = new Mutex();
- l.acquire(1);
- assertTrue(l.isHeldExclusively());
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- Mutex r = (Mutex) in.readObject();
- assertTrue(r.isHeldExclusively());
- }
-
-
- /**
- * tryReleaseShared setting state changes getState
- */
- public void testGetStateWithReleaseShared() {
- final BooleanLatch l = new BooleanLatch();
- assertFalse(l.isSignalled());
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- }
-
- /**
- * releaseShared has no effect when already signalled
- */
- public void testReleaseShared() {
- final BooleanLatch l = new BooleanLatch();
- assertFalse(l.isSignalled());
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- }
-
- /**
- * acquireSharedInterruptibly returns after release, but not before
- */
- public void testAcquireSharedInterruptibly() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(l.isSignalled());
- l.acquireSharedInterruptibly(0);
- threadAssertTrue(l.isSignalled());
- }});
-
- t.start();
- assertFalse(l.isSignalled());
- Thread.sleep(SHORT_DELAY_MS);
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- t.join();
- }
-
-
- /**
- * acquireSharedTimed returns after release
- */
- public void testAsquireSharedTimed() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(l.isSignalled());
- long nanos = MILLISECONDS.toNanos(MEDIUM_DELAY_MS);
- assertTrue(l.tryAcquireSharedNanos(0, nanos));
- assertTrue(l.isSignalled());
- }});
-
- t.start();
- assertFalse(l.isSignalled());
- Thread.sleep(SHORT_DELAY_MS);
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- t.join();
- }
-
- /**
- * acquireSharedInterruptibly throws IE if interrupted before released
- */
- public void testAcquireSharedInterruptibly_InterruptedException() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(l.isSignalled());
- l.acquireSharedInterruptibly(0);
- }});
-
- t.start();
- assertFalse(l.isSignalled());
- t.interrupt();
- t.join();
- }
-
- /**
- * acquireSharedTimed throws IE if interrupted before released
- */
- public void testAcquireSharedNanos_InterruptedException() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(l.isSignalled());
- long nanos = MILLISECONDS.toNanos(SMALL_DELAY_MS);
- l.tryAcquireSharedNanos(0, nanos);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(l.isSignalled());
- t.interrupt();
- t.join();
- }
-
- /**
- * acquireSharedTimed times out if not released before timeout
- */
- public void testAcquireSharedNanos_Timeout() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(l.isSignalled());
- long nanos = MILLISECONDS.toNanos(SMALL_DELAY_MS);
- assertFalse(l.tryAcquireSharedNanos(0, nanos));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(l.isSignalled());
- t.join();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java
deleted file mode 100644
index a5b6554..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java
+++ /dev/null
@@ -1,1023 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent;
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.locks.*;
-import java.io.*;
-
-public class AbstractQueuedSynchronizerTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AbstractQueuedSynchronizerTest.class);
- }
-
- /**
- * A simple mutex class, adapted from the
- * AbstractQueuedSynchronizer javadoc. Exclusive acquire tests
- * exercise this as a sample user extension. Other
- * methods/features of AbstractQueuedSynchronizerTest are tested
- * via other test classes, including those for ReentrantLock,
- * ReentrantReadWriteLock, and Semaphore
- */
- static class Mutex extends AbstractQueuedSynchronizer {
- public boolean isHeldExclusively() { return getState() == 1; }
-
- public boolean tryAcquire(int acquires) {
- assertTrue(acquires == 1);
- return compareAndSetState(0, 1);
- }
-
- public boolean tryRelease(int releases) {
- if (getState() == 0) throw new IllegalMonitorStateException();
- setState(0);
- return true;
- }
-
- public AbstractQueuedSynchronizer.ConditionObject newCondition() { return new AbstractQueuedSynchronizer.ConditionObject(); }
-
- }
-
-
- /**
- * A simple latch class, to test shared mode.
- */
- static class BooleanLatch extends AbstractQueuedSynchronizer {
- public boolean isSignalled() { return getState() != 0; }
-
- public int tryAcquireShared(int ignore) {
- return isSignalled()? 1 : -1;
- }
-
- public boolean tryReleaseShared(int ignore) {
- setState(1);
- return true;
- }
- }
-
- /**
- * A runnable calling acquireInterruptibly that does not expect to
- * be interrupted.
- */
- class InterruptibleSyncRunnable extends CheckedRunnable {
- final Mutex sync;
- InterruptibleSyncRunnable(Mutex l) { sync = l; }
- public void realRun() throws InterruptedException {
- sync.acquireInterruptibly(1);
- }
- }
-
-
- /**
- * A runnable calling acquireInterruptibly that expects to be
- * interrupted.
- */
- class InterruptedSyncRunnable extends CheckedInterruptedRunnable {
- final Mutex sync;
- InterruptedSyncRunnable(Mutex l) { sync = l; }
- public void realRun() throws InterruptedException {
- sync.acquireInterruptibly(1);
- }
- }
-
- /**
- * isHeldExclusively is false upon construction
- */
- public void testIsHeldExclusively() {
- Mutex rl = new Mutex();
- assertFalse(rl.isHeldExclusively());
- }
-
- /**
- * acquiring released sync succeeds
- */
- public void testAcquire() {
- Mutex rl = new Mutex();
- rl.acquire(1);
- assertTrue(rl.isHeldExclusively());
- rl.release(1);
- assertFalse(rl.isHeldExclusively());
- }
-
- /**
- * tryAcquire on an released sync succeeds
- */
- public void testTryAcquire() {
- Mutex rl = new Mutex();
- assertTrue(rl.tryAcquire(1));
- assertTrue(rl.isHeldExclusively());
- rl.release(1);
- }
-
- /**
- * hasQueuedThreads reports whether there are waiting threads
- */
- public void testhasQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertFalse(sync.hasQueuedThreads());
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThreads());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThreads());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThreads());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThreads());
- t1.join();
- t2.join();
- }
-
- /**
- * isQueued(null) throws NPE
- */
- public void testIsQueuedNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.isQueued(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * isQueued reports whether a thread is queued.
- */
- public void testIsQueued() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertFalse(sync.isQueued(t1));
- assertFalse(sync.isQueued(t2));
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.isQueued(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.isQueued(t1));
- assertTrue(sync.isQueued(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.isQueued(t1));
- assertTrue(sync.isQueued(t2));
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.isQueued(t1));
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.isQueued(t2));
- t1.join();
- t2.join();
- }
-
- /**
- * getFirstQueuedThread returns first waiting thread or null if none
- */
- public void testGetFirstQueuedThread() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertNull(sync.getFirstQueuedThread());
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(t1, sync.getFirstQueuedThread());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(t1, sync.getFirstQueuedThread());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(t2, sync.getFirstQueuedThread());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertNull(sync.getFirstQueuedThread());
- t1.join();
- t2.join();
- }
-
-
- /**
- * hasContended reports false if no thread has ever blocked, else true
- */
- public void testHasContended() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertFalse(sync.hasContended());
- sync.acquire(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasContended());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueuedThreads includes waiting threads
- */
- public void testGetQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertTrue(sync.getQueuedThreads().isEmpty());
- sync.acquire(1);
- assertTrue(sync.getQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getQueuedThreads().contains(t1));
- assertTrue(sync.getQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.getQueuedThreads().contains(t1));
- assertTrue(sync.getQueuedThreads().contains(t2));
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * getExclusiveQueuedThreads includes waiting threads
- */
- public void testGetExclusiveQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
- sync.acquire(1);
- assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getExclusiveQueuedThreads().contains(t1));
- assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.getExclusiveQueuedThreads().contains(t1));
- assertTrue(sync.getExclusiveQueuedThreads().contains(t2));
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getExclusiveQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * getSharedQueuedThreads does not include exclusively waiting threads
- */
- public void testGetSharedQueuedThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- Thread t1 = new Thread(new InterruptedSyncRunnable(sync));
- Thread t2 = new Thread(new InterruptibleSyncRunnable(sync));
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- sync.acquire(1);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.getSharedQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * tryAcquireNanos is interruptible.
- */
- public void testInterruptedException2() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.tryAcquireNanos(1, MILLISECONDS.toNanos(MEDIUM_DELAY_MS));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * TryAcquire on exclusively held sync fails
- */
- public void testTryAcquireWhenSynced() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(sync.tryAcquire(1));
- }});
-
- t.start();
- t.join();
- sync.release(1);
- }
-
- /**
- * tryAcquireNanos on an exclusively held sync times out
- */
- public void testAcquireNanos_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- long nanos = MILLISECONDS.toNanos(SHORT_DELAY_MS);
- assertFalse(sync.tryAcquireNanos(1, nanos));
- }});
-
- t.start();
- t.join();
- sync.release(1);
- }
-
-
- /**
- * getState is true when acquired and false when not
- */
- public void testGetState() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- assertTrue(sync.isHeldExclusively());
- sync.release(1);
- assertFalse(sync.isHeldExclusively());
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- Thread.sleep(SMALL_DELAY_MS);
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.isHeldExclusively());
- t.join();
- assertFalse(sync.isHeldExclusively());
- }
-
-
- /**
- * acquireInterruptibly is interruptible.
- */
- public void testAcquireInterruptibly1() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquire(1);
- Thread t = new Thread(new InterruptedSyncRunnable(sync));
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- sync.release(1);
- t.join();
- }
-
- /**
- * acquireInterruptibly succeeds when released, else is interruptible
- */
- public void testAcquireInterruptibly2() throws InterruptedException {
- final Mutex sync = new Mutex();
- sync.acquireInterruptibly(1);
- Thread t = new Thread(new InterruptedSyncRunnable(sync));
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- assertTrue(sync.isHeldExclusively());
- t.join();
- }
-
- /**
- * owns is true for a condition created by sync else false
- */
- public void testOwns() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- assertTrue(sync.owns(c));
- assertFalse(sync2.owns(c));
- }
-
- /**
- * Calling await without holding sync throws IllegalMonitorStateException
- */
- public void testAwait_IllegalMonitor() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- try {
- c.await();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * Calling signal without holding sync throws IllegalMonitorStateException
- */
- public void testSignal_IllegalMonitor() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- try {
- c.signal();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * awaitNanos without a signal times out
- */
- public void testAwaitNanos_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- sync.acquire(1);
- long t = c.awaitNanos(100);
- assertTrue(t <= 0);
- sync.release(1);
- }
-
- /**
- * Timed await without a signal times out
- */
- public void testAwait_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- sync.acquire(1);
- assertFalse(c.await(SHORT_DELAY_MS, MILLISECONDS));
- sync.release(1);
- }
-
- /**
- * awaitUntil without a signal times out
- */
- public void testAwaitUntil_Timeout() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- sync.acquire(1);
- java.util.Date d = new java.util.Date();
- assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
- sync.release(1);
- }
-
- /**
- * await returns when signalled
- */
- public void testAwait() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- c.signal();
- sync.release(1);
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
-
-
- /**
- * hasWaiters throws NPE if null
- */
- public void testHasWaitersNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.hasWaiters(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * getWaitQueueLength throws NPE if null
- */
- public void testGetWaitQueueLengthNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.getWaitQueueLength(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * getWaitingThreads throws NPE if null
- */
- public void testGetWaitingThreadsNPE() {
- final Mutex sync = new Mutex();
- try {
- sync.getWaitingThreads(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * hasWaiters throws IAE if not owned
- */
- public void testHasWaitersIAE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- try {
- sync2.hasWaiters(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * hasWaiters throws IMSE if not synced
- */
- public void testHasWaitersIMSE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- try {
- sync.hasWaiters(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitQueueLength throws IAE if not owned
- */
- public void testGetWaitQueueLengthIAE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- try {
- sync2.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitQueueLength throws IMSE if not synced
- */
- public void testGetWaitQueueLengthIMSE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- try {
- sync.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitingThreads throws IAE if not owned
- */
- public void testGetWaitingThreadsIAE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- final Mutex sync2 = new Mutex();
- try {
- sync2.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitingThreads throws IMSE if not synced
- */
- public void testGetWaitingThreadsIMSE() {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- try {
- sync.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
-
- /**
- * hasWaiters returns true when a thread is waiting, else false
- */
- public void testHasWaiters() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertFalse(sync.hasWaiters(c));
- threadAssertEquals(0, sync.getWaitQueueLength(c));
- c.await();
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertTrue(sync.hasWaiters(c));
- assertEquals(1, sync.getWaitQueueLength(c));
- c.signal();
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertFalse(sync.hasWaiters(c));
- assertEquals(0, sync.getWaitQueueLength(c));
- sync.release(1);
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * getWaitQueueLength returns number of waiting threads
- */
- public void testGetWaitQueueLength() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertFalse(sync.hasWaiters(c));
- threadAssertEquals(0, sync.getWaitQueueLength(c));
- c.await();
- sync.release(1);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertTrue(sync.hasWaiters(c));
- threadAssertEquals(1, sync.getWaitQueueLength(c));
- c.await();
- sync.release(1);
- }});
-
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertTrue(sync.hasWaiters(c));
- assertEquals(2, sync.getWaitQueueLength(c));
- c.signalAll();
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertFalse(sync.hasWaiters(c));
- assertEquals(0, sync.getWaitQueueLength(c));
- sync.release(1);
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * getWaitingThreads returns only and all waiting threads
- */
- public void testGetWaitingThreads() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertTrue(sync.getWaitingThreads(c).isEmpty());
- c.await();
- sync.release(1);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- threadAssertFalse(sync.getWaitingThreads(c).isEmpty());
- c.await();
- sync.release(1);
- }});
-
- sync.acquire(1);
- assertTrue(sync.getWaitingThreads(c).isEmpty());
- sync.release(1);
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertTrue(sync.hasWaiters(c));
- assertTrue(sync.getWaitingThreads(c).contains(t1));
- assertTrue(sync.getWaitingThreads(c).contains(t2));
- c.signalAll();
- sync.release(1);
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- assertFalse(sync.hasWaiters(c));
- assertTrue(sync.getWaitingThreads(c).isEmpty());
- sync.release(1);
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
-
-
- /**
- * awaitUninterruptibly doesn't abort on interrupt
- */
- public void testAwaitUninterruptibly() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- sync.acquire(1);
- c.awaitUninterruptibly();
- sync.release(1);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- sync.acquire(1);
- c.signal();
- sync.release(1);
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * await is interruptible
- */
- public void testAwait_Interrupt() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitNanos is interruptible
- */
- public void testAwaitNanos_Interrupt() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.awaitNanos(MILLISECONDS.toNanos(LONG_DELAY_MS));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitUntil is interruptible
- */
- public void testAwaitUntil_Interrupt() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- java.util.Date d = new java.util.Date();
- c.awaitUntil(new java.util.Date(d.getTime() + 10000));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * signalAll wakes up all threads
- */
- public void testSignalAll() throws InterruptedException {
- final Mutex sync = new Mutex();
- final AbstractQueuedSynchronizer.ConditionObject c = sync.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- sync.release(1);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- sync.acquire(1);
- c.await();
- sync.release(1);
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- sync.acquire(1);
- c.signalAll();
- sync.release(1);
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
-
- /**
- * toString indicates current state
- */
- public void testToString() {
- Mutex sync = new Mutex();
- String us = sync.toString();
- assertTrue(us.indexOf("State = 0") >= 0);
- sync.acquire(1);
- String ls = sync.toString();
- assertTrue(ls.indexOf("State = 1") >= 0);
- }
-
- /**
- * A serialized AQS deserializes with current state
- */
- public void testSerialization() throws Exception {
- Mutex l = new Mutex();
- l.acquire(1);
- assertTrue(l.isHeldExclusively());
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- Mutex r = (Mutex) in.readObject();
- assertTrue(r.isHeldExclusively());
- }
-
-
- /**
- * tryReleaseShared setting state changes getState
- */
- public void testGetStateWithReleaseShared() {
- final BooleanLatch l = new BooleanLatch();
- assertFalse(l.isSignalled());
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- }
-
- /**
- * releaseShared has no effect when already signalled
- */
- public void testReleaseShared() {
- final BooleanLatch l = new BooleanLatch();
- assertFalse(l.isSignalled());
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- }
-
- /**
- * acquireSharedInterruptibly returns after release, but not before
- */
- public void testAcquireSharedInterruptibly() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(l.isSignalled());
- l.acquireSharedInterruptibly(0);
- threadAssertTrue(l.isSignalled());
- }});
-
- t.start();
- assertFalse(l.isSignalled());
- Thread.sleep(SHORT_DELAY_MS);
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- t.join();
- }
-
-
- /**
- * acquireSharedTimed returns after release
- */
- public void testAsquireSharedTimed() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(l.isSignalled());
- long nanos = MILLISECONDS.toNanos(MEDIUM_DELAY_MS);
- assertTrue(l.tryAcquireSharedNanos(0, nanos));
- assertTrue(l.isSignalled());
- }});
-
- t.start();
- assertFalse(l.isSignalled());
- Thread.sleep(SHORT_DELAY_MS);
- l.releaseShared(0);
- assertTrue(l.isSignalled());
- t.join();
- }
-
- /**
- * acquireSharedInterruptibly throws IE if interrupted before released
- */
- public void testAcquireSharedInterruptibly_InterruptedException() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(l.isSignalled());
- l.acquireSharedInterruptibly(0);
- }});
-
- t.start();
- assertFalse(l.isSignalled());
- t.interrupt();
- t.join();
- }
-
- /**
- * acquireSharedTimed throws IE if interrupted before released
- */
- public void testAcquireSharedNanos_InterruptedException() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(l.isSignalled());
- long nanos = MILLISECONDS.toNanos(SMALL_DELAY_MS);
- l.tryAcquireSharedNanos(0, nanos);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(l.isSignalled());
- t.interrupt();
- t.join();
- }
-
- /**
- * acquireSharedTimed times out if not released before timeout
- */
- public void testAcquireSharedNanos_Timeout() throws InterruptedException {
- final BooleanLatch l = new BooleanLatch();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(l.isSignalled());
- long nanos = MILLISECONDS.toNanos(SMALL_DELAY_MS);
- assertFalse(l.tryAcquireSharedNanos(0, nanos));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(l.isSignalled());
- t.join();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java
deleted file mode 100755
index 8fc5cb6..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java
+++ /dev/null
@@ -1,920 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-
-public class ArrayBlockingQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ArrayBlockingQueueTest.class);
- }
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private ArrayBlockingQueue populatedQueue(int n) {
- ArrayBlockingQueue q = new ArrayBlockingQueue(n);
- assertTrue(q.isEmpty());
- for (int i = 0; i < n; i++)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(0, q.remainingCapacity());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * A new queue has the indicated capacity
- */
- public void testConstructor1() {
- assertEquals(SIZE, new ArrayBlockingQueue(SIZE).remainingCapacity());
- }
-
- /**
- * Constructor throws IAE if capacity argument nonpositive
- */
- public void testConstructor2() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(1, true, null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from too large collection throws IAE
- */
- public void testConstructor6() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ArrayBlockingQueue q = new ArrayBlockingQueue(1, false, Arrays.asList(ints));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
- */
- public void testConstructor7() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * Queue transitions from empty to full when elements added
- */
- public void testEmptyFull() {
- ArrayBlockingQueue q = new ArrayBlockingQueue(2);
- assertTrue(q.isEmpty());
- assertEquals(2, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- q.add(two);
- assertFalse(q.isEmpty());
- assertEquals(0, q.remainingCapacity());
- assertFalse(q.offer(three));
- }
-
- /**
- * remainingCapacity decreases on add, increases on remove
- */
- public void testRemainingCapacity() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remainingCapacity());
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.remainingCapacity());
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(1);
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(1);
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Offer succeeds if not full; fails if full
- */
- public void testOffer() {
- ArrayBlockingQueue q = new ArrayBlockingQueue(1);
- assertTrue(q.offer(zero));
- assertFalse(q.offer(one));
- }
-
- /**
- * add succeeds if not full; throws ISE if full
- */
- public void testAdd() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.add(new Integer(i)));
- }
- assertEquals(0, q.remainingCapacity());
- q.add(new Integer(SIZE));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(1);
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll throws ISE if not enough room
- */
- public void testAddAll4() {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(1);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
- /**
- * Queue contains all elements, in traversal order, of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * put(null) throws NPE
- */
- public void testPutNull() throws InterruptedException {
- try {
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- q.put(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully put are contained
- */
- public void testPut() throws InterruptedException {
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.put(I);
- assertTrue(q.contains(I));
- }
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * put blocks interruptibly if full
- */
- public void testBlockingPut() throws InterruptedException {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- q.put(i);
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- try {
- q.put(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * put blocks waiting for take when full
- */
- public void testPutWithTake() throws InterruptedException {
- final int capacity = 2;
- final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < capacity + 1; i++)
- q.put(i);
- try {
- q.put(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(q.remainingCapacity(), 0);
- assertEquals(0, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(q.remainingCapacity(), 0);
- }
-
- /**
- * timed offer times out if full and elements not taken
- */
- public void testTimedOffer() throws InterruptedException {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Object());
- q.put(new Object());
- assertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, MILLISECONDS));
- try {
- q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * take retrieves elements in FIFO order
- */
- public void testTake() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- }
-
- /**
- * take blocks interruptibly when empty
- */
- public void testTakeFromEmpty() throws InterruptedException {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
- Thread t = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- q.take();
- }};
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * Take removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTake() throws InterruptedException {
- final ArrayBlockingQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- try {
- q.take();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * timed pool with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll0() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(0, MILLISECONDS));
- }
- assertNull(q.poll(0, MILLISECONDS));
- }
-
- /**
- * timed pool with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPoll() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));;
- }
- try {
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOffer() throws InterruptedException {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.poll());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.element());
- assertEquals(i, q.poll());
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- assertEquals(i, q.poll());
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertEquals(SIZE, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(one));
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- ArrayBlockingQueue p = new ArrayBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- ArrayBlockingQueue p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- ArrayBlockingQueue p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.take());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.take());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws CCE
- */
- public void testToArray1_BadArg() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() throws InterruptedException {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertEquals(it.next(), q.take());
- }
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
- q.add(two);
- q.add(one);
- q.add(three);
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertSame(it.next(), one);
- assertSame(it.next(), three);
- assertFalse(it.hasNext());
- }
-
- /**
- * iterator ordering is FIFO
- */
- public void testIteratorOrdering() {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
- q.add(one);
- q.add(two);
- q.add(three);
-
- assertEquals("queue should be full", 0, q.remainingCapacity());
-
- int k = 0;
- for (Iterator it = q.iterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
- assertEquals(3, k);
- }
-
- /**
- * Modifications do not cause iterators to fail
- */
- public void testWeaklyConsistentIteration () {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
- q.add(one);
- q.add(two);
- q.add(three);
- for (Iterator it = q.iterator(); it.hasNext();) {
- q.remove();
- it.next();
- }
- assertEquals(0, q.size());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
-
- /**
- * offer transfers elements across Executor tasks
- */
- public void testOfferInExecutor() {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
- q.add(one);
- q.add(two);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(q.offer(three));
- assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
- assertEquals(0, q.remainingCapacity());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- assertSame(one, q.take());
- }});
-
- joinPool(executor);
- }
-
- /**
- * poll retrieves elements across Executor threads
- */
- public void testPollInExecutor() {
- final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll());
- assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- assertTrue(q.isEmpty());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- q.put(one);
- }});
-
- joinPool(executor);
- }
-
- /**
- * A deserialized serialized queue has same elements in same order
- */
- public void testSerialization() throws Exception {
- ArrayBlockingQueue q = populatedQueue(SIZE);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-
- /**
- * drainTo(null) throws NPE
- */
- public void testDrainToNull() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this) throws IAE
- */
- public void testDrainToSelf() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c) empties queue into another collection c
- */
- public void testDrainTo() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- q.add(zero);
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(zero));
- assertTrue(q.contains(one));
- l.clear();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), 2);
- for (int i = 0; i < 2; ++i)
- assertEquals(l.get(i), new Integer(i));
- }
-
- /**
- * drainTo empties full queue, unblocking a waiting put.
- */
- public void testDrainToWithActivePut() throws InterruptedException {
- final ArrayBlockingQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Integer(SIZE+1));
- }});
-
- t.start();
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertTrue(l.size() >= SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- t.join();
- assertTrue(q.size() + l.size() >= SIZE);
- }
-
- /**
- * drainTo(null, n) throws NPE
- */
- public void testDrainToNullN() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null, 0);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this, n) throws IAE
- */
- public void testDrainToSelfN() {
- ArrayBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c, n) empties first max {n, size} elements of queue into c
- */
- public void testDrainToN() {
- ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE*2);
- for (int i = 0; i < SIZE + 2; ++i) {
- for (int j = 0; j < SIZE; j++)
- assertTrue(q.offer(new Integer(j)));
- ArrayList l = new ArrayList();
- q.drainTo(l, i);
- int k = (i < SIZE)? i : SIZE;
- assertEquals(l.size(), k);
- assertEquals(q.size(), SIZE-k);
- for (int j = 0; j < k; ++j)
- assertEquals(l.get(j), new Integer(j));
- while (q.poll() != null) ;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ArrayDequeTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ArrayDequeTest.java
deleted file mode 100644
index cec1d58..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ArrayDequeTest.java
+++ /dev/null
@@ -1,630 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-
-public class ArrayDequeTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ArrayDequeTest.class);
- }
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private ArrayDeque populatedDeque(int n) {
- ArrayDeque q = new ArrayDeque();
- assertTrue(q.isEmpty());
- for (int i = 0; i < n; ++i)
- assertTrue(q.offerLast(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * new queue is empty
- */
- public void testConstructor1() {
- assertEquals(0, new ArrayDeque().size());
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- ArrayDeque q = new ArrayDeque((Collection)null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
-
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ArrayDeque q = new ArrayDeque(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- ArrayDeque q = new ArrayDeque();
- assertTrue(q.isEmpty());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.add(new Integer(2));
- q.removeFirst();
- q.removeFirst();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.removeFirst();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * push(null) throws NPE
- */
- public void testPushNull() {
- try {
- ArrayDeque q = new ArrayDeque(1);
- q.push(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * peekFirst returns element inserted with push
- */
- public void testPush() {
- ArrayDeque q = populatedDeque(3);
- q.pollLast();
- q.push(four);
- assertSame(four, q.peekFirst());
- }
-
- /**
- * pop removes next element, or throws NSEE if empty
- */
- public void testPop() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pop());
- }
- try {
- q.pop();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferFirstNull() {
- try {
- ArrayDeque q = new ArrayDeque();
- q.offerFirst(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * OfferFirst succeeds
- */
- public void testOfferFirst() {
- ArrayDeque q = new ArrayDeque();
- assertTrue(q.offerFirst(new Integer(0)));
- assertTrue(q.offerFirst(new Integer(1)));
- }
-
- /**
- * OfferLast succeeds
- */
- public void testOfferLast() {
- ArrayDeque q = new ArrayDeque();
- assertTrue(q.offerLast(new Integer(0)));
- assertTrue(q.offerLast(new Integer(1)));
- }
-
- /**
- * add succeeds
- */
- public void testAdd() {
- ArrayDeque q = new ArrayDeque();
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- assertTrue(q.add(new Integer(i)));
- }
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- ArrayDeque q = new ArrayDeque();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements, in traversal order, of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ArrayDeque q = new ArrayDeque();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * pollFirst succeeds unless empty
- */
- public void testPollFirst() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst());
- }
- assertNull(q.pollFirst());
- }
-
- /**
- * pollLast succeeds unless empty
- */
- public void testPollLast() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.pollLast());
- }
- assertNull(q.pollLast());
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * peekFirst returns next element, or null if empty
- */
- public void testPeekFirst() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peekFirst());
- assertEquals(i, q.pollFirst());
- assertTrue(q.peekFirst() == null ||
- !q.peekFirst().equals(i));
- }
- assertNull(q.peekFirst());
- }
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.poll());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * peekLast returns next element, or null if empty
- */
- public void testPeekLast() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.peekLast());
- assertEquals(i, q.pollLast());
- assertTrue(q.peekLast() == null ||
- !q.peekLast().equals(i));
- }
- assertNull(q.peekLast());
- }
-
- /**
- * getFirst returns next getFirst, or throws NSEE if empty
- */
- public void testFirstElement() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.getFirst());
- assertEquals(i, q.pollFirst());
- }
- try {
- q.getFirst();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * getLast returns next element, or throws NSEE if empty
- */
- public void testLastElement() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.getLast());
- assertEquals(i, q.pollLast());
- }
- try {
- q.getLast();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- assertNull(q.peekLast());
- }
-
-
- /**
- * removeFirst removes next element, or throws NSEE if empty
- */
- public void testRemoveFirst() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.removeFirst());
- }
- try {
- q.removeFirst();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * removeFirstOccurrence(x) removes x and returns true if present
- */
- public void testRemoveFirstOccurrence() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.removeFirstOccurrence(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.removeFirstOccurrence(new Integer(i)));
- assertFalse(q.removeFirstOccurrence(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * removeLastOccurrence(x) removes x and returns true if present
- */
- public void testRemoveLastOccurrence() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.removeLastOccurrence(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.removeLastOccurrence(new Integer(i)));
- assertFalse(q.removeLastOccurrence(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- ArrayDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- assertEquals(i, q.pollFirst());
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- ArrayDeque q = populatedDeque(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertTrue(q.add(new Integer(1)));
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- ArrayDeque q = populatedDeque(SIZE);
- ArrayDeque p = new ArrayDeque();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- assertTrue(p.add(new Integer(i)));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- ArrayDeque q = populatedDeque(SIZE);
- ArrayDeque p = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- assertEquals(changed, (i > 0));
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.removeFirst();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- ArrayDeque q = populatedDeque(SIZE);
- ArrayDeque p = populatedDeque(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- assertFalse(q.contains(p.removeFirst()));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() {
- ArrayDeque q = populatedDeque(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.pollFirst());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() {
- ArrayDeque q = populatedDeque(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- ArrayDeque l = new ArrayDeque();
- l.add(new Object());
- try {
- Object o[] = l.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws CCE
- */
- public void testToArray1_BadArg() {
- ArrayDeque l = new ArrayDeque();
- l.add(new Integer(5));
- try {
- Object o[] = l.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- ArrayDeque q = populatedDeque(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator ordering is FIFO
- */
- public void testIteratorOrdering() {
- final ArrayDeque q = new ArrayDeque();
- q.add(new Integer(1));
- q.add(new Integer(2));
- q.add(new Integer(3));
- int k = 0;
- for (Iterator it = q.iterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
-
- assertEquals(3, k);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final ArrayDeque q = new ArrayDeque();
- final Random rng = new Random();
- for (int iters = 0; iters < 100; ++iters) {
- int max = rng.nextInt(5) + 2;
- int split = rng.nextInt(max-1) + 1;
- for (int j = 1; j <= max; ++j)
- q.add(new Integer(j));
- Iterator it = q.iterator();
- for (int j = 1; j <= split; ++j)
- assertEquals(it.next(), new Integer(j));
- it.remove();
- assertEquals(it.next(), new Integer(split+1));
- for (int j = 1; j <= split; ++j)
- q.remove(new Integer(j));
- it = q.iterator();
- for (int j = split+1; j <= max; ++j) {
- assertEquals(it.next(), new Integer(j));
- it.remove();
- }
- assertFalse(it.hasNext());
- assertTrue(q.isEmpty());
- }
- }
-
- /**
- * Descending iterator iterates through all elements
- */
- public void testDescendingIterator() {
- ArrayDeque q = populatedDeque(SIZE);
- int i = 0;
- Iterator it = q.descendingIterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- assertFalse(it.hasNext());
- try {
- it.next();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * Descending iterator ordering is reverse FIFO
- */
- public void testDescendingIteratorOrdering() {
- final ArrayDeque q = new ArrayDeque();
- for (int iters = 0; iters < 100; ++iters) {
- q.add(new Integer(3));
- q.add(new Integer(2));
- q.add(new Integer(1));
- int k = 0;
- for (Iterator it = q.descendingIterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
-
- assertEquals(3, k);
- q.remove();
- q.remove();
- q.remove();
- }
- }
-
- /**
- * descendingIterator.remove removes current element
- */
- public void testDescendingIteratorRemove () {
- final ArrayDeque q = new ArrayDeque();
- final Random rng = new Random();
- for (int iters = 0; iters < 100; ++iters) {
- int max = rng.nextInt(5) + 2;
- int split = rng.nextInt(max-1) + 1;
- for (int j = max; j >= 1; --j)
- q.add(new Integer(j));
- Iterator it = q.descendingIterator();
- for (int j = 1; j <= split; ++j)
- assertEquals(it.next(), new Integer(j));
- it.remove();
- assertEquals(it.next(), new Integer(split+1));
- for (int j = 1; j <= split; ++j)
- q.remove(new Integer(j));
- it = q.descendingIterator();
- for (int j = split+1; j <= max; ++j) {
- assertEquals(it.next(), new Integer(j));
- it.remove();
- }
- assertFalse(it.hasNext());
- assertTrue(q.isEmpty());
- }
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- ArrayDeque q = populatedDeque(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * peekFirst returns element inserted with addFirst
- */
- public void testAddFirst() {
- ArrayDeque q = populatedDeque(3);
- q.addFirst(four);
- assertSame(four, q.peekFirst());
- }
-
- /**
- * peekLast returns element inserted with addLast
- */
- public void testAddLast() {
- ArrayDeque q = populatedDeque(3);
- q.addLast(four);
- assertSame(four, q.peekLast());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java
deleted file mode 100755
index b2d91b8..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-
-public class AtomicBooleanTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicBooleanTest.class);
- }
-
- /**
- * constructor initializes to given value
- */
- public void testConstructor() {
- assertTrue(new AtomicBoolean(true).get());
- assertFalse(new AtomicBoolean(false).get());
- }
-
- /**
- * default constructed initializes to false
- */
- public void testConstructor2() {
- AtomicBoolean ai = new AtomicBoolean();
- assertFalse(ai.get());
- }
-
- /**
- * get returns the last value set
- */
- public void testGetSet() {
- AtomicBoolean ai = new AtomicBoolean(true);
- assertTrue(ai.get());
- ai.set(false);
- assertFalse(ai.get());
- ai.set(true);
- assertTrue(ai.get());
- }
-
- /**
- * get returns the last value lazySet in same thread
- */
- public void testGetLazySet() {
- AtomicBoolean ai = new AtomicBoolean(true);
- assertTrue(ai.get());
- ai.lazySet(false);
- assertFalse(ai.get());
- ai.lazySet(true);
- assertTrue(ai.get());
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicBoolean ai = new AtomicBoolean(true);
- assertTrue(ai.compareAndSet(true,false));
- assertFalse(ai.get());
- assertTrue(ai.compareAndSet(false,false));
- assertFalse(ai.get());
- assertFalse(ai.compareAndSet(true,false));
- assertFalse(ai.get());
- assertTrue(ai.compareAndSet(false,true));
- assertTrue(ai.get());
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicBoolean ai = new AtomicBoolean(true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(false, true)) Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(true, false));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicBoolean ai = new AtomicBoolean(true);
- while (!ai.weakCompareAndSet(true,false));
- assertFalse(ai.get());
- while (!ai.weakCompareAndSet(false,false));
- assertFalse(ai.get());
- while (!ai.weakCompareAndSet(false,true));
- assertTrue(ai.get());
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicBoolean ai = new AtomicBoolean(true);
- assertEquals(true,ai.getAndSet(false));
- assertEquals(false,ai.getAndSet(false));
- assertEquals(false,ai.getAndSet(true));
- assertTrue(ai.get());
- }
-
- /**
- * a deserialized serialized atomic holds same value
- */
- public void testSerialization() throws Exception {
- AtomicBoolean l = new AtomicBoolean();
-
- l.set(true);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicBoolean r = (AtomicBoolean) in.readObject();
- assertEquals(l.get(), r.get());
- }
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- AtomicBoolean ai = new AtomicBoolean();
- assertEquals(ai.toString(), Boolean.toString(false));
- ai.set(true);
- assertEquals(ai.toString(), Boolean.toString(true));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java
deleted file mode 100644
index 838296d..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-import java.util.*;
-
-public class AtomicIntegerArrayTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicIntegerArrayTest.class);
- }
-
-
- /**
- * constructor creates array of given size with all elements zero
- */
- public void testConstructor() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(0,ai.get(i));
- }
-
- /**
- * constructor with null array throws NPE
- */
- public void testConstructor2NPE() {
- try {
- int[] a = null;
- AtomicIntegerArray ai = new AtomicIntegerArray(a);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * constructor with array is of same size and has all elements
- */
- public void testConstructor2() {
- int[] a = { 17, 3, -42, 99, -7};
- AtomicIntegerArray ai = new AtomicIntegerArray(a);
- assertEquals(a.length, ai.length());
- for (int i = 0; i < a.length; ++i)
- assertEquals(a[i], ai.get(i));
- }
-
- /**
- * get and set for out of bound indices throw IndexOutOfBoundsException
- */
- public void testIndexing() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- try {
- ai.get(SIZE);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.get(-1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.set(SIZE, 0);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.set(-1, 0);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- }
-
- /**
- * get returns the last value set at index
- */
- public void testGetSet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.get(i));
- ai.set(i, 2);
- assertEquals(2,ai.get(i));
- ai.set(i, -3);
- assertEquals(-3,ai.get(i));
- }
- }
-
- /**
- * get returns the last value lazySet at index by same thread
- */
- public void testGetLazySet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.lazySet(i, 1);
- assertEquals(1,ai.get(i));
- ai.lazySet(i, 2);
- assertEquals(2,ai.get(i));
- ai.lazySet(i, -3);
- assertEquals(-3,ai.get(i));
- }
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertTrue(ai.compareAndSet(i, 1,2));
- assertTrue(ai.compareAndSet(i, 2,-4));
- assertEquals(-4,ai.get(i));
- assertFalse(ai.compareAndSet(i, -5,7));
- assertEquals(-4,ai.get(i));
- assertTrue(ai.compareAndSet(i, -4,7));
- assertEquals(7,ai.get(i));
- }
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicIntegerArray a = new AtomicIntegerArray(1);
- a.set(0, 1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!a.compareAndSet(0, 2, 3))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(a.compareAndSet(0, 1, 2));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertEquals(a.get(0), 3);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- while (!ai.weakCompareAndSet(i, 1,2));
- while (!ai.weakCompareAndSet(i, 2,-4));
- assertEquals(-4,ai.get(i));
- while (!ai.weakCompareAndSet(i, -4,7));
- assertEquals(7,ai.get(i));
- }
- }
-
- /**
- * getAndSet returns previous value and sets to given value at given index
- */
- public void testGetAndSet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndSet(i,0));
- assertEquals(0,ai.getAndSet(i,-10));
- assertEquals(-10,ai.getAndSet(i,1));
- }
- }
-
- /**
- * getAndAdd returns previous value and adds given value
- */
- public void testGetAndAdd() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndAdd(i,2));
- assertEquals(3,ai.get(i));
- assertEquals(3,ai.getAndAdd(i,-4));
- assertEquals(-1,ai.get(i));
- }
- }
-
- /**
- * getAndDecrement returns previous value and decrements
- */
- public void testGetAndDecrement() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndDecrement(i));
- assertEquals(0,ai.getAndDecrement(i));
- assertEquals(-1,ai.getAndDecrement(i));
- }
- }
-
- /**
- * getAndIncrement returns previous value and increments
- */
- public void testGetAndIncrement() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndIncrement(i));
- assertEquals(2,ai.get(i));
- ai.set(i,-2);
- assertEquals(-2,ai.getAndIncrement(i));
- assertEquals(-1,ai.getAndIncrement(i));
- assertEquals(0,ai.getAndIncrement(i));
- assertEquals(1,ai.get(i));
- }
- }
-
- /**
- * addAndGet adds given value to current, and returns current value
- */
- public void testAddAndGet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(3,ai.addAndGet(i,2));
- assertEquals(3,ai.get(i));
- assertEquals(-1,ai.addAndGet(i,-4));
- assertEquals(-1,ai.get(i));
- }
- }
-
- /**
- * decrementAndGet decrements and returns current value
- */
- public void testDecrementAndGet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(0,ai.decrementAndGet(i));
- assertEquals(-1,ai.decrementAndGet(i));
- assertEquals(-2,ai.decrementAndGet(i));
- assertEquals(-2,ai.get(i));
- }
- }
-
- /**
- * incrementAndGet increments and returns current value
- */
- public void testIncrementAndGet() {
- AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(2,ai.incrementAndGet(i));
- assertEquals(2,ai.get(i));
- ai.set(i, -2);
- assertEquals(-1,ai.incrementAndGet(i));
- assertEquals(0,ai.incrementAndGet(i));
- assertEquals(1,ai.incrementAndGet(i));
- assertEquals(1,ai.get(i));
- }
- }
-
- static final int COUNTDOWN = 100000;
-
- class Counter implements Runnable {
- final AtomicIntegerArray ai;
- volatile int counts;
- Counter(AtomicIntegerArray a) { ai = a; }
- public void run() {
- for (;;) {
- boolean done = true;
- for (int i = 0; i < ai.length(); ++i) {
- int v = ai.get(i);
- threadAssertTrue(v >= 0);
- if (v != 0) {
- done = false;
- if (ai.compareAndSet(i, v, v-1))
- ++counts;
- }
- }
- if (done)
- break;
- }
- }
- }
-
- /**
- * Multiple threads using same array of counters successfully
- * update a number of times equal to total count
- */
- public void testCountingInMultipleThreads() throws InterruptedException {
- final AtomicIntegerArray ai = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i)
- ai.set(i, COUNTDOWN);
- Counter c1 = new Counter(ai);
- Counter c2 = new Counter(ai);
- Thread t1 = new Thread(c1);
- Thread t2 = new Thread(c2);
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- assertEquals(c1.counts+c2.counts, SIZE * COUNTDOWN);
- }
-
-
- /**
- * a deserialized serialized array holds same values
- */
- public void testSerialization() throws Exception {
- AtomicIntegerArray l = new AtomicIntegerArray(SIZE);
- for (int i = 0; i < SIZE; ++i)
- l.set(i, -i);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicIntegerArray r = (AtomicIntegerArray) in.readObject();
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(l.get(i), r.get(i));
- }
- }
-
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- int[] a = { 17, 3, -42, 99, -7};
- AtomicIntegerArray ai = new AtomicIntegerArray(a);
- assertEquals(Arrays.toString(a), ai.toString());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java
deleted file mode 100755
index 383e30b..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import java.util.concurrent.atomic.*;
-import junit.framework.*;
-import java.util.*;
-
-public class AtomicIntegerFieldUpdaterTest extends JSR166TestCase {
- volatile int x = 0;
- int w;
- long z;
- public static Test suite() {
- return new TestSuite(AtomicIntegerFieldUpdaterTest.class);
- }
-
- /**
- * Construction with non-existent field throws RuntimeException
- */
- public void testConstructor() {
- try {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest>
- a = AtomicIntegerFieldUpdater.newUpdater
- (AtomicIntegerFieldUpdaterTest.class, "y");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * construction with field not of given type throws RuntimeException
- */
- public void testConstructor2() {
- try {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest>
- a = AtomicIntegerFieldUpdater.newUpdater
- (AtomicIntegerFieldUpdaterTest.class, "z");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * construction with non-volatile field throws RuntimeException
- */
- public void testConstructor3() {
- try {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest>
- a = AtomicIntegerFieldUpdater.newUpdater
- (AtomicIntegerFieldUpdaterTest.class, "w");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * get returns the last value set or assigned
- */
- public void testGetSet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.get(this));
- a.set(this,2);
- assertEquals(2,a.get(this));
- a.set(this,-3);
- assertEquals(-3,a.get(this));
- }
-
- /**
- * get returns the last value lazySet by same thread
- */
- public void testGetLazySet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.get(this));
- a.lazySet(this,2);
- assertEquals(2,a.get(this));
- a.lazySet(this,-3);
- assertEquals(-3,a.get(this));
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertTrue(a.compareAndSet(this,1,2));
- assertTrue(a.compareAndSet(this,2,-4));
- assertEquals(-4,a.get(this));
- assertFalse(a.compareAndSet(this,-5,7));
- assertEquals(-4,a.get(this));
- assertTrue(a.compareAndSet(this,-4,7));
- assertEquals(7,a.get(this));
- }
-
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- x = 1;
- final AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest>a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!a.compareAndSet(AtomicIntegerFieldUpdaterTest.this, 2, 3))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(a.compareAndSet(this, 1, 2));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertEquals(a.get(this), 3);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- while (!a.weakCompareAndSet(this,1,2));
- while (!a.weakCompareAndSet(this,2,-4));
- assertEquals(-4,a.get(this));
- while (!a.weakCompareAndSet(this,-4,7));
- assertEquals(7,a.get(this));
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndSet(this, 0));
- assertEquals(0,a.getAndSet(this,-10));
- assertEquals(-10,a.getAndSet(this,1));
- }
-
- /**
- * getAndAdd returns previous value and adds given value
- */
- public void testGetAndAdd() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndAdd(this,2));
- assertEquals(3,a.get(this));
- assertEquals(3,a.getAndAdd(this,-4));
- assertEquals(-1,a.get(this));
- }
-
- /**
- * getAndDecrement returns previous value and decrements
- */
- public void testGetAndDecrement() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndDecrement(this));
- assertEquals(0,a.getAndDecrement(this));
- assertEquals(-1,a.getAndDecrement(this));
- }
-
- /**
- * getAndIncrement returns previous value and increments
- */
- public void testGetAndIncrement() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndIncrement(this));
- assertEquals(2,a.get(this));
- a.set(this,-2);
- assertEquals(-2,a.getAndIncrement(this));
- assertEquals(-1,a.getAndIncrement(this));
- assertEquals(0,a.getAndIncrement(this));
- assertEquals(1,a.get(this));
- }
-
- /**
- * addAndGet adds given value to current, and returns current value
- */
- public void testAddAndGet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(3,a.addAndGet(this,2));
- assertEquals(3,a.get(this));
- assertEquals(-1,a.addAndGet(this,-4));
- assertEquals(-1,a.get(this));
- }
-
- /**
- * decrementAndGet decrements and returns current value
- */
- public void testDecrementAndGet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(0,a.decrementAndGet(this));
- assertEquals(-1,a.decrementAndGet(this));
- assertEquals(-2,a.decrementAndGet(this));
- assertEquals(-2,a.get(this));
- }
-
- /**
- * incrementAndGet increments and returns current value
- */
- public void testIncrementAndGet() {
- AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> a;
- try {
- a = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(2,a.incrementAndGet(this));
- assertEquals(2,a.get(this));
- a.set(this,-2);
- assertEquals(-1,a.incrementAndGet(this));
- assertEquals(0,a.incrementAndGet(this));
- assertEquals(1,a.incrementAndGet(this));
- assertEquals(1,a.get(this));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java
deleted file mode 100755
index a2f3b4b..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-
-public class AtomicIntegerTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicIntegerTest.class);
- }
-
- final int[] VALUES = {
- Integer.MIN_VALUE, -1, 0, 1, 42, Integer.MAX_VALUE,
- };
-
- /**
- * constructor initializes to given value
- */
- public void testConstructor() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.get());
- }
-
- /**
- * default constructed initializes to zero
- */
- public void testConstructor2() {
- AtomicInteger ai = new AtomicInteger();
- assertEquals(0,ai.get());
- }
-
- /**
- * get returns the last value set
- */
- public void testGetSet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.get());
- ai.set(2);
- assertEquals(2,ai.get());
- ai.set(-3);
- assertEquals(-3,ai.get());
- }
-
- /**
- * get returns the last value lazySet in same thread
- */
- public void testGetLazySet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.get());
- ai.lazySet(2);
- assertEquals(2,ai.get());
- ai.lazySet(-3);
- assertEquals(-3,ai.get());
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertTrue(ai.compareAndSet(1,2));
- assertTrue(ai.compareAndSet(2,-4));
- assertEquals(-4,ai.get());
- assertFalse(ai.compareAndSet(-5,7));
- assertEquals(-4,ai.get());
- assertTrue(ai.compareAndSet(-4,7));
- assertEquals(7,ai.get());
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicInteger ai = new AtomicInteger(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(2, 3))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(1, 2));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertEquals(ai.get(), 3);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicInteger ai = new AtomicInteger(1);
- while (!ai.weakCompareAndSet(1,2));
- while (!ai.weakCompareAndSet(2,-4));
- assertEquals(-4,ai.get());
- while (!ai.weakCompareAndSet(-4,7));
- assertEquals(7,ai.get());
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.getAndSet(0));
- assertEquals(0,ai.getAndSet(-10));
- assertEquals(-10,ai.getAndSet(1));
- }
-
- /**
- * getAndAdd returns previous value and adds given value
- */
- public void testGetAndAdd() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.getAndAdd(2));
- assertEquals(3,ai.get());
- assertEquals(3,ai.getAndAdd(-4));
- assertEquals(-1,ai.get());
- }
-
- /**
- * getAndDecrement returns previous value and decrements
- */
- public void testGetAndDecrement() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.getAndDecrement());
- assertEquals(0,ai.getAndDecrement());
- assertEquals(-1,ai.getAndDecrement());
- }
-
- /**
- * getAndIncrement returns previous value and increments
- */
- public void testGetAndIncrement() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(1,ai.getAndIncrement());
- assertEquals(2,ai.get());
- ai.set(-2);
- assertEquals(-2,ai.getAndIncrement());
- assertEquals(-1,ai.getAndIncrement());
- assertEquals(0,ai.getAndIncrement());
- assertEquals(1,ai.get());
- }
-
- /**
- * addAndGet adds given value to current, and returns current value
- */
- public void testAddAndGet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(3,ai.addAndGet(2));
- assertEquals(3,ai.get());
- assertEquals(-1,ai.addAndGet(-4));
- assertEquals(-1,ai.get());
- }
-
- /**
- * decrementAndGet decrements and returns current value
- */
- public void testDecrementAndGet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(0,ai.decrementAndGet());
- assertEquals(-1,ai.decrementAndGet());
- assertEquals(-2,ai.decrementAndGet());
- assertEquals(-2,ai.get());
- }
-
- /**
- * incrementAndGet increments and returns current value
- */
- public void testIncrementAndGet() {
- AtomicInteger ai = new AtomicInteger(1);
- assertEquals(2,ai.incrementAndGet());
- assertEquals(2,ai.get());
- ai.set(-2);
- assertEquals(-1,ai.incrementAndGet());
- assertEquals(0,ai.incrementAndGet());
- assertEquals(1,ai.incrementAndGet());
- assertEquals(1,ai.get());
- }
-
- /**
- * a deserialized serialized atomic holds same value
- */
- public void testSerialization() throws Exception {
- AtomicInteger l = new AtomicInteger();
-
- l.set(22);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicInteger r = (AtomicInteger) in.readObject();
- assertEquals(l.get(), r.get());
- }
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- AtomicInteger ai = new AtomicInteger();
- assertEquals("0", ai.toString());
- for (int x : VALUES) {
- ai.set(x);
- assertEquals(ai.toString(), Integer.toString(x));
- }
- }
-
- /**
- * intValue returns current value.
- */
- public void testIntValue() {
- AtomicInteger ai = new AtomicInteger();
- assertEquals(0, ai.intValue());
- for (int x : VALUES) {
- ai.set(x);
- assertEquals(x, ai.intValue());
- }
- }
-
- /**
- * longValue returns current value.
- */
- public void testLongValue() {
- AtomicInteger ai = new AtomicInteger();
- assertEquals(0L, ai.longValue());
- for (int x : VALUES) {
- ai.set(x);
- assertEquals((long)x, ai.longValue());
- }
- }
-
- /**
- * floatValue returns current value.
- */
- public void testFloatValue() {
- AtomicInteger ai = new AtomicInteger();
- assertEquals(0.0f, ai.floatValue());
- for (int x : VALUES) {
- ai.set(x);
- assertEquals((float)x, ai.floatValue());
- }
- }
-
- /**
- * doubleValue returns current value.
- */
- public void testDoubleValue() {
- AtomicInteger ai = new AtomicInteger();
- assertEquals(0.0d, ai.doubleValue());
- for (int x : VALUES) {
- ai.set(x);
- assertEquals((double)x, ai.doubleValue());
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java
deleted file mode 100644
index 88e0984..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-import java.util.*;
-
-public class AtomicLongArrayTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicLongArrayTest.class);
- }
-
- /**
- * constructor creates array of given size with all elements zero
- */
- public void testConstructor() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(0,ai.get(i));
- }
-
- /**
- * constructor with null array throws NPE
- */
- public void testConstructor2NPE() {
- try {
- long[] a = null;
- AtomicLongArray ai = new AtomicLongArray(a);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * constructor with array is of same size and has all elements
- */
- public void testConstructor2() {
- long[] a = { 17L, 3L, -42L, 99L, -7L};
- AtomicLongArray ai = new AtomicLongArray(a);
- assertEquals(a.length, ai.length());
- for (int i = 0; i < a.length; ++i)
- assertEquals(a[i], ai.get(i));
- }
-
- /**
- * get and set for out of bound indices throw IndexOutOfBoundsException
- */
- public void testIndexing() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- try {
- ai.get(SIZE);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.get(-1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.set(SIZE, 0);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.set(-1, 0);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- }
-
- /**
- * get returns the last value set at index
- */
- public void testGetSet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.get(i));
- ai.set(i, 2);
- assertEquals(2,ai.get(i));
- ai.set(i, -3);
- assertEquals(-3,ai.get(i));
- }
- }
-
- /**
- * get returns the last value lazySet at index by same thread
- */
- public void testGetLazySet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.lazySet(i, 1);
- assertEquals(1,ai.get(i));
- ai.lazySet(i, 2);
- assertEquals(2,ai.get(i));
- ai.lazySet(i, -3);
- assertEquals(-3,ai.get(i));
- }
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertTrue(ai.compareAndSet(i, 1,2));
- assertTrue(ai.compareAndSet(i, 2,-4));
- assertEquals(-4,ai.get(i));
- assertFalse(ai.compareAndSet(i, -5,7));
- assertEquals(-4,ai.get(i));
- assertTrue(ai.compareAndSet(i, -4,7));
- assertEquals(7,ai.get(i));
- }
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws InterruptedException {
- final AtomicLongArray a = new AtomicLongArray(1);
- a.set(0, 1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!a.compareAndSet(0, 2, 3))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(a.compareAndSet(0, 1, 2));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertEquals(a.get(0), 3);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- while (!ai.weakCompareAndSet(i, 1,2));
- while (!ai.weakCompareAndSet(i, 2,-4));
- assertEquals(-4,ai.get(i));
- while (!ai.weakCompareAndSet(i, -4,7));
- assertEquals(7,ai.get(i));
- }
- }
-
- /**
- * getAndSet returns previous value and sets to given value at given index
- */
- public void testGetAndSet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndSet(i,0));
- assertEquals(0,ai.getAndSet(i,-10));
- assertEquals(-10,ai.getAndSet(i,1));
- }
- }
-
- /**
- * getAndAdd returns previous value and adds given value
- */
- public void testGetAndAdd() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndAdd(i,2));
- assertEquals(3,ai.get(i));
- assertEquals(3,ai.getAndAdd(i,-4));
- assertEquals(-1,ai.get(i));
- }
- }
-
- /**
- * getAndDecrement returns previous value and decrements
- */
- public void testGetAndDecrement() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndDecrement(i));
- assertEquals(0,ai.getAndDecrement(i));
- assertEquals(-1,ai.getAndDecrement(i));
- }
- }
-
- /**
- * getAndIncrement returns previous value and increments
- */
- public void testGetAndIncrement() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(1,ai.getAndIncrement(i));
- assertEquals(2,ai.get(i));
- ai.set(i,-2);
- assertEquals(-2,ai.getAndIncrement(i));
- assertEquals(-1,ai.getAndIncrement(i));
- assertEquals(0,ai.getAndIncrement(i));
- assertEquals(1,ai.get(i));
- }
- }
-
- /**
- * addAndGet adds given value to current, and returns current value
- */
- public void testAddAndGet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(3,ai.addAndGet(i,2));
- assertEquals(3,ai.get(i));
- assertEquals(-1,ai.addAndGet(i,-4));
- assertEquals(-1,ai.get(i));
- }
- }
-
- /**
- * decrementAndGet decrements and returns current value
- */
- public void testDecrementAndGet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(0,ai.decrementAndGet(i));
- assertEquals(-1,ai.decrementAndGet(i));
- assertEquals(-2,ai.decrementAndGet(i));
- assertEquals(-2,ai.get(i));
- }
- }
-
- /**
- * incrementAndGet increments and returns current value
- */
- public void testIncrementAndGet() {
- AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, 1);
- assertEquals(2,ai.incrementAndGet(i));
- assertEquals(2,ai.get(i));
- ai.set(i, -2);
- assertEquals(-1,ai.incrementAndGet(i));
- assertEquals(0,ai.incrementAndGet(i));
- assertEquals(1,ai.incrementAndGet(i));
- assertEquals(1,ai.get(i));
- }
- }
-
- static final long COUNTDOWN = 100000;
-
- class Counter implements Runnable {
- final AtomicLongArray ai;
- volatile long counts;
- Counter(AtomicLongArray a) { ai = a; }
- public void run() {
- for (;;) {
- boolean done = true;
- for (int i = 0; i < ai.length(); ++i) {
- long v = ai.get(i);
- threadAssertTrue(v >= 0);
- if (v != 0) {
- done = false;
- if (ai.compareAndSet(i, v, v-1))
- ++counts;
- }
- }
- if (done)
- break;
- }
- }
- }
-
- /**
- * Multiple threads using same array of counters successfully
- * update a number of times equal to total count
- */
- public void testCountingInMultipleThreads() throws InterruptedException {
- final AtomicLongArray ai = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i)
- ai.set(i, COUNTDOWN);
- Counter c1 = new Counter(ai);
- Counter c2 = new Counter(ai);
- Thread t1 = new Thread(c1);
- Thread t2 = new Thread(c2);
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- assertEquals(c1.counts+c2.counts, SIZE * COUNTDOWN);
- }
-
- /**
- * a deserialized serialized array holds same values
- */
- public void testSerialization() throws Exception {
- AtomicLongArray l = new AtomicLongArray(SIZE);
- for (int i = 0; i < SIZE; ++i)
- l.set(i, -i);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicLongArray r = (AtomicLongArray) in.readObject();
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(l.get(i), r.get(i));
- }
- }
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- long[] a = { 17, 3, -42, 99, -7};
- AtomicLongArray ai = new AtomicLongArray(a);
- assertEquals(Arrays.toString(a), ai.toString());
- }
-
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java
deleted file mode 100755
index 491baf4..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import java.util.concurrent.atomic.*;
-import junit.framework.*;
-import java.util.*;
-
-public class AtomicLongFieldUpdaterTest extends JSR166TestCase {
- volatile long x = 0;
- int z;
- long w;
-
- public static Test suite() {
- return new TestSuite(AtomicLongFieldUpdaterTest.class);
- }
-
- /**
- * Construction with non-existent field throws RuntimeException
- */
- public void testConstructor() {
- try {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest>
- a = AtomicLongFieldUpdater.newUpdater
- (AtomicLongFieldUpdaterTest.class, "y");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * construction with field not of given type throws RuntimeException
- */
- public void testConstructor2() {
- try {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest>
- a = AtomicLongFieldUpdater.newUpdater
- (AtomicLongFieldUpdaterTest.class, "z");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * construction with non-volatile field throws RuntimeException
- */
- public void testConstructor3() {
- try {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest>
- a = AtomicLongFieldUpdater.newUpdater
- (AtomicLongFieldUpdaterTest.class, "w");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * get returns the last value set or assigned
- */
- public void testGetSet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.get(this));
- a.set(this,2);
- assertEquals(2,a.get(this));
- a.set(this,-3);
- assertEquals(-3,a.get(this));
- }
-
- /**
- * get returns the last value lazySet by same thread
- */
- public void testGetLazySet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.get(this));
- a.lazySet(this,2);
- assertEquals(2,a.get(this));
- a.lazySet(this,-3);
- assertEquals(-3,a.get(this));
- }
-
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertTrue(a.compareAndSet(this,1,2));
- assertTrue(a.compareAndSet(this,2,-4));
- assertEquals(-4,a.get(this));
- assertFalse(a.compareAndSet(this,-5,7));
- assertEquals(-4,a.get(this));
- assertTrue(a.compareAndSet(this,-4,7));
- assertEquals(7,a.get(this));
- }
-
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- x = 1;
- final AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest>a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!a.compareAndSet(AtomicLongFieldUpdaterTest.this, 2, 3))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(a.compareAndSet(this, 1, 2));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertEquals(a.get(this), 3);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- while (!a.weakCompareAndSet(this,1,2));
- while (!a.weakCompareAndSet(this,2,-4));
- assertEquals(-4,a.get(this));
- while (!a.weakCompareAndSet(this,-4,7));
- assertEquals(7,a.get(this));
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndSet(this, 0));
- assertEquals(0,a.getAndSet(this,-10));
- assertEquals(-10,a.getAndSet(this,1));
- }
-
- /**
- * getAndAdd returns previous value and adds given value
- */
- public void testGetAndAdd() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndAdd(this,2));
- assertEquals(3,a.get(this));
- assertEquals(3,a.getAndAdd(this,-4));
- assertEquals(-1,a.get(this));
- }
-
- /**
- * getAndDecrement returns previous value and decrements
- */
- public void testGetAndDecrement() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndDecrement(this));
- assertEquals(0,a.getAndDecrement(this));
- assertEquals(-1,a.getAndDecrement(this));
- }
-
- /**
- * getAndIncrement returns previous value and increments
- */
- public void testGetAndIncrement() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(1,a.getAndIncrement(this));
- assertEquals(2,a.get(this));
- a.set(this,-2);
- assertEquals(-2,a.getAndIncrement(this));
- assertEquals(-1,a.getAndIncrement(this));
- assertEquals(0,a.getAndIncrement(this));
- assertEquals(1,a.get(this));
- }
-
- /**
- * addAndGet adds given value to current, and returns current value
- */
- public void testAddAndGet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(3,a.addAndGet(this,2));
- assertEquals(3,a.get(this));
- assertEquals(-1,a.addAndGet(this,-4));
- assertEquals(-1,a.get(this));
- }
-
- /**
- * decrementAndGet decrements and returns current value
- */
- public void testDecrementAndGet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(0,a.decrementAndGet(this));
- assertEquals(-1,a.decrementAndGet(this));
- assertEquals(-2,a.decrementAndGet(this));
- assertEquals(-2,a.get(this));
- }
-
- /**
- * incrementAndGet increments and returns current value
- */
- public void testIncrementAndGet() {
- AtomicLongFieldUpdater<AtomicLongFieldUpdaterTest> a;
- try {
- a = AtomicLongFieldUpdater.newUpdater(AtomicLongFieldUpdaterTest.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = 1;
- assertEquals(2,a.incrementAndGet(this));
- assertEquals(2,a.get(this));
- a.set(this,-2);
- assertEquals(-1,a.incrementAndGet(this));
- assertEquals(0,a.incrementAndGet(this));
- assertEquals(1,a.incrementAndGet(this));
- assertEquals(1,a.get(this));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java
deleted file mode 100755
index e73e86e..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-
-public class AtomicLongTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicLongTest.class);
- }
-
- final long[] VALUES = {
- Long.MIN_VALUE,
- Integer.MIN_VALUE, -1, 0, 1, 42, Integer.MAX_VALUE,
- Long.MAX_VALUE,
- };
-
- /**
- * constructor initializes to given value
- */
- public void testConstructor() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.get());
- }
-
- /**
- * default constructed initializes to zero
- */
- public void testConstructor2() {
- AtomicLong ai = new AtomicLong();
- assertEquals(0,ai.get());
- }
-
- /**
- * get returns the last value set
- */
- public void testGetSet() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.get());
- ai.set(2);
- assertEquals(2,ai.get());
- ai.set(-3);
- assertEquals(-3,ai.get());
- }
-
- /**
- * get returns the last value lazySet in same thread
- */
- public void testGetLazySet() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.get());
- ai.lazySet(2);
- assertEquals(2,ai.get());
- ai.lazySet(-3);
- assertEquals(-3,ai.get());
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicLong ai = new AtomicLong(1);
- assertTrue(ai.compareAndSet(1,2));
- assertTrue(ai.compareAndSet(2,-4));
- assertEquals(-4,ai.get());
- assertFalse(ai.compareAndSet(-5,7));
- assertEquals(-4,ai.get());
- assertTrue(ai.compareAndSet(-4,7));
- assertEquals(7,ai.get());
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicLong ai = new AtomicLong(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(2, 3))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(1, 2));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertEquals(ai.get(), 3);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicLong ai = new AtomicLong(1);
- while (!ai.weakCompareAndSet(1,2));
- while (!ai.weakCompareAndSet(2,-4));
- assertEquals(-4,ai.get());
- while (!ai.weakCompareAndSet(-4,7));
- assertEquals(7,ai.get());
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.getAndSet(0));
- assertEquals(0,ai.getAndSet(-10));
- assertEquals(-10,ai.getAndSet(1));
- }
-
- /**
- * getAndAdd returns previous value and adds given value
- */
- public void testGetAndAdd() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.getAndAdd(2));
- assertEquals(3,ai.get());
- assertEquals(3,ai.getAndAdd(-4));
- assertEquals(-1,ai.get());
- }
-
- /**
- * getAndDecrement returns previous value and decrements
- */
- public void testGetAndDecrement() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.getAndDecrement());
- assertEquals(0,ai.getAndDecrement());
- assertEquals(-1,ai.getAndDecrement());
- }
-
- /**
- * getAndIncrement returns previous value and increments
- */
- public void testGetAndIncrement() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(1,ai.getAndIncrement());
- assertEquals(2,ai.get());
- ai.set(-2);
- assertEquals(-2,ai.getAndIncrement());
- assertEquals(-1,ai.getAndIncrement());
- assertEquals(0,ai.getAndIncrement());
- assertEquals(1,ai.get());
- }
-
- /**
- * addAndGet adds given value to current, and returns current value
- */
- public void testAddAndGet() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(3,ai.addAndGet(2));
- assertEquals(3,ai.get());
- assertEquals(-1,ai.addAndGet(-4));
- assertEquals(-1,ai.get());
- }
-
- /**
- * decrementAndGet decrements and returns current value
- */
- public void testDecrementAndGet() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(0,ai.decrementAndGet());
- assertEquals(-1,ai.decrementAndGet());
- assertEquals(-2,ai.decrementAndGet());
- assertEquals(-2,ai.get());
- }
-
- /**
- * incrementAndGet increments and returns current value
- */
- public void testIncrementAndGet() {
- AtomicLong ai = new AtomicLong(1);
- assertEquals(2,ai.incrementAndGet());
- assertEquals(2,ai.get());
- ai.set(-2);
- assertEquals(-1,ai.incrementAndGet());
- assertEquals(0,ai.incrementAndGet());
- assertEquals(1,ai.incrementAndGet());
- assertEquals(1,ai.get());
- }
-
- /**
- * a deserialized serialized atomic holds same value
- */
- public void testSerialization() throws Exception {
- AtomicLong l = new AtomicLong();
-
- l.set(-22);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicLong r = (AtomicLong) in.readObject();
- assertEquals(l.get(), r.get());
- }
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- AtomicLong ai = new AtomicLong();
- assertEquals("0", ai.toString());
- for (long i : VALUES) {
- ai.set(i);
- assertEquals(ai.toString(), Long.toString(i));
- }
- }
-
- /**
- * intValue returns current value.
- */
- public void testIntValue() {
- AtomicLong ai = new AtomicLong();
- assertEquals(0, ai.intValue());
- for (long x : VALUES) {
- ai.set(x);
- assertEquals((int)x, ai.intValue());
- }
- }
-
- /**
- * longValue returns current value.
- */
- public void testLongValue() {
- AtomicLong ai = new AtomicLong();
- assertEquals(0L, ai.longValue());
- for (long x : VALUES) {
- ai.set(x);
- assertEquals((long)x, ai.longValue());
- }
- }
-
- /**
- * floatValue returns current value.
- */
- public void testFloatValue() {
- AtomicLong ai = new AtomicLong();
- assertEquals(0.0f, ai.floatValue());
- for (long x : VALUES) {
- ai.set(x);
- assertEquals((float)x, ai.floatValue());
- }
- }
-
- /**
- * doubleValue returns current value.
- */
- public void testDoubleValue() {
- AtomicLong ai = new AtomicLong();
- assertEquals(0.0d, ai.doubleValue());
- for (long x : VALUES) {
- ai.set(x);
- assertEquals((double)x, ai.doubleValue());
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java
deleted file mode 100755
index 72a2337..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-
-public class AtomicMarkableReferenceTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicMarkableReferenceTest.class);
- }
-
- /**
- * constructor initializes to given reference and mark
- */
- public void testConstructor() {
- AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- assertSame(one,ai.getReference());
- assertFalse(ai.isMarked());
- AtomicMarkableReference a2 = new AtomicMarkableReference(null, true);
- assertNull(a2.getReference());
- assertTrue(a2.isMarked());
- }
-
- /**
- * get returns the last values of reference and mark set
- */
- public void testGetSet() {
- boolean[] mark = new boolean[1];
- AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- assertSame(one,ai.getReference());
- assertFalse(ai.isMarked());
- assertSame(one, ai.get(mark));
- assertFalse(mark[0]);
- ai.set(two, false);
- assertSame(two,ai.getReference());
- assertFalse(ai.isMarked());
- assertSame(two, ai.get(mark));
- assertFalse(mark[0]);
- ai.set(one, true);
- assertSame(one,ai.getReference());
- assertTrue(ai.isMarked());
- assertSame(one, ai.get(mark));
- assertTrue(mark[0]);
- }
-
- /**
- * attemptMark succeeds in single thread
- */
- public void testAttemptMark() {
- boolean[] mark = new boolean[1];
- AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- assertFalse(ai.isMarked());
- assertTrue(ai.attemptMark(one, true));
- assertTrue(ai.isMarked());
- assertSame(one, ai.get(mark));
- assertTrue(mark[0]);
- }
-
- /**
- * compareAndSet succeeds in changing values if equal to expected reference
- * and mark else fails
- */
- public void testCompareAndSet() {
- boolean[] mark = new boolean[1];
- AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- assertSame(one, ai.get(mark));
- assertFalse(ai.isMarked());
- assertFalse(mark[0]);
-
- assertTrue(ai.compareAndSet(one, two, false, false));
- assertSame(two, ai.get(mark));
- assertFalse(mark[0]);
-
- assertTrue(ai.compareAndSet(two, m3, false, true));
- assertSame(m3, ai.get(mark));
- assertTrue(mark[0]);
-
- assertFalse(ai.compareAndSet(two, m3, true, true));
- assertSame(m3, ai.get(mark));
- assertTrue(mark[0]);
- }
-
- /**
- * compareAndSet in one thread enables another waiting for reference value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(two, three, false, false))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(one, two, false, false));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(ai.getReference(), three);
- assertFalse(ai.isMarked());
- }
-
- /**
- * compareAndSet in one thread enables another waiting for mark value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads2() throws Exception {
- final AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(one, one, true, false))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(one, one, false, true));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(ai.getReference(), one);
- assertFalse(ai.isMarked());
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing values when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- boolean[] mark = new boolean[1];
- AtomicMarkableReference ai = new AtomicMarkableReference(one, false);
- assertSame(one, ai.get(mark));
- assertFalse(ai.isMarked());
- assertFalse(mark[0]);
-
- while (!ai.weakCompareAndSet(one, two, false, false));
- assertSame(two, ai.get(mark));
- assertFalse(mark[0]);
-
- while (!ai.weakCompareAndSet(two, m3, false, true));
- assertSame(m3, ai.get(mark));
- assertTrue(mark[0]);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java
deleted file mode 100644
index 25f8474..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-import java.util.*;
-
-public class AtomicReferenceArrayTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicReferenceArrayTest.class);
- }
-
- /**
- * constructor creates array of given size with all elements null
- */
- public void testConstructor() {
- AtomicReferenceArray<Integer> ai = new AtomicReferenceArray<Integer>(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertNull(ai.get(i));
- }
- }
-
- /**
- * constructor with null array throws NPE
- */
- public void testConstructor2NPE() {
- try {
- Integer[] a = null;
- AtomicReferenceArray<Integer> ai = new AtomicReferenceArray<Integer>(a);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * constructor with array is of same size and has all elements
- */
- public void testConstructor2() {
- Integer[] a = { two, one, three, four, seven};
- AtomicReferenceArray<Integer> ai = new AtomicReferenceArray<Integer>(a);
- assertEquals(a.length, ai.length());
- for (int i = 0; i < a.length; ++i)
- assertEquals(a[i], ai.get(i));
- }
-
-
- /**
- * get and set for out of bound indices throw IndexOutOfBoundsException
- */
- public void testIndexing() {
- AtomicReferenceArray<Integer> ai = new AtomicReferenceArray<Integer>(SIZE);
- try {
- ai.get(SIZE);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.get(-1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.set(SIZE, null);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- try {
- ai.set(-1, null);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {
- }
- }
-
- /**
- * get returns the last value set at index
- */
- public void testGetSet() {
- AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, one);
- assertSame(one,ai.get(i));
- ai.set(i, two);
- assertSame(two,ai.get(i));
- ai.set(i, m3);
- assertSame(m3,ai.get(i));
- }
- }
-
- /**
- * get returns the last value lazySet at index by same thread
- */
- public void testGetLazySet() {
- AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.lazySet(i, one);
- assertSame(one,ai.get(i));
- ai.lazySet(i, two);
- assertSame(two,ai.get(i));
- ai.lazySet(i, m3);
- assertSame(m3,ai.get(i));
- }
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, one);
- assertTrue(ai.compareAndSet(i, one,two));
- assertTrue(ai.compareAndSet(i, two,m4));
- assertSame(m4,ai.get(i));
- assertFalse(ai.compareAndSet(i, m5,seven));
- assertSame(m4,ai.get(i));
- assertTrue(ai.compareAndSet(i, m4,seven));
- assertSame(seven,ai.get(i));
- }
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws InterruptedException {
- final AtomicReferenceArray a = new AtomicReferenceArray(1);
- a.set(0, one);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!a.compareAndSet(0, two, three))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(a.compareAndSet(0, one, two));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(a.get(0), three);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, one);
- while (!ai.weakCompareAndSet(i, one,two));
- while (!ai.weakCompareAndSet(i, two,m4));
- assertSame(m4,ai.get(i));
- while (!ai.weakCompareAndSet(i, m4,seven));
- assertSame(seven,ai.get(i));
- }
- }
-
- /**
- * getAndSet returns previous value and sets to given value at given index
- */
- public void testGetAndSet() {
- AtomicReferenceArray ai = new AtomicReferenceArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- ai.set(i, one);
- assertSame(one,ai.getAndSet(i,zero));
- assertSame(zero,ai.getAndSet(i,m10));
- assertSame(m10,ai.getAndSet(i,one));
- }
- }
-
- /**
- * a deserialized serialized array holds same values
- */
- public void testSerialization() throws Exception {
- AtomicReferenceArray l = new AtomicReferenceArray(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- l.set(i, new Integer(-i));
- }
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicReferenceArray r = (AtomicReferenceArray) in.readObject();
- assertEquals(l.length(), r.length());
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(r.get(i), l.get(i));
- }
- }
-
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- Integer[] a = { two, one, three, four, seven};
- AtomicReferenceArray<Integer> ai = new AtomicReferenceArray<Integer>(a);
- assertEquals(Arrays.toString(a), ai.toString());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java
deleted file mode 100755
index 78c321e..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import java.util.concurrent.atomic.*;
-import junit.framework.*;
-import java.util.*;
-
-public class AtomicReferenceFieldUpdaterTest extends JSR166TestCase {
- volatile Integer x = null;
- Object z;
- Integer w;
-
- public static Test suite() {
- return new TestSuite(AtomicReferenceFieldUpdaterTest.class);
- }
-
- /**
- * Construction with non-existent field throws RuntimeException
- */
- public void testConstructor() {
- try {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>
- a = AtomicReferenceFieldUpdater.newUpdater
- (AtomicReferenceFieldUpdaterTest.class, Integer.class, "y");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
-
- /**
- * construction with field not of given type throws RuntimeException
- */
- public void testConstructor2() {
- try {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>
- a = AtomicReferenceFieldUpdater.newUpdater
- (AtomicReferenceFieldUpdaterTest.class, Integer.class, "z");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * Constructor with non-volatile field throws exception
- */
- public void testConstructor3() {
- try {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>
- a = AtomicReferenceFieldUpdater.newUpdater
- (AtomicReferenceFieldUpdaterTest.class, Integer.class, "w");
- shouldThrow();
- } catch (RuntimeException success) {}
- }
-
- /**
- * get returns the last value set or assigned
- */
- public void testGetSet() {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>a;
- try {
- a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = one;
- assertSame(one,a.get(this));
- a.set(this,two);
- assertSame(two,a.get(this));
- a.set(this,m3);
- assertSame(m3,a.get(this));
- }
-
- /**
- * get returns the last value lazySet by same thread
- */
- public void testGetLazySet() {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>a;
- try {
- a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = one;
- assertSame(one,a.get(this));
- a.lazySet(this,two);
- assertSame(two,a.get(this));
- a.lazySet(this,m3);
- assertSame(m3,a.get(this));
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>a;
- try {
- a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = one;
- assertTrue(a.compareAndSet(this,one,two));
- assertTrue(a.compareAndSet(this,two,m4));
- assertSame(m4,a.get(this));
- assertFalse(a.compareAndSet(this,m5,seven));
- assertFalse(seven == a.get(this));
- assertTrue(a.compareAndSet(this,m4,seven));
- assertSame(seven,a.get(this));
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- x = one;
- final AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>a;
- try {
- a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!a.compareAndSet(AtomicReferenceFieldUpdaterTest.this, two, three))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(a.compareAndSet(this, one, two));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(a.get(this), three);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>a;
- try {
- a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = one;
- while (!a.weakCompareAndSet(this,one,two));
- while (!a.weakCompareAndSet(this,two,m4));
- assertSame(m4,a.get(this));
- while (!a.weakCompareAndSet(this,m4,seven));
- assertSame(seven,a.get(this));
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer>a;
- try {
- a = AtomicReferenceFieldUpdater.newUpdater(AtomicReferenceFieldUpdaterTest.class, Integer.class, "x");
- } catch (RuntimeException ok) {
- return;
- }
- x = one;
- assertSame(one,a.getAndSet(this, zero));
- assertSame(zero,a.getAndSet(this,m10));
- assertSame(m10,a.getAndSet(this,1));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java
deleted file mode 100755
index 5046ee8..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-import java.io.*;
-
-public class AtomicReferenceTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicReferenceTest.class);
- }
-
- /**
- * constructor initializes to given value
- */
- public void testConstructor() {
- AtomicReference ai = new AtomicReference(one);
- assertSame(one,ai.get());
- }
-
- /**
- * default constructed initializes to null
- */
- public void testConstructor2() {
- AtomicReference ai = new AtomicReference();
- assertNull(ai.get());
- }
-
- /**
- * get returns the last value set
- */
- public void testGetSet() {
- AtomicReference ai = new AtomicReference(one);
- assertSame(one,ai.get());
- ai.set(two);
- assertSame(two,ai.get());
- ai.set(m3);
- assertSame(m3,ai.get());
- }
-
- /**
- * get returns the last value lazySet in same thread
- */
- public void testGetLazySet() {
- AtomicReference ai = new AtomicReference(one);
- assertSame(one,ai.get());
- ai.lazySet(two);
- assertSame(two,ai.get());
- ai.lazySet(m3);
- assertSame(m3,ai.get());
- }
-
- /**
- * compareAndSet succeeds in changing value if equal to expected else fails
- */
- public void testCompareAndSet() {
- AtomicReference ai = new AtomicReference(one);
- assertTrue(ai.compareAndSet(one,two));
- assertTrue(ai.compareAndSet(two,m4));
- assertSame(m4,ai.get());
- assertFalse(ai.compareAndSet(m5,seven));
- assertSame(m4,ai.get());
- assertTrue(ai.compareAndSet(m4,seven));
- assertSame(seven,ai.get());
- }
-
- /**
- * compareAndSet in one thread enables another waiting for value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicReference ai = new AtomicReference(one);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(two, three))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(one, two));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(ai.get(), three);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing value when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- AtomicReference ai = new AtomicReference(one);
- while (!ai.weakCompareAndSet(one,two));
- while (!ai.weakCompareAndSet(two,m4));
- assertSame(m4,ai.get());
- while (!ai.weakCompareAndSet(m4,seven));
- assertSame(seven,ai.get());
- }
-
- /**
- * getAndSet returns previous value and sets to given value
- */
- public void testGetAndSet() {
- AtomicReference ai = new AtomicReference(one);
- assertSame(one,ai.getAndSet(zero));
- assertSame(zero,ai.getAndSet(m10));
- assertSame(m10,ai.getAndSet(one));
- }
-
- /**
- * a deserialized serialized atomic holds same value
- */
- public void testSerialization() throws Exception {
- AtomicReference l = new AtomicReference();
-
- l.set(one);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- AtomicReference r = (AtomicReference) in.readObject();
- assertEquals(l.get(), r.get());
- }
-
- /**
- * toString returns current value.
- */
- public void testToString() {
- AtomicReference<Integer> ai = new AtomicReference<Integer>(one);
- assertEquals(ai.toString(), one.toString());
- ai.set(two);
- assertEquals(ai.toString(), two.toString());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java b/luni/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java
deleted file mode 100755
index ca9b724..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.atomic.*;
-
-public class AtomicStampedReferenceTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(AtomicStampedReferenceTest.class);
- }
-
- /**
- * constructor initializes to given reference and stamp
- */
- public void testConstructor() {
- AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- assertSame(one,ai.getReference());
- assertEquals(0, ai.getStamp());
- AtomicStampedReference a2 = new AtomicStampedReference(null, 1);
- assertNull(a2.getReference());
- assertEquals(1, a2.getStamp());
- }
-
- /**
- * get returns the last values of reference and stamp set
- */
- public void testGetSet() {
- int[] mark = new int[1];
- AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- assertSame(one,ai.getReference());
- assertEquals(0, ai.getStamp());
- assertSame(one, ai.get(mark));
- assertEquals(0, mark[0]);
- ai.set(two, 0);
- assertSame(two,ai.getReference());
- assertEquals(0, ai.getStamp());
- assertSame(two, ai.get(mark));
- assertEquals(0, mark[0]);
- ai.set(one, 1);
- assertSame(one,ai.getReference());
- assertEquals(1, ai.getStamp());
- assertSame(one, ai.get(mark));
- assertEquals(1,mark[0]);
- }
-
- /**
- * attemptStamp succeeds in single thread
- */
- public void testAttemptStamp() {
- int[] mark = new int[1];
- AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- assertEquals(0, ai.getStamp());
- assertTrue(ai.attemptStamp(one, 1));
- assertEquals(1, ai.getStamp());
- assertSame(one, ai.get(mark));
- assertEquals(1, mark[0]);
- }
-
- /**
- * compareAndSet succeeds in changing values if equal to expected reference
- * and stamp else fails
- */
- public void testCompareAndSet() {
- int[] mark = new int[1];
- AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- assertSame(one, ai.get(mark));
- assertEquals(0, ai.getStamp());
- assertEquals(0, mark[0]);
-
- assertTrue(ai.compareAndSet(one, two, 0, 0));
- assertSame(two, ai.get(mark));
- assertEquals(0, mark[0]);
-
- assertTrue(ai.compareAndSet(two, m3, 0, 1));
- assertSame(m3, ai.get(mark));
- assertEquals(1, mark[0]);
-
- assertFalse(ai.compareAndSet(two, m3, 1, 1));
- assertSame(m3, ai.get(mark));
- assertEquals(1, mark[0]);
- }
-
- /**
- * compareAndSet in one thread enables another waiting for reference value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads() throws Exception {
- final AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(two, three, 0, 0))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(one, two, 0, 0));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(ai.getReference(), three);
- assertEquals(ai.getStamp(), 0);
- }
-
- /**
- * compareAndSet in one thread enables another waiting for stamp value
- * to succeed
- */
- public void testCompareAndSetInMultipleThreads2() throws Exception {
- final AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- while (!ai.compareAndSet(one, one, 1, 2))
- Thread.yield();
- }});
-
- t.start();
- assertTrue(ai.compareAndSet(one, one, 0, 1));
- t.join(LONG_DELAY_MS);
- assertFalse(t.isAlive());
- assertSame(ai.getReference(), one);
- assertEquals(ai.getStamp(), 2);
- }
-
- /**
- * repeated weakCompareAndSet succeeds in changing values when equal
- * to expected
- */
- public void testWeakCompareAndSet() {
- int[] mark = new int[1];
- AtomicStampedReference ai = new AtomicStampedReference(one, 0);
- assertSame(one, ai.get(mark));
- assertEquals(0, ai.getStamp ());
- assertEquals(0, mark[0]);
-
- while (!ai.weakCompareAndSet(one, two, 0, 0));
- assertSame(two, ai.get(mark));
- assertEquals(0, mark[0]);
-
- while (!ai.weakCompareAndSet(two, m3, 0, 1));
- assertSame(m3, ai.get(mark));
- assertEquals(1, mark[0]);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java
deleted file mode 100755
index 9b355f5..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java
+++ /dev/null
@@ -1,596 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.Enumeration;
-import java.io.*;
-
-public class ConcurrentHashMapTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ConcurrentHashMapTest.class);
- }
-
- /**
- * Create a map from Integers 1-5 to Strings "A"-"E".
- */
- private static ConcurrentHashMap map5() {
- ConcurrentHashMap map = new ConcurrentHashMap(5);
- assertTrue(map.isEmpty());
- map.put(one, "A");
- map.put(two, "B");
- map.put(three, "C");
- map.put(four, "D");
- map.put(five, "E");
- assertFalse(map.isEmpty());
- assertEquals(5, map.size());
- return map;
- }
-
- /**
- * clear removes all pairs
- */
- public void testClear() {
- ConcurrentHashMap map = map5();
- map.clear();
- assertEquals(map.size(), 0);
- }
-
- /**
- * Maps with same contents are equal
- */
- public void testEquals() {
- ConcurrentHashMap map1 = map5();
- ConcurrentHashMap map2 = map5();
- assertEquals(map1, map2);
- assertEquals(map2, map1);
- map1.clear();
- assertFalse(map1.equals(map2));
- assertFalse(map2.equals(map1));
- }
-
- /**
- * contains returns true for contained value
- */
- public void testContains() {
- ConcurrentHashMap map = map5();
- assertTrue(map.contains("A"));
- assertFalse(map.contains("Z"));
- }
-
- /**
- * containsKey returns true for contained key
- */
- public void testContainsKey() {
- ConcurrentHashMap map = map5();
- assertTrue(map.containsKey(one));
- assertFalse(map.containsKey(zero));
- }
-
- /**
- * containsValue returns true for held values
- */
- public void testContainsValue() {
- ConcurrentHashMap map = map5();
- assertTrue(map.containsValue("A"));
- assertFalse(map.containsValue("Z"));
- }
-
- /**
- * enumeration returns an enumeration containing the correct
- * elements
- */
- public void testEnumeration() {
- ConcurrentHashMap map = map5();
- Enumeration e = map.elements();
- int count = 0;
- while (e.hasMoreElements()) {
- count++;
- e.nextElement();
- }
- assertEquals(5, count);
- }
-
- /**
- * get returns the correct element at the given key,
- * or null if not present
- */
- public void testGet() {
- ConcurrentHashMap map = map5();
- assertEquals("A", (String)map.get(one));
- ConcurrentHashMap empty = new ConcurrentHashMap();
- assertNull(map.get("anything"));
- }
-
- /**
- * isEmpty is true of empty map and false for non-empty
- */
- public void testIsEmpty() {
- ConcurrentHashMap empty = new ConcurrentHashMap();
- ConcurrentHashMap map = map5();
- assertTrue(empty.isEmpty());
- assertFalse(map.isEmpty());
- }
-
- /**
- * keys returns an enumeration containing all the keys from the map
- */
- public void testKeys() {
- ConcurrentHashMap map = map5();
- Enumeration e = map.keys();
- int count = 0;
- while (e.hasMoreElements()) {
- count++;
- e.nextElement();
- }
- assertEquals(5, count);
- }
-
- /**
- * keySet returns a Set containing all the keys
- */
- public void testKeySet() {
- ConcurrentHashMap map = map5();
- Set s = map.keySet();
- assertEquals(5, s.size());
- assertTrue(s.contains(one));
- assertTrue(s.contains(two));
- assertTrue(s.contains(three));
- assertTrue(s.contains(four));
- assertTrue(s.contains(five));
- }
-
- /**
- * keySet.toArray returns contains all keys
- */
- public void testKeySetToArray() {
- ConcurrentHashMap map = map5();
- Set s = map.keySet();
- Object[] ar = s.toArray();
- assertTrue(s.containsAll(Arrays.asList(ar)));
- assertEquals(5, ar.length);
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * Values.toArray contains all values
- */
- public void testValuesToArray() {
- ConcurrentHashMap map = map5();
- Collection v = map.values();
- Object[] ar = v.toArray();
- ArrayList s = new ArrayList(Arrays.asList(ar));
- assertEquals(5, ar.length);
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
- /**
- * entrySet.toArray contains all entries
- */
- public void testEntrySetToArray() {
- ConcurrentHashMap map = map5();
- Set s = map.entrySet();
- Object[] ar = s.toArray();
- assertEquals(5, ar.length);
- for (int i = 0; i < 5; ++i) {
- assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
- assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
- }
- }
-
- /**
- * values collection contains all values
- */
- public void testValues() {
- ConcurrentHashMap map = map5();
- Collection s = map.values();
- assertEquals(5, s.size());
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
- /**
- * entrySet contains all pairs
- */
- public void testEntrySet() {
- ConcurrentHashMap map = map5();
- Set s = map.entrySet();
- assertEquals(5, s.size());
- Iterator it = s.iterator();
- while (it.hasNext()) {
- Map.Entry e = (Map.Entry) it.next();
- assertTrue(
- (e.getKey().equals(one) && e.getValue().equals("A")) ||
- (e.getKey().equals(two) && e.getValue().equals("B")) ||
- (e.getKey().equals(three) && e.getValue().equals("C")) ||
- (e.getKey().equals(four) && e.getValue().equals("D")) ||
- (e.getKey().equals(five) && e.getValue().equals("E")));
- }
- }
-
- /**
- * putAll adds all key-value pairs from the given map
- */
- public void testPutAll() {
- ConcurrentHashMap empty = new ConcurrentHashMap();
- ConcurrentHashMap map = map5();
- empty.putAll(map);
- assertEquals(5, empty.size());
- assertTrue(empty.containsKey(one));
- assertTrue(empty.containsKey(two));
- assertTrue(empty.containsKey(three));
- assertTrue(empty.containsKey(four));
- assertTrue(empty.containsKey(five));
- }
-
- /**
- * putIfAbsent works when the given key is not present
- */
- public void testPutIfAbsent() {
- ConcurrentHashMap map = map5();
- map.putIfAbsent(six, "Z");
- assertTrue(map.containsKey(six));
- }
-
- /**
- * putIfAbsent does not add the pair if the key is already present
- */
- public void testPutIfAbsent2() {
- ConcurrentHashMap map = map5();
- assertEquals("A", map.putIfAbsent(one, "Z"));
- }
-
- /**
- * replace fails when the given key is not present
- */
- public void testReplace() {
- ConcurrentHashMap map = map5();
- assertNull(map.replace(six, "Z"));
- assertFalse(map.containsKey(six));
- }
-
- /**
- * replace succeeds if the key is already present
- */
- public void testReplace2() {
- ConcurrentHashMap map = map5();
- assertNotNull(map.replace(one, "Z"));
- assertEquals("Z", map.get(one));
- }
-
-
- /**
- * replace value fails when the given key not mapped to expected value
- */
- public void testReplaceValue() {
- ConcurrentHashMap map = map5();
- assertEquals("A", map.get(one));
- assertFalse(map.replace(one, "Z", "Z"));
- assertEquals("A", map.get(one));
- }
-
- /**
- * replace value succeeds when the given key mapped to expected value
- */
- public void testReplaceValue2() {
- ConcurrentHashMap map = map5();
- assertEquals("A", map.get(one));
- assertTrue(map.replace(one, "A", "Z"));
- assertEquals("Z", map.get(one));
- }
-
-
- /**
- * remove removes the correct key-value pair from the map
- */
- public void testRemove() {
- ConcurrentHashMap map = map5();
- map.remove(five);
- assertEquals(4, map.size());
- assertFalse(map.containsKey(five));
- }
-
- /**
- * remove(key,value) removes only if pair present
- */
- public void testRemove2() {
- ConcurrentHashMap map = map5();
- map.remove(five, "E");
- assertEquals(4, map.size());
- assertFalse(map.containsKey(five));
- map.remove(four, "A");
- assertEquals(4, map.size());
- assertTrue(map.containsKey(four));
- }
-
- /**
- * size returns the correct values
- */
- public void testSize() {
- ConcurrentHashMap map = map5();
- ConcurrentHashMap empty = new ConcurrentHashMap();
- assertEquals(0, empty.size());
- assertEquals(5, map.size());
- }
-
- /**
- * toString contains toString of elements
- */
- public void testToString() {
- ConcurrentHashMap map = map5();
- String s = map.toString();
- for (int i = 1; i <= 5; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- // Exception tests
-
- /**
- * Cannot create with negative capacity
- */
- public void testConstructor1() {
- try {
- new ConcurrentHashMap(-1,0,1);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Cannot create with negative concurrency level
- */
- public void testConstructor2() {
- try {
- new ConcurrentHashMap(1,0,-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Cannot create with only negative capacity
- */
- public void testConstructor3() {
- try {
- new ConcurrentHashMap(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * get(null) throws NPE
- */
- public void testGet_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.get(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsKey(null) throws NPE
- */
- public void testContainsKey_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.containsKey(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsValue(null) throws NPE
- */
- public void testContainsValue_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.containsValue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * contains(null) throws NPE
- */
- public void testContains_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.contains(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * put(null,x) throws NPE
- */
- public void testPut1_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.put(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * put(x, null) throws NPE
- */
- public void testPut2_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.put("whatever", null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * putIfAbsent(null, x) throws NPE
- */
- public void testPutIfAbsent1_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.putIfAbsent(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x) throws NPE
- */
- public void testReplace_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.replace(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x, y) throws NPE
- */
- public void testReplaceValue_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.replace(null, one, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * putIfAbsent(x, null) throws NPE
- */
- public void testPutIfAbsent2_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.putIfAbsent("whatever", null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * replace(x, null) throws NPE
- */
- public void testReplace2_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.replace("whatever", null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(x, null, y) throws NPE
- */
- public void testReplaceValue2_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.replace("whatever", null, "A");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(x, y, null) throws NPE
- */
- public void testReplaceValue3_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.replace("whatever", one, null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * remove(null) throws NPE
- */
- public void testRemove1_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.put("sadsdf", "asdads");
- c.remove(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null, x) throws NPE
- */
- public void testRemove2_NullPointerException() {
- try {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.put("sadsdf", "asdads");
- c.remove(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(x, null) returns false
- */
- public void testRemove3() {
- ConcurrentHashMap c = new ConcurrentHashMap(5);
- c.put("sadsdf", "asdads");
- assertFalse(c.remove("sadsdf", null));
- }
-
- /**
- * A deserialized map equals original
- */
- public void testSerialization() throws Exception {
- ConcurrentHashMap q = map5();
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ConcurrentHashMap r = (ConcurrentHashMap)in.readObject();
- assertEquals(q.size(), r.size());
- assertTrue(q.equals(r));
- assertTrue(r.equals(q));
- }
-
-
- /**
- * SetValue of an EntrySet entry sets value in the map.
- */
- public void testSetValueWriteThrough() {
- // Adapted from a bug report by Eric Zoerner
- ConcurrentHashMap map = new ConcurrentHashMap(2, 5.0f, 1);
- assertTrue(map.isEmpty());
- for (int i = 0; i < 20; i++)
- map.put(new Integer(i), new Integer(i));
- assertFalse(map.isEmpty());
- Map.Entry entry1 = (Map.Entry)map.entrySet().iterator().next();
-
- // assert that entry1 is not 16
- assertTrue("entry is 16, test not valid",
- !entry1.getKey().equals(new Integer(16)));
-
- // remove 16 (a different key) from map
- // which just happens to cause entry1 to be cloned in map
- map.remove(new Integer(16));
- entry1.setValue("XYZ");
- assertTrue(map.containsValue("XYZ")); // fails
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java
deleted file mode 100755
index 1fbc729..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java
+++ /dev/null
@@ -1,507 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class ConcurrentLinkedQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ConcurrentLinkedQueueTest.class);
- }
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private ConcurrentLinkedQueue populatedQueue(int n) {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- assertTrue(q.isEmpty());
- for (int i = 0; i < n; ++i)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * new queue is empty
- */
- public void testConstructor1() {
- assertEquals(0, new ConcurrentLinkedQueue().size());
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue((Collection)null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- assertTrue(q.isEmpty());
- q.add(one);
- assertFalse(q.isEmpty());
- q.add(two);
- q.remove();
- q.remove();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * Offer returns true
- */
- public void testOffer() {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- assertTrue(q.offer(zero));
- assertTrue(q.offer(one));
- }
-
- /**
- * add returns true
- */
- public void testAdd() {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- assertTrue(q.add(new Integer(i)));
- }
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements, in traversal order, of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.poll());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.element());
- assertEquals(i, q.poll());
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.poll();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(one);
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- ConcurrentLinkedQueue p = new ConcurrentLinkedQueue();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if change
- */
- public void testRetainAll() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- ConcurrentLinkedQueue p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- ConcurrentLinkedQueue p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.poll());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws ArrayStoreException
- */
- public void testToArray1_BadArg() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator ordering is FIFO
- */
- public void testIteratorOrdering() {
- final ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- q.add(one);
- q.add(two);
- q.add(three);
-
- int k = 0;
- for (Iterator it = q.iterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
-
- assertEquals(3, k);
- }
-
- /**
- * Modifications do not cause iterators to fail
- */
- public void testWeaklyConsistentIteration () {
- final ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- q.add(one);
- q.add(two);
- q.add(three);
-
- for (Iterator it = q.iterator(); it.hasNext();) {
- q.remove();
- it.next();
- }
-
- assertEquals("queue should be empty again", 0, q.size());
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final ConcurrentLinkedQueue q = new ConcurrentLinkedQueue();
- q.add(one);
- q.add(two);
- q.add(three);
- Iterator it = q.iterator();
- it.next();
- it.remove();
- it = q.iterator();
- assertSame(it.next(), two);
- assertSame(it.next(), three);
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * A deserialized serialized queue has same elements in same order
- */
- public void testSerialization() throws Exception {
- ConcurrentLinkedQueue q = populatedQueue(SIZE);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ConcurrentLinkedQueue r = (ConcurrentLinkedQueue)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListMapTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListMapTest.java
deleted file mode 100644
index 3cf5b75..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListMapTest.java
+++ /dev/null
@@ -1,1280 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class ConcurrentSkipListMapTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ConcurrentSkipListMapTest.class);
- }
-
- /**
- * Create a map from Integers 1-5 to Strings "A"-"E".
- */
- private static ConcurrentSkipListMap map5() {
- ConcurrentSkipListMap map = new ConcurrentSkipListMap();
- assertTrue(map.isEmpty());
- map.put(one, "A");
- map.put(five, "E");
- map.put(three, "C");
- map.put(two, "B");
- map.put(four, "D");
- assertFalse(map.isEmpty());
- assertEquals(5, map.size());
- return map;
- }
-
- /**
- * clear removes all pairs
- */
- public void testClear() {
- ConcurrentSkipListMap map = map5();
- map.clear();
- assertEquals(map.size(), 0);
- }
-
- /**
- *
- */
- public void testConstructFromSorted() {
- ConcurrentSkipListMap map = map5();
- ConcurrentSkipListMap map2 = new ConcurrentSkipListMap(map);
- assertEquals(map, map2);
- }
-
- /**
- * Maps with same contents are equal
- */
- public void testEquals() {
- ConcurrentSkipListMap map1 = map5();
- ConcurrentSkipListMap map2 = map5();
- assertEquals(map1, map2);
- assertEquals(map2, map1);
- map1.clear();
- assertFalse(map1.equals(map2));
- assertFalse(map2.equals(map1));
- }
-
- /**
- * containsKey returns true for contained key
- */
- public void testContainsKey() {
- ConcurrentSkipListMap map = map5();
- assertTrue(map.containsKey(one));
- assertFalse(map.containsKey(zero));
- }
-
- /**
- * containsValue returns true for held values
- */
- public void testContainsValue() {
- ConcurrentSkipListMap map = map5();
- assertTrue(map.containsValue("A"));
- assertFalse(map.containsValue("Z"));
- }
-
- /**
- * get returns the correct element at the given key,
- * or null if not present
- */
- public void testGet() {
- ConcurrentSkipListMap map = map5();
- assertEquals("A", (String)map.get(one));
- ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
- assertNull(empty.get(one));
- }
-
- /**
- * isEmpty is true of empty map and false for non-empty
- */
- public void testIsEmpty() {
- ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
- ConcurrentSkipListMap map = map5();
- assertTrue(empty.isEmpty());
- assertFalse(map.isEmpty());
- }
-
- /**
- * firstKey returns first key
- */
- public void testFirstKey() {
- ConcurrentSkipListMap map = map5();
- assertEquals(one, map.firstKey());
- }
-
- /**
- * lastKey returns last key
- */
- public void testLastKey() {
- ConcurrentSkipListMap map = map5();
- assertEquals(five, map.lastKey());
- }
-
-
- /**
- * keySet.toArray returns contains all keys
- */
- public void testKeySetToArray() {
- ConcurrentSkipListMap map = map5();
- Set s = map.keySet();
- Object[] ar = s.toArray();
- assertTrue(s.containsAll(Arrays.asList(ar)));
- assertEquals(5, ar.length);
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * descendingkeySet.toArray returns contains all keys
- */
- public void testDescendingKeySetToArray() {
- ConcurrentSkipListMap map = map5();
- Set s = map.descendingKeySet();
- Object[] ar = s.toArray();
- assertEquals(5, ar.length);
- assertTrue(s.containsAll(Arrays.asList(ar)));
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * keySet returns a Set containing all the keys
- */
- public void testKeySet() {
- ConcurrentSkipListMap map = map5();
- Set s = map.keySet();
- assertEquals(5, s.size());
- assertTrue(s.contains(one));
- assertTrue(s.contains(two));
- assertTrue(s.contains(three));
- assertTrue(s.contains(four));
- assertTrue(s.contains(five));
- }
-
- /**
- * keySet is ordered
- */
- public void testKeySetOrder() {
- ConcurrentSkipListMap map = map5();
- Set s = map.keySet();
- Iterator i = s.iterator();
- Integer last = (Integer)i.next();
- assertEquals(last, one);
- int count = 1;
- while (i.hasNext()) {
- Integer k = (Integer)i.next();
- assertTrue(last.compareTo(k) < 0);
- last = k;
- ++count;
- }
- assertEquals(count ,5);
- }
-
- /**
- * descending iterator of key set is inverse ordered
- */
- public void testKeySetDescendingIteratorOrder() {
- ConcurrentSkipListMap map = map5();
- NavigableSet s = map.navigableKeySet();
- Iterator i = s.descendingIterator();
- Integer last = (Integer)i.next();
- assertEquals(last, five);
- int count = 1;
- while (i.hasNext()) {
- Integer k = (Integer)i.next();
- assertTrue(last.compareTo(k) > 0);
- last = k;
- ++count;
- }
- assertEquals(count ,5);
- }
-
- /**
- * descendingKeySet is ordered
- */
- public void testDescendingKeySetOrder() {
- ConcurrentSkipListMap map = map5();
- Set s = map.descendingKeySet();
- Iterator i = s.iterator();
- Integer last = (Integer)i.next();
- assertEquals(last, five);
- int count = 1;
- while (i.hasNext()) {
- Integer k = (Integer)i.next();
- assertTrue(last.compareTo(k) > 0);
- last = k;
- ++count;
- }
- assertEquals(count, 5);
- }
-
- /**
- * descending iterator of descendingKeySet is ordered
- */
- public void testDescendingKeySetDescendingIteratorOrder() {
- ConcurrentSkipListMap map = map5();
- NavigableSet s = map.descendingKeySet();
- Iterator i = s.descendingIterator();
- Integer last = (Integer)i.next();
- assertEquals(last, one);
- int count = 1;
- while (i.hasNext()) {
- Integer k = (Integer)i.next();
- assertTrue(last.compareTo(k) < 0);
- last = k;
- ++count;
- }
- assertEquals(count, 5);
- }
-
- /**
- * Values.toArray contains all values
- */
- public void testValuesToArray() {
- ConcurrentSkipListMap map = map5();
- Collection v = map.values();
- Object[] ar = v.toArray();
- ArrayList s = new ArrayList(Arrays.asList(ar));
- assertEquals(5, ar.length);
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
- /**
- * values collection contains all values
- */
- public void testValues() {
- ConcurrentSkipListMap map = map5();
- Collection s = map.values();
- assertEquals(5, s.size());
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
- /**
- * entrySet contains all pairs
- */
- public void testEntrySet() {
- ConcurrentSkipListMap map = map5();
- Set s = map.entrySet();
- assertEquals(5, s.size());
- Iterator it = s.iterator();
- while (it.hasNext()) {
- Map.Entry e = (Map.Entry) it.next();
- assertTrue(
- (e.getKey().equals(one) && e.getValue().equals("A")) ||
- (e.getKey().equals(two) && e.getValue().equals("B")) ||
- (e.getKey().equals(three) && e.getValue().equals("C")) ||
- (e.getKey().equals(four) && e.getValue().equals("D")) ||
- (e.getKey().equals(five) && e.getValue().equals("E")));
- }
- }
-
- /**
- * descendingEntrySet contains all pairs
- */
- public void testDescendingEntrySet() {
- ConcurrentSkipListMap map = map5();
- Set s = map.descendingMap().entrySet();
- assertEquals(5, s.size());
- Iterator it = s.iterator();
- while (it.hasNext()) {
- Map.Entry e = (Map.Entry) it.next();
- assertTrue(
- (e.getKey().equals(one) && e.getValue().equals("A")) ||
- (e.getKey().equals(two) && e.getValue().equals("B")) ||
- (e.getKey().equals(three) && e.getValue().equals("C")) ||
- (e.getKey().equals(four) && e.getValue().equals("D")) ||
- (e.getKey().equals(five) && e.getValue().equals("E")));
- }
- }
-
- /**
- * entrySet.toArray contains all entries
- */
- public void testEntrySetToArray() {
- ConcurrentSkipListMap map = map5();
- Set s = map.entrySet();
- Object[] ar = s.toArray();
- assertEquals(5, ar.length);
- for (int i = 0; i < 5; ++i) {
- assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
- assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
- }
- }
-
- /**
- * descendingEntrySet.toArray contains all entries
- */
- public void testDescendingEntrySetToArray() {
- ConcurrentSkipListMap map = map5();
- Set s = map.descendingMap().entrySet();
- Object[] ar = s.toArray();
- assertEquals(5, ar.length);
- for (int i = 0; i < 5; ++i) {
- assertTrue(map.containsKey(((Map.Entry)(ar[i])).getKey()));
- assertTrue(map.containsValue(((Map.Entry)(ar[i])).getValue()));
- }
- }
-
- /**
- * putAll adds all key-value pairs from the given map
- */
- public void testPutAll() {
- ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
- ConcurrentSkipListMap map = map5();
- empty.putAll(map);
- assertEquals(5, empty.size());
- assertTrue(empty.containsKey(one));
- assertTrue(empty.containsKey(two));
- assertTrue(empty.containsKey(three));
- assertTrue(empty.containsKey(four));
- assertTrue(empty.containsKey(five));
- }
-
- /**
- * putIfAbsent works when the given key is not present
- */
- public void testPutIfAbsent() {
- ConcurrentSkipListMap map = map5();
- map.putIfAbsent(six, "Z");
- assertTrue(map.containsKey(six));
- }
-
- /**
- * putIfAbsent does not add the pair if the key is already present
- */
- public void testPutIfAbsent2() {
- ConcurrentSkipListMap map = map5();
- assertEquals("A", map.putIfAbsent(one, "Z"));
- }
-
- /**
- * replace fails when the given key is not present
- */
- public void testReplace() {
- ConcurrentSkipListMap map = map5();
- assertNull(map.replace(six, "Z"));
- assertFalse(map.containsKey(six));
- }
-
- /**
- * replace succeeds if the key is already present
- */
- public void testReplace2() {
- ConcurrentSkipListMap map = map5();
- assertNotNull(map.replace(one, "Z"));
- assertEquals("Z", map.get(one));
- }
-
-
- /**
- * replace value fails when the given key not mapped to expected value
- */
- public void testReplaceValue() {
- ConcurrentSkipListMap map = map5();
- assertEquals("A", map.get(one));
- assertFalse(map.replace(one, "Z", "Z"));
- assertEquals("A", map.get(one));
- }
-
- /**
- * replace value succeeds when the given key mapped to expected value
- */
- public void testReplaceValue2() {
- ConcurrentSkipListMap map = map5();
- assertEquals("A", map.get(one));
- assertTrue(map.replace(one, "A", "Z"));
- assertEquals("Z", map.get(one));
- }
-
-
- /**
- * remove removes the correct key-value pair from the map
- */
- public void testRemove() {
- ConcurrentSkipListMap map = map5();
- map.remove(five);
- assertEquals(4, map.size());
- assertFalse(map.containsKey(five));
- }
-
- /**
- * remove(key,value) removes only if pair present
- */
- public void testRemove2() {
- ConcurrentSkipListMap map = map5();
- assertTrue(map.containsKey(five));
- assertEquals("E", map.get(five));
- map.remove(five, "E");
- assertEquals(4, map.size());
- assertFalse(map.containsKey(five));
- map.remove(four, "A");
- assertEquals(4, map.size());
- assertTrue(map.containsKey(four));
- }
-
- /**
- * lowerEntry returns preceding entry.
- */
- public void testLowerEntry() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e1 = map.lowerEntry(three);
- assertEquals(two, e1.getKey());
-
- Map.Entry e2 = map.lowerEntry(six);
- assertEquals(five, e2.getKey());
-
- Map.Entry e3 = map.lowerEntry(one);
- assertNull(e3);
-
- Map.Entry e4 = map.lowerEntry(zero);
- assertNull(e4);
- }
-
- /**
- * higherEntry returns next entry.
- */
- public void testHigherEntry() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e1 = map.higherEntry(three);
- assertEquals(four, e1.getKey());
-
- Map.Entry e2 = map.higherEntry(zero);
- assertEquals(one, e2.getKey());
-
- Map.Entry e3 = map.higherEntry(five);
- assertNull(e3);
-
- Map.Entry e4 = map.higherEntry(six);
- assertNull(e4);
- }
-
- /**
- * floorEntry returns preceding entry.
- */
- public void testFloorEntry() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e1 = map.floorEntry(three);
- assertEquals(three, e1.getKey());
-
- Map.Entry e2 = map.floorEntry(six);
- assertEquals(five, e2.getKey());
-
- Map.Entry e3 = map.floorEntry(one);
- assertEquals(one, e3.getKey());
-
- Map.Entry e4 = map.floorEntry(zero);
- assertNull(e4);
- }
-
- /**
- * ceilingEntry returns next entry.
- */
- public void testCeilingEntry() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e1 = map.ceilingEntry(three);
- assertEquals(three, e1.getKey());
-
- Map.Entry e2 = map.ceilingEntry(zero);
- assertEquals(one, e2.getKey());
-
- Map.Entry e3 = map.ceilingEntry(five);
- assertEquals(five, e3.getKey());
-
- Map.Entry e4 = map.ceilingEntry(six);
- assertNull(e4);
- }
-
- /**
- * lowerEntry, higherEntry, ceilingEntry, and floorEntry return
- * immutable entries
- */
- public void testEntryImmutablity() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e = map.lowerEntry(three);
- assertEquals(two, e.getKey());
- try {
- e.setValue("X");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.higherEntry(zero);
- assertEquals(one, e.getKey());
- try {
- e.setValue("X");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.floorEntry(one);
- assertEquals(one, e.getKey());
- try {
- e.setValue("X");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.ceilingEntry(five);
- assertEquals(five, e.getKey());
- try {
- e.setValue("X");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- }
-
-
-
- /**
- * lowerKey returns preceding element
- */
- public void testLowerKey() {
- ConcurrentSkipListMap q = map5();
- Object e1 = q.lowerKey(three);
- assertEquals(two, e1);
-
- Object e2 = q.lowerKey(six);
- assertEquals(five, e2);
-
- Object e3 = q.lowerKey(one);
- assertNull(e3);
-
- Object e4 = q.lowerKey(zero);
- assertNull(e4);
- }
-
- /**
- * higherKey returns next element
- */
- public void testHigherKey() {
- ConcurrentSkipListMap q = map5();
- Object e1 = q.higherKey(three);
- assertEquals(four, e1);
-
- Object e2 = q.higherKey(zero);
- assertEquals(one, e2);
-
- Object e3 = q.higherKey(five);
- assertNull(e3);
-
- Object e4 = q.higherKey(six);
- assertNull(e4);
- }
-
- /**
- * floorKey returns preceding element
- */
- public void testFloorKey() {
- ConcurrentSkipListMap q = map5();
- Object e1 = q.floorKey(three);
- assertEquals(three, e1);
-
- Object e2 = q.floorKey(six);
- assertEquals(five, e2);
-
- Object e3 = q.floorKey(one);
- assertEquals(one, e3);
-
- Object e4 = q.floorKey(zero);
- assertNull(e4);
- }
-
- /**
- * ceilingKey returns next element
- */
- public void testCeilingKey() {
- ConcurrentSkipListMap q = map5();
- Object e1 = q.ceilingKey(three);
- assertEquals(three, e1);
-
- Object e2 = q.ceilingKey(zero);
- assertEquals(one, e2);
-
- Object e3 = q.ceilingKey(five);
- assertEquals(five, e3);
-
- Object e4 = q.ceilingKey(six);
- assertNull(e4);
- }
-
- /**
- * pollFirstEntry returns entries in order
- */
- public void testPollFirstEntry() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e = map.pollFirstEntry();
- assertEquals(one, e.getKey());
- assertEquals("A", e.getValue());
- e = map.pollFirstEntry();
- assertEquals(two, e.getKey());
- map.put(one, "A");
- e = map.pollFirstEntry();
- assertEquals(one, e.getKey());
- assertEquals("A", e.getValue());
- e = map.pollFirstEntry();
- assertEquals(three, e.getKey());
- map.remove(four);
- e = map.pollFirstEntry();
- assertEquals(five, e.getKey());
- try {
- e.setValue("A");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.pollFirstEntry();
- assertNull(e);
- }
-
- /**
- * pollLastEntry returns entries in order
- */
- public void testPollLastEntry() {
- ConcurrentSkipListMap map = map5();
- Map.Entry e = map.pollLastEntry();
- assertEquals(five, e.getKey());
- assertEquals("E", e.getValue());
- e = map.pollLastEntry();
- assertEquals(four, e.getKey());
- map.put(five, "E");
- e = map.pollLastEntry();
- assertEquals(five, e.getKey());
- assertEquals("E", e.getValue());
- e = map.pollLastEntry();
- assertEquals(three, e.getKey());
- map.remove(two);
- e = map.pollLastEntry();
- assertEquals(one, e.getKey());
- try {
- e.setValue("E");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.pollLastEntry();
- assertNull(e);
- }
-
- /**
- * size returns the correct values
- */
- public void testSize() {
- ConcurrentSkipListMap map = map5();
- ConcurrentSkipListMap empty = new ConcurrentSkipListMap();
- assertEquals(0, empty.size());
- assertEquals(5, map.size());
- }
-
- /**
- * toString contains toString of elements
- */
- public void testToString() {
- ConcurrentSkipListMap map = map5();
- String s = map.toString();
- for (int i = 1; i <= 5; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- // Exception tests
-
- /**
- * get(null) of nonempty map throws NPE
- */
- public void testGet_NullPointerException() {
- try {
- ConcurrentSkipListMap c = map5();
- c.get(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsKey(null) of nonempty map throws NPE
- */
- public void testContainsKey_NullPointerException() {
- try {
- ConcurrentSkipListMap c = map5();
- c.containsKey(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsValue(null) throws NPE
- */
- public void testContainsValue_NullPointerException() {
- try {
- ConcurrentSkipListMap c = new ConcurrentSkipListMap();
- c.containsValue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * put(null,x) throws NPE
- */
- public void testPut1_NullPointerException() {
- try {
- ConcurrentSkipListMap c = map5();
- c.put(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * putIfAbsent(null, x) throws NPE
- */
- public void testPutIfAbsent1_NullPointerException() {
- try {
- ConcurrentSkipListMap c = map5();
- c.putIfAbsent(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x) throws NPE
- */
- public void testReplace_NullPointerException() {
- try {
- ConcurrentSkipListMap c = map5();
- c.replace(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x, y) throws NPE
- */
- public void testReplaceValue_NullPointerException() {
- try {
- ConcurrentSkipListMap c = map5();
- c.replace(null, one, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null) throws NPE
- */
- public void testRemove1_NullPointerException() {
- try {
- ConcurrentSkipListMap c = new ConcurrentSkipListMap();
- c.put("sadsdf", "asdads");
- c.remove(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null, x) throws NPE
- */
- public void testRemove2_NullPointerException() {
- try {
- ConcurrentSkipListMap c = new ConcurrentSkipListMap();
- c.put("sadsdf", "asdads");
- c.remove(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(x, null) returns false
- */
- public void testRemove3() {
- ConcurrentSkipListMap c = new ConcurrentSkipListMap();
- c.put("sadsdf", "asdads");
- assertFalse(c.remove("sadsdf", null));
- }
-
- /**
- * A deserialized map equals original
- */
- public void testSerialization() throws Exception {
- ConcurrentSkipListMap q = map5();
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ConcurrentSkipListMap r = (ConcurrentSkipListMap)in.readObject();
- assertEquals(q.size(), r.size());
- assertTrue(q.equals(r));
- assertTrue(r.equals(q));
- }
-
-
-
- /**
- * subMap returns map with keys in requested range
- */
- public void testSubMapContents() {
- ConcurrentSkipListMap map = map5();
- NavigableMap sm = map.subMap(two, true, four, false);
- assertEquals(two, sm.firstKey());
- assertEquals(three, sm.lastKey());
- assertEquals(2, sm.size());
- assertFalse(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertTrue(sm.containsKey(three));
- assertFalse(sm.containsKey(four));
- assertFalse(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- Iterator r = sm.descendingKeySet().iterator();
- k = (Integer)(r.next());
- assertEquals(three, k);
- k = (Integer)(r.next());
- assertEquals(two, k);
- assertFalse(r.hasNext());
-
- Iterator j = sm.keySet().iterator();
- j.next();
- j.remove();
- assertFalse(map.containsKey(two));
- assertEquals(4, map.size());
- assertEquals(1, sm.size());
- assertEquals(three, sm.firstKey());
- assertEquals(three, sm.lastKey());
- assertEquals("C", sm.remove(three));
- assertTrue(sm.isEmpty());
- assertEquals(3, map.size());
- }
-
- public void testSubMapContents2() {
- ConcurrentSkipListMap map = map5();
- NavigableMap sm = map.subMap(two, true, three, false);
- assertEquals(1, sm.size());
- assertEquals(two, sm.firstKey());
- assertEquals(two, sm.lastKey());
- assertFalse(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertFalse(sm.containsKey(three));
- assertFalse(sm.containsKey(four));
- assertFalse(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- assertFalse(i.hasNext());
- Iterator r = sm.descendingKeySet().iterator();
- k = (Integer)(r.next());
- assertEquals(two, k);
- assertFalse(r.hasNext());
-
- Iterator j = sm.keySet().iterator();
- j.next();
- j.remove();
- assertFalse(map.containsKey(two));
- assertEquals(4, map.size());
- assertEquals(0, sm.size());
- assertTrue(sm.isEmpty());
- assertSame(sm.remove(three), null);
- assertEquals(4, map.size());
- }
-
- /**
- * headMap returns map with keys in requested range
- */
- public void testHeadMapContents() {
- ConcurrentSkipListMap map = map5();
- NavigableMap sm = map.headMap(four, false);
- assertTrue(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertTrue(sm.containsKey(three));
- assertFalse(sm.containsKey(four));
- assertFalse(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(one, k);
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- sm.clear();
- assertTrue(sm.isEmpty());
- assertEquals(2, map.size());
- assertEquals(four, map.firstKey());
- }
-
- /**
- * tailMap returns map with keys in requested range
- */
- public void testTailMapContents() {
- ConcurrentSkipListMap map = map5();
- NavigableMap sm = map.tailMap(two, true);
- assertFalse(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertTrue(sm.containsKey(three));
- assertTrue(sm.containsKey(four));
- assertTrue(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- k = (Integer)(i.next());
- assertEquals(four, k);
- k = (Integer)(i.next());
- assertEquals(five, k);
- assertFalse(i.hasNext());
- Iterator r = sm.descendingKeySet().iterator();
- k = (Integer)(r.next());
- assertEquals(five, k);
- k = (Integer)(r.next());
- assertEquals(four, k);
- k = (Integer)(r.next());
- assertEquals(three, k);
- k = (Integer)(r.next());
- assertEquals(two, k);
- assertFalse(r.hasNext());
-
- Iterator ei = sm.entrySet().iterator();
- Map.Entry e;
- e = (Map.Entry)(ei.next());
- assertEquals(two, e.getKey());
- assertEquals("B", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(three, e.getKey());
- assertEquals("C", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(four, e.getKey());
- assertEquals("D", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(five, e.getKey());
- assertEquals("E", e.getValue());
- assertFalse(i.hasNext());
-
- NavigableMap ssm = sm.tailMap(four, true);
- assertEquals(four, ssm.firstKey());
- assertEquals(five, ssm.lastKey());
- assertEquals("D", ssm.remove(four));
- assertEquals(1, ssm.size());
- assertEquals(3, sm.size());
- assertEquals(4, map.size());
- }
-
- Random rnd = new Random(666);
- BitSet bs;
-
- /**
- * Submaps of submaps subdivide correctly
- */
- public void testRecursiveSubMaps() throws Exception {
- int mapSize = 1000;
- Class cl = ConcurrentSkipListMap.class;
- NavigableMap<Integer, Integer> map = newMap(cl);
- bs = new BitSet(mapSize);
-
- populate(map, mapSize);
- check(map, 0, mapSize - 1, true);
- check(map.descendingMap(), 0, mapSize - 1, false);
-
- mutateMap(map, 0, mapSize - 1);
- check(map, 0, mapSize - 1, true);
- check(map.descendingMap(), 0, mapSize - 1, false);
-
- bashSubMap(map.subMap(0, true, mapSize, false),
- 0, mapSize - 1, true);
- }
-
- static NavigableMap<Integer, Integer> newMap(Class cl) throws Exception {
- NavigableMap<Integer, Integer> result =
- (NavigableMap<Integer, Integer>) cl.newInstance();
- assertEquals(result.size(), 0);
- assertFalse(result.keySet().iterator().hasNext());
- return result;
- }
-
- void populate(NavigableMap<Integer, Integer> map, int limit) {
- for (int i = 0, n = 2 * limit / 3; i < n; i++) {
- int key = rnd.nextInt(limit);
- put(map, key);
- }
- }
-
- void mutateMap(NavigableMap<Integer, Integer> map, int min, int max) {
- int size = map.size();
- int rangeSize = max - min + 1;
-
- // Remove a bunch of entries directly
- for (int i = 0, n = rangeSize / 2; i < n; i++) {
- remove(map, min - 5 + rnd.nextInt(rangeSize + 10));
- }
-
- // Remove a bunch of entries with iterator
- for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext(); ) {
- if (rnd.nextBoolean()) {
- bs.clear(it.next());
- it.remove();
- }
- }
-
- // Add entries till we're back to original size
- while (map.size() < size) {
- int key = min + rnd.nextInt(rangeSize);
- assertTrue(key >= min && key<= max);
- put(map, key);
- }
- }
-
- void mutateSubMap(NavigableMap<Integer, Integer> map, int min, int max) {
- int size = map.size();
- int rangeSize = max - min + 1;
-
- // Remove a bunch of entries directly
- for (int i = 0, n = rangeSize / 2; i < n; i++) {
- remove(map, min - 5 + rnd.nextInt(rangeSize + 10));
- }
-
- // Remove a bunch of entries with iterator
- for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext(); ) {
- if (rnd.nextBoolean()) {
- bs.clear(it.next());
- it.remove();
- }
- }
-
- // Add entries till we're back to original size
- while (map.size() < size) {
- int key = min - 5 + rnd.nextInt(rangeSize + 10);
- if (key >= min && key<= max) {
- put(map, key);
- } else {
- try {
- map.put(key, 2 * key);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
- }
- }
-
- void put(NavigableMap<Integer, Integer> map, int key) {
- if (map.put(key, 2 * key) == null)
- bs.set(key);
- }
-
- void remove(NavigableMap<Integer, Integer> map, int key) {
- if (map.remove(key) != null)
- bs.clear(key);
- }
-
- void bashSubMap(NavigableMap<Integer, Integer> map,
- int min, int max, boolean ascending) {
- check(map, min, max, ascending);
- check(map.descendingMap(), min, max, !ascending);
-
- mutateSubMap(map, min, max);
- check(map, min, max, ascending);
- check(map.descendingMap(), min, max, !ascending);
-
- // Recurse
- if (max - min < 2)
- return;
- int midPoint = (min + max) / 2;
-
- // headMap - pick direction and endpoint inclusion randomly
- boolean incl = rnd.nextBoolean();
- NavigableMap<Integer,Integer> hm = map.headMap(midPoint, incl);
- if (ascending) {
- if (rnd.nextBoolean())
- bashSubMap(hm, min, midPoint - (incl ? 0 : 1), true);
- else
- bashSubMap(hm.descendingMap(), min, midPoint - (incl ? 0 : 1),
- false);
- } else {
- if (rnd.nextBoolean())
- bashSubMap(hm, midPoint + (incl ? 0 : 1), max, false);
- else
- bashSubMap(hm.descendingMap(), midPoint + (incl ? 0 : 1), max,
- true);
- }
-
- // tailMap - pick direction and endpoint inclusion randomly
- incl = rnd.nextBoolean();
- NavigableMap<Integer,Integer> tm = map.tailMap(midPoint,incl);
- if (ascending) {
- if (rnd.nextBoolean())
- bashSubMap(tm, midPoint + (incl ? 0 : 1), max, true);
- else
- bashSubMap(tm.descendingMap(), midPoint + (incl ? 0 : 1), max,
- false);
- } else {
- if (rnd.nextBoolean()) {
- bashSubMap(tm, min, midPoint - (incl ? 0 : 1), false);
- } else {
- bashSubMap(tm.descendingMap(), min, midPoint - (incl ? 0 : 1),
- true);
- }
- }
-
- // subMap - pick direction and endpoint inclusion randomly
- int rangeSize = max - min + 1;
- int[] endpoints = new int[2];
- endpoints[0] = min + rnd.nextInt(rangeSize);
- endpoints[1] = min + rnd.nextInt(rangeSize);
- Arrays.sort(endpoints);
- boolean lowIncl = rnd.nextBoolean();
- boolean highIncl = rnd.nextBoolean();
- if (ascending) {
- NavigableMap<Integer,Integer> sm = map.subMap(
- endpoints[0], lowIncl, endpoints[1], highIncl);
- if (rnd.nextBoolean())
- bashSubMap(sm, endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), true);
- else
- bashSubMap(sm.descendingMap(), endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), false);
- } else {
- NavigableMap<Integer,Integer> sm = map.subMap(
- endpoints[1], highIncl, endpoints[0], lowIncl);
- if (rnd.nextBoolean())
- bashSubMap(sm, endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), false);
- else
- bashSubMap(sm.descendingMap(), endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), true);
- }
- }
-
- /**
- * min and max are both inclusive. If max < min, interval is empty.
- */
- void check(NavigableMap<Integer, Integer> map,
- final int min, final int max, final boolean ascending) {
- class ReferenceSet {
- int lower(int key) {
- return ascending ? lowerAscending(key) : higherAscending(key);
- }
- int floor(int key) {
- return ascending ? floorAscending(key) : ceilingAscending(key);
- }
- int ceiling(int key) {
- return ascending ? ceilingAscending(key) : floorAscending(key);
- }
- int higher(int key) {
- return ascending ? higherAscending(key) : lowerAscending(key);
- }
- int first() {
- return ascending ? firstAscending() : lastAscending();
- }
- int last() {
- return ascending ? lastAscending() : firstAscending();
- }
- int lowerAscending(int key) {
- return floorAscending(key - 1);
- }
- int floorAscending(int key) {
- if (key < min)
- return -1;
- else if (key > max)
- key = max;
-
- // BitSet should support this! Test would run much faster
- while (key >= min) {
- if (bs.get(key))
- return(key);
- key--;
- }
- return -1;
- }
- int ceilingAscending(int key) {
- if (key < min)
- key = min;
- else if (key > max)
- return -1;
- int result = bs.nextSetBit(key);
- return result > max ? -1 : result;
- }
- int higherAscending(int key) {
- return ceilingAscending(key + 1);
- }
- private int firstAscending() {
- int result = ceilingAscending(min);
- return result > max ? -1 : result;
- }
- private int lastAscending() {
- int result = floorAscending(max);
- return result < min ? -1 : result;
- }
- }
- ReferenceSet rs = new ReferenceSet();
-
- // Test contents using containsKey
- int size = 0;
- for (int i = min; i <= max; i++) {
- boolean bsContainsI = bs.get(i);
- assertEquals(bsContainsI, map.containsKey(i));
- if (bsContainsI)
- size++;
- }
- assertEquals(map.size(), size);
-
- // Test contents using contains keySet iterator
- int size2 = 0;
- int previousKey = -1;
- for (int key : map.keySet()) {
- assertTrue(bs.get(key));
- size2++;
- assertTrue(previousKey < 0 ||
- (ascending ? key - previousKey > 0 : key - previousKey < 0));
- previousKey = key;
- }
- assertEquals(size2, size);
-
- // Test navigation ops
- for (int key = min - 1; key <= max + 1; key++) {
- assertEq(map.lowerKey(key), rs.lower(key));
- assertEq(map.floorKey(key), rs.floor(key));
- assertEq(map.higherKey(key), rs.higher(key));
- assertEq(map.ceilingKey(key), rs.ceiling(key));
- }
-
- // Test extrema
- if (map.size() != 0) {
- assertEq(map.firstKey(), rs.first());
- assertEq(map.lastKey(), rs.last());
- } else {
- assertEq(rs.first(), -1);
- assertEq(rs.last(), -1);
- try {
- map.firstKey();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- try {
- map.lastKey();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
- }
-
- static void assertEq(Integer i, int j) {
- if (i == null)
- assertEquals(j, -1);
- else
- assertEquals((int) i, j);
- }
-
- static boolean eq(Integer i, int j) {
- return i == null ? j == -1 : i == j;
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSetTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSetTest.java
deleted file mode 100644
index 2d03b3c..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSetTest.java
+++ /dev/null
@@ -1,961 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class ConcurrentSkipListSetTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ConcurrentSkipListSetTest.class);
- }
-
- static class MyReverseComparator implements Comparator {
- public int compare(Object x, Object y) {
- return ((Comparable)y).compareTo(x);
- }
- }
-
- /**
- * Create a set of given size containing consecutive
- * Integers 0 ... n.
- */
- private ConcurrentSkipListSet populatedSet(int n) {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.isEmpty());
- for (int i = n-1; i >= 0; i-=2)
- assertTrue(q.add(new Integer(i)));
- for (int i = (n & 1); i < n; i+=2)
- assertTrue(q.add(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * Create set of first 5 ints
- */
- private ConcurrentSkipListSet set5() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.isEmpty());
- q.add(one);
- q.add(two);
- q.add(three);
- q.add(four);
- q.add(five);
- assertEquals(5, q.size());
- return q;
- }
-
- /**
- * A new set has unbounded capacity
- */
- public void testConstructor1() {
- assertEquals(0, new ConcurrentSkipListSet().size());
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet((Collection)null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- ConcurrentSkipListSet q = new ConcurrentSkipListSet(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- ConcurrentSkipListSet q = new ConcurrentSkipListSet(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Set contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- ConcurrentSkipListSet q = new ConcurrentSkipListSet(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * The comparator used in constructor is used
- */
- public void testConstructor7() {
- MyReverseComparator cmp = new MyReverseComparator();
- ConcurrentSkipListSet q = new ConcurrentSkipListSet(cmp);
- assertEquals(cmp, q.comparator());
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- for (int i = SIZE-1; i >= 0; --i)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.isEmpty());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.add(new Integer(2));
- q.pollFirst();
- q.pollFirst();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.pollFirst();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Add of comparable element succeeds
- */
- public void testAdd() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.add(zero));
- assertTrue(q.add(one));
- }
-
- /**
- * Add of duplicate element fails
- */
- public void testAddDup() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.add(zero));
- assertFalse(q.add(zero));
- }
-
- /**
- * Add of non-Comparable throws CCE
- */
- public void testAddNonComparable() {
- try {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- q.add(new Object());
- q.add(new Object());
- q.add(new Object());
- shouldThrow();
- } catch (ClassCastException success) {}
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Set contains all elements of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(SIZE-1-i);
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(i, q.pollFirst());
- }
-
- /**
- * pollFirst succeeds unless empty
- */
- public void testPollFirst() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst());
- }
- assertNull(q.pollFirst());
- }
-
- /**
- * pollLast succeeds unless empty
- */
- public void testPollLast() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.pollLast());
- }
- assertNull(q.pollFirst());
- }
-
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.pollFirst();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- ConcurrentSkipListSet p = new ConcurrentSkipListSet();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- ConcurrentSkipListSet p = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.pollFirst();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- ConcurrentSkipListSet p = populatedSet(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.pollFirst());
- assertFalse(q.contains(I));
- }
- }
- }
-
-
-
- /**
- * lower returns preceding element
- */
- public void testLower() {
- ConcurrentSkipListSet q = set5();
- Object e1 = q.lower(three);
- assertEquals(two, e1);
-
- Object e2 = q.lower(six);
- assertEquals(five, e2);
-
- Object e3 = q.lower(one);
- assertNull(e3);
-
- Object e4 = q.lower(zero);
- assertNull(e4);
- }
-
- /**
- * higher returns next element
- */
- public void testHigher() {
- ConcurrentSkipListSet q = set5();
- Object e1 = q.higher(three);
- assertEquals(four, e1);
-
- Object e2 = q.higher(zero);
- assertEquals(one, e2);
-
- Object e3 = q.higher(five);
- assertNull(e3);
-
- Object e4 = q.higher(six);
- assertNull(e4);
- }
-
- /**
- * floor returns preceding element
- */
- public void testFloor() {
- ConcurrentSkipListSet q = set5();
- Object e1 = q.floor(three);
- assertEquals(three, e1);
-
- Object e2 = q.floor(six);
- assertEquals(five, e2);
-
- Object e3 = q.floor(one);
- assertEquals(one, e3);
-
- Object e4 = q.floor(zero);
- assertNull(e4);
- }
-
- /**
- * ceiling returns next element
- */
- public void testCeiling() {
- ConcurrentSkipListSet q = set5();
- Object e1 = q.ceiling(three);
- assertEquals(three, e1);
-
- Object e2 = q.ceiling(zero);
- assertEquals(one, e2);
-
- Object e3 = q.ceiling(five);
- assertEquals(five, e3);
-
- Object e4 = q.ceiling(six);
- assertNull(e4);
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.pollFirst());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator of empty set has no elements
- */
- public void testEmptyIterator() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, 0);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- q.add(new Integer(2));
- q.add(new Integer(1));
- q.add(new Integer(3));
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * A deserialized serialized set has same elements
- */
- public void testSerialization() throws Exception {
- ConcurrentSkipListSet q = populatedSet(SIZE);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ConcurrentSkipListSet r = (ConcurrentSkipListSet)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.pollFirst(), r.pollFirst());
- }
-
- /**
- * subSet returns set with keys in requested range
- */
- public void testSubSetContents() {
- ConcurrentSkipListSet set = set5();
- SortedSet sm = set.subSet(two, four);
- assertEquals(two, sm.first());
- assertEquals(three, sm.last());
- assertEquals(2, sm.size());
- assertFalse(sm.contains(one));
- assertTrue(sm.contains(two));
- assertTrue(sm.contains(three));
- assertFalse(sm.contains(four));
- assertFalse(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- Iterator j = sm.iterator();
- j.next();
- j.remove();
- assertFalse(set.contains(two));
- assertEquals(4, set.size());
- assertEquals(1, sm.size());
- assertEquals(three, sm.first());
- assertEquals(three, sm.last());
- assertTrue(sm.remove(three));
- assertTrue(sm.isEmpty());
- assertEquals(3, set.size());
- }
-
- public void testSubSetContents2() {
- ConcurrentSkipListSet set = set5();
- SortedSet sm = set.subSet(two, three);
- assertEquals(1, sm.size());
- assertEquals(two, sm.first());
- assertEquals(two, sm.last());
- assertFalse(sm.contains(one));
- assertTrue(sm.contains(two));
- assertFalse(sm.contains(three));
- assertFalse(sm.contains(four));
- assertFalse(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- assertFalse(i.hasNext());
- Iterator j = sm.iterator();
- j.next();
- j.remove();
- assertFalse(set.contains(two));
- assertEquals(4, set.size());
- assertEquals(0, sm.size());
- assertTrue(sm.isEmpty());
- assertFalse(sm.remove(three));
- assertEquals(4, set.size());
- }
-
- /**
- * headSet returns set with keys in requested range
- */
- public void testHeadSetContents() {
- ConcurrentSkipListSet set = set5();
- SortedSet sm = set.headSet(four);
- assertTrue(sm.contains(one));
- assertTrue(sm.contains(two));
- assertTrue(sm.contains(three));
- assertFalse(sm.contains(four));
- assertFalse(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(one, k);
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- sm.clear();
- assertTrue(sm.isEmpty());
- assertEquals(2, set.size());
- assertEquals(four, set.first());
- }
-
- /**
- * tailSet returns set with keys in requested range
- */
- public void testTailSetContents() {
- ConcurrentSkipListSet set = set5();
- SortedSet sm = set.tailSet(two);
- assertFalse(sm.contains(one));
- assertTrue(sm.contains(two));
- assertTrue(sm.contains(three));
- assertTrue(sm.contains(four));
- assertTrue(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- k = (Integer)(i.next());
- assertEquals(four, k);
- k = (Integer)(i.next());
- assertEquals(five, k);
- assertFalse(i.hasNext());
-
- SortedSet ssm = sm.tailSet(four);
- assertEquals(four, ssm.first());
- assertEquals(five, ssm.last());
- assertTrue(ssm.remove(four));
- assertEquals(1, ssm.size());
- assertEquals(3, sm.size());
- assertEquals(4, set.size());
- }
-
- Random rnd = new Random(666);
- BitSet bs;
-
- /**
- * Subsets of subsets subdivide correctly
- */
- public void testRecursiveSubSets() throws Exception {
- int setSize = 1000;
- Class cl = ConcurrentSkipListSet.class;
-
- NavigableSet<Integer> set = newSet(cl);
- bs = new BitSet(setSize);
-
- populate(set, setSize);
- check(set, 0, setSize - 1, true);
- check(set.descendingSet(), 0, setSize - 1, false);
-
- mutateSet(set, 0, setSize - 1);
- check(set, 0, setSize - 1, true);
- check(set.descendingSet(), 0, setSize - 1, false);
-
- bashSubSet(set.subSet(0, true, setSize, false),
- 0, setSize - 1, true);
- }
-
- static NavigableSet<Integer> newSet(Class cl) throws Exception {
- NavigableSet<Integer> result = (NavigableSet<Integer>) cl.newInstance();
- assertEquals(result.size(), 0);
- assertFalse(result.iterator().hasNext());
- return result;
- }
-
- void populate(NavigableSet<Integer> set, int limit) {
- for (int i = 0, n = 2 * limit / 3; i < n; i++) {
- int element = rnd.nextInt(limit);
- put(set, element);
- }
- }
-
- void mutateSet(NavigableSet<Integer> set, int min, int max) {
- int size = set.size();
- int rangeSize = max - min + 1;
-
- // Remove a bunch of entries directly
- for (int i = 0, n = rangeSize / 2; i < n; i++) {
- remove(set, min - 5 + rnd.nextInt(rangeSize + 10));
- }
-
- // Remove a bunch of entries with iterator
- for (Iterator<Integer> it = set.iterator(); it.hasNext(); ) {
- if (rnd.nextBoolean()) {
- bs.clear(it.next());
- it.remove();
- }
- }
-
- // Add entries till we're back to original size
- while (set.size() < size) {
- int element = min + rnd.nextInt(rangeSize);
- assertTrue(element >= min && element<= max);
- put(set, element);
- }
- }
-
- void mutateSubSet(NavigableSet<Integer> set, int min, int max) {
- int size = set.size();
- int rangeSize = max - min + 1;
-
- // Remove a bunch of entries directly
- for (int i = 0, n = rangeSize / 2; i < n; i++) {
- remove(set, min - 5 + rnd.nextInt(rangeSize + 10));
- }
-
- // Remove a bunch of entries with iterator
- for (Iterator<Integer> it = set.iterator(); it.hasNext(); ) {
- if (rnd.nextBoolean()) {
- bs.clear(it.next());
- it.remove();
- }
- }
-
- // Add entries till we're back to original size
- while (set.size() < size) {
- int element = min - 5 + rnd.nextInt(rangeSize + 10);
- if (element >= min && element<= max) {
- put(set, element);
- } else {
- try {
- set.add(element);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
- }
- }
-
- void put(NavigableSet<Integer> set, int element) {
- if (set.add(element))
- bs.set(element);
- }
-
- void remove(NavigableSet<Integer> set, int element) {
- if (set.remove(element))
- bs.clear(element);
- }
-
- void bashSubSet(NavigableSet<Integer> set,
- int min, int max, boolean ascending) {
- check(set, min, max, ascending);
- check(set.descendingSet(), min, max, !ascending);
-
- mutateSubSet(set, min, max);
- check(set, min, max, ascending);
- check(set.descendingSet(), min, max, !ascending);
-
- // Recurse
- if (max - min < 2)
- return;
- int midPoint = (min + max) / 2;
-
- // headSet - pick direction and endpoint inclusion randomly
- boolean incl = rnd.nextBoolean();
- NavigableSet<Integer> hm = set.headSet(midPoint, incl);
- if (ascending) {
- if (rnd.nextBoolean())
- bashSubSet(hm, min, midPoint - (incl ? 0 : 1), true);
- else
- bashSubSet(hm.descendingSet(), min, midPoint - (incl ? 0 : 1),
- false);
- } else {
- if (rnd.nextBoolean())
- bashSubSet(hm, midPoint + (incl ? 0 : 1), max, false);
- else
- bashSubSet(hm.descendingSet(), midPoint + (incl ? 0 : 1), max,
- true);
- }
-
- // tailSet - pick direction and endpoint inclusion randomly
- incl = rnd.nextBoolean();
- NavigableSet<Integer> tm = set.tailSet(midPoint,incl);
- if (ascending) {
- if (rnd.nextBoolean())
- bashSubSet(tm, midPoint + (incl ? 0 : 1), max, true);
- else
- bashSubSet(tm.descendingSet(), midPoint + (incl ? 0 : 1), max,
- false);
- } else {
- if (rnd.nextBoolean()) {
- bashSubSet(tm, min, midPoint - (incl ? 0 : 1), false);
- } else {
- bashSubSet(tm.descendingSet(), min, midPoint - (incl ? 0 : 1),
- true);
- }
- }
-
- // subSet - pick direction and endpoint inclusion randomly
- int rangeSize = max - min + 1;
- int[] endpoints = new int[2];
- endpoints[0] = min + rnd.nextInt(rangeSize);
- endpoints[1] = min + rnd.nextInt(rangeSize);
- Arrays.sort(endpoints);
- boolean lowIncl = rnd.nextBoolean();
- boolean highIncl = rnd.nextBoolean();
- if (ascending) {
- NavigableSet<Integer> sm = set.subSet(
- endpoints[0], lowIncl, endpoints[1], highIncl);
- if (rnd.nextBoolean())
- bashSubSet(sm, endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), true);
- else
- bashSubSet(sm.descendingSet(), endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), false);
- } else {
- NavigableSet<Integer> sm = set.subSet(
- endpoints[1], highIncl, endpoints[0], lowIncl);
- if (rnd.nextBoolean())
- bashSubSet(sm, endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), false);
- else
- bashSubSet(sm.descendingSet(), endpoints[0] + (lowIncl ? 0 : 1),
- endpoints[1] - (highIncl ? 0 : 1), true);
- }
- }
-
- /**
- * min and max are both inclusive. If max < min, interval is empty.
- */
- void check(NavigableSet<Integer> set,
- final int min, final int max, final boolean ascending) {
- class ReferenceSet {
- int lower(int element) {
- return ascending ?
- lowerAscending(element) : higherAscending(element);
- }
- int floor(int element) {
- return ascending ?
- floorAscending(element) : ceilingAscending(element);
- }
- int ceiling(int element) {
- return ascending ?
- ceilingAscending(element) : floorAscending(element);
- }
- int higher(int element) {
- return ascending ?
- higherAscending(element) : lowerAscending(element);
- }
- int first() {
- return ascending ? firstAscending() : lastAscending();
- }
- int last() {
- return ascending ? lastAscending() : firstAscending();
- }
- int lowerAscending(int element) {
- return floorAscending(element - 1);
- }
- int floorAscending(int element) {
- if (element < min)
- return -1;
- else if (element > max)
- element = max;
-
- // BitSet should support this! Test would run much faster
- while (element >= min) {
- if (bs.get(element))
- return(element);
- element--;
- }
- return -1;
- }
- int ceilingAscending(int element) {
- if (element < min)
- element = min;
- else if (element > max)
- return -1;
- int result = bs.nextSetBit(element);
- return result > max ? -1 : result;
- }
- int higherAscending(int element) {
- return ceilingAscending(element + 1);
- }
- private int firstAscending() {
- int result = ceilingAscending(min);
- return result > max ? -1 : result;
- }
- private int lastAscending() {
- int result = floorAscending(max);
- return result < min ? -1 : result;
- }
- }
- ReferenceSet rs = new ReferenceSet();
-
- // Test contents using containsElement
- int size = 0;
- for (int i = min; i <= max; i++) {
- boolean bsContainsI = bs.get(i);
- assertEquals(bsContainsI, set.contains(i));
- if (bsContainsI)
- size++;
- }
- assertEquals(set.size(), size);
-
- // Test contents using contains elementSet iterator
- int size2 = 0;
- int previousElement = -1;
- for (int element : set) {
- assertTrue(bs.get(element));
- size2++;
- assertTrue(previousElement < 0 || (ascending ?
- element - previousElement > 0 : element - previousElement < 0));
- previousElement = element;
- }
- assertEquals(size2, size);
-
- // Test navigation ops
- for (int element = min - 1; element <= max + 1; element++) {
- assertEq(set.lower(element), rs.lower(element));
- assertEq(set.floor(element), rs.floor(element));
- assertEq(set.higher(element), rs.higher(element));
- assertEq(set.ceiling(element), rs.ceiling(element));
- }
-
- // Test extrema
- if (set.size() != 0) {
- assertEq(set.first(), rs.first());
- assertEq(set.last(), rs.last());
- } else {
- assertEq(rs.first(), -1);
- assertEq(rs.last(), -1);
- try {
- set.first();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- try {
- set.last();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
- }
-
- static void assertEq(Integer i, int j) {
- if (i == null)
- assertEquals(j, -1);
- else
- assertEquals((int) i, j);
- }
-
- static boolean eq(Integer i, int j) {
- return i == null ? j == -1 : i == j;
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSubMapTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSubMapTest.java
deleted file mode 100644
index fc70935..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSubMapTest.java
+++ /dev/null
@@ -1,1438 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class ConcurrentSkipListSubMapTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ConcurrentSkipListSubMapTest.class);
- }
-
- /**
- * Create a map from Integers 1-5 to Strings "A"-"E".
- */
- private static ConcurrentNavigableMap map5() {
- ConcurrentSkipListMap map = new ConcurrentSkipListMap();
- assertTrue(map.isEmpty());
- map.put(zero, "Z");
- map.put(one, "A");
- map.put(five, "E");
- map.put(three, "C");
- map.put(two, "B");
- map.put(four, "D");
- map.put(seven, "F");
- assertFalse(map.isEmpty());
- assertEquals(7, map.size());
- return map.subMap(one, true, seven, false);
- }
-
- /**
- * Create a map from Integers -5 to -1 to Strings "A"-"E".
- */
- private static ConcurrentNavigableMap dmap5() {
- ConcurrentSkipListMap map = new ConcurrentSkipListMap();
- assertTrue(map.isEmpty());
- map.put(m1, "A");
- map.put(m5, "E");
- map.put(m3, "C");
- map.put(m2, "B");
- map.put(m4, "D");
- assertFalse(map.isEmpty());
- assertEquals(5, map.size());
- return map.descendingMap();
- }
-
- private static ConcurrentNavigableMap map0() {
- ConcurrentSkipListMap map = new ConcurrentSkipListMap();
- assertTrue(map.isEmpty());
- return map.tailMap(one, true);
- }
-
- private static ConcurrentNavigableMap dmap0() {
- ConcurrentSkipListMap map = new ConcurrentSkipListMap();
- assertTrue(map.isEmpty());
- return map;
- }
-
- /**
- * clear removes all pairs
- */
- public void testClear() {
- ConcurrentNavigableMap map = map5();
- map.clear();
- assertEquals(map.size(), 0);
- }
-
-
- /**
- * Maps with same contents are equal
- */
- public void testEquals() {
- ConcurrentNavigableMap map1 = map5();
- ConcurrentNavigableMap map2 = map5();
- assertEquals(map1, map2);
- assertEquals(map2, map1);
- map1.clear();
- assertFalse(map1.equals(map2));
- assertFalse(map2.equals(map1));
- }
-
- /**
- * containsKey returns true for contained key
- */
- public void testContainsKey() {
- ConcurrentNavigableMap map = map5();
- assertTrue(map.containsKey(one));
- assertFalse(map.containsKey(zero));
- }
-
- /**
- * containsValue returns true for held values
- */
- public void testContainsValue() {
- ConcurrentNavigableMap map = map5();
- assertTrue(map.containsValue("A"));
- assertFalse(map.containsValue("Z"));
- }
-
- /**
- * get returns the correct element at the given key,
- * or null if not present
- */
- public void testGet() {
- ConcurrentNavigableMap map = map5();
- assertEquals("A", (String)map.get(one));
- ConcurrentNavigableMap empty = map0();
- assertNull(empty.get(one));
- }
-
- /**
- * isEmpty is true of empty map and false for non-empty
- */
- public void testIsEmpty() {
- ConcurrentNavigableMap empty = map0();
- ConcurrentNavigableMap map = map5();
- assertTrue(empty.isEmpty());
- assertFalse(map.isEmpty());
- }
-
- /**
- * firstKey returns first key
- */
- public void testFirstKey() {
- ConcurrentNavigableMap map = map5();
- assertEquals(one, map.firstKey());
- }
-
- /**
- * lastKey returns last key
- */
- public void testLastKey() {
- ConcurrentNavigableMap map = map5();
- assertEquals(five, map.lastKey());
- }
-
-
- /**
- * keySet returns a Set containing all the keys
- */
- public void testKeySet() {
- ConcurrentNavigableMap map = map5();
- Set s = map.keySet();
- assertEquals(5, s.size());
- assertTrue(s.contains(one));
- assertTrue(s.contains(two));
- assertTrue(s.contains(three));
- assertTrue(s.contains(four));
- assertTrue(s.contains(five));
- }
-
- /**
- * keySet is ordered
- */
- public void testKeySetOrder() {
- ConcurrentNavigableMap map = map5();
- Set s = map.keySet();
- Iterator i = s.iterator();
- Integer last = (Integer)i.next();
- assertEquals(last, one);
- while (i.hasNext()) {
- Integer k = (Integer)i.next();
- assertTrue(last.compareTo(k) < 0);
- last = k;
- }
- }
-
- /**
- * values collection contains all values
- */
- public void testValues() {
- ConcurrentNavigableMap map = map5();
- Collection s = map.values();
- assertEquals(5, s.size());
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
- /**
- * keySet.toArray returns contains all keys
- */
- public void testKeySetToArray() {
- ConcurrentNavigableMap map = map5();
- Set s = map.keySet();
- Object[] ar = s.toArray();
- assertTrue(s.containsAll(Arrays.asList(ar)));
- assertEquals(5, ar.length);
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * descendingkeySet.toArray returns contains all keys
- */
- public void testDescendingKeySetToArray() {
- ConcurrentNavigableMap map = map5();
- Set s = map.descendingKeySet();
- Object[] ar = s.toArray();
- assertEquals(5, ar.length);
- assertTrue(s.containsAll(Arrays.asList(ar)));
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * Values.toArray contains all values
- */
- public void testValuesToArray() {
- ConcurrentNavigableMap map = map5();
- Collection v = map.values();
- Object[] ar = v.toArray();
- ArrayList s = new ArrayList(Arrays.asList(ar));
- assertEquals(5, ar.length);
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
-
- /**
- * entrySet contains all pairs
- */
- public void testEntrySet() {
- ConcurrentNavigableMap map = map5();
- Set s = map.entrySet();
- assertEquals(5, s.size());
- Iterator it = s.iterator();
- while (it.hasNext()) {
- Map.Entry e = (Map.Entry) it.next();
- assertTrue(
- (e.getKey().equals(one) && e.getValue().equals("A")) ||
- (e.getKey().equals(two) && e.getValue().equals("B")) ||
- (e.getKey().equals(three) && e.getValue().equals("C")) ||
- (e.getKey().equals(four) && e.getValue().equals("D")) ||
- (e.getKey().equals(five) && e.getValue().equals("E")));
- }
- }
-
- /**
- * putAll adds all key-value pairs from the given map
- */
- public void testPutAll() {
- ConcurrentNavigableMap empty = map0();
- ConcurrentNavigableMap map = map5();
- empty.putAll(map);
- assertEquals(5, empty.size());
- assertTrue(empty.containsKey(one));
- assertTrue(empty.containsKey(two));
- assertTrue(empty.containsKey(three));
- assertTrue(empty.containsKey(four));
- assertTrue(empty.containsKey(five));
- }
-
- /**
- * putIfAbsent works when the given key is not present
- */
- public void testPutIfAbsent() {
- ConcurrentNavigableMap map = map5();
- map.putIfAbsent(six, "Z");
- assertTrue(map.containsKey(six));
- }
-
- /**
- * putIfAbsent does not add the pair if the key is already present
- */
- public void testPutIfAbsent2() {
- ConcurrentNavigableMap map = map5();
- assertEquals("A", map.putIfAbsent(one, "Z"));
- }
-
- /**
- * replace fails when the given key is not present
- */
- public void testReplace() {
- ConcurrentNavigableMap map = map5();
- assertNull(map.replace(six, "Z"));
- assertFalse(map.containsKey(six));
- }
-
- /**
- * replace succeeds if the key is already present
- */
- public void testReplace2() {
- ConcurrentNavigableMap map = map5();
- assertNotNull(map.replace(one, "Z"));
- assertEquals("Z", map.get(one));
- }
-
-
- /**
- * replace value fails when the given key not mapped to expected value
- */
- public void testReplaceValue() {
- ConcurrentNavigableMap map = map5();
- assertEquals("A", map.get(one));
- assertFalse(map.replace(one, "Z", "Z"));
- assertEquals("A", map.get(one));
- }
-
- /**
- * replace value succeeds when the given key mapped to expected value
- */
- public void testReplaceValue2() {
- ConcurrentNavigableMap map = map5();
- assertEquals("A", map.get(one));
- assertTrue(map.replace(one, "A", "Z"));
- assertEquals("Z", map.get(one));
- }
-
-
- /**
- * remove removes the correct key-value pair from the map
- */
- public void testRemove() {
- ConcurrentNavigableMap map = map5();
- map.remove(five);
- assertEquals(4, map.size());
- assertFalse(map.containsKey(five));
- }
-
- /**
- * remove(key,value) removes only if pair present
- */
- public void testRemove2() {
- ConcurrentNavigableMap map = map5();
- assertTrue(map.containsKey(five));
- assertEquals("E", map.get(five));
- map.remove(five, "E");
- assertEquals(4, map.size());
- assertFalse(map.containsKey(five));
- map.remove(four, "A");
- assertEquals(4, map.size());
- assertTrue(map.containsKey(four));
- }
-
- /**
- * lowerEntry returns preceding entry.
- */
- public void testLowerEntry() {
- ConcurrentNavigableMap map = map5();
- Map.Entry e1 = map.lowerEntry(three);
- assertEquals(two, e1.getKey());
-
- Map.Entry e2 = map.lowerEntry(six);
- assertEquals(five, e2.getKey());
-
- Map.Entry e3 = map.lowerEntry(one);
- assertNull(e3);
-
- Map.Entry e4 = map.lowerEntry(zero);
- assertNull(e4);
- }
-
- /**
- * higherEntry returns next entry.
- */
- public void testHigherEntry() {
- ConcurrentNavigableMap map = map5();
- Map.Entry e1 = map.higherEntry(three);
- assertEquals(four, e1.getKey());
-
- Map.Entry e2 = map.higherEntry(zero);
- assertEquals(one, e2.getKey());
-
- Map.Entry e3 = map.higherEntry(five);
- assertNull(e3);
-
- Map.Entry e4 = map.higherEntry(six);
- assertNull(e4);
- }
-
- /**
- * floorEntry returns preceding entry.
- */
- public void testFloorEntry() {
- ConcurrentNavigableMap map = map5();
- Map.Entry e1 = map.floorEntry(three);
- assertEquals(three, e1.getKey());
-
- Map.Entry e2 = map.floorEntry(six);
- assertEquals(five, e2.getKey());
-
- Map.Entry e3 = map.floorEntry(one);
- assertEquals(one, e3.getKey());
-
- Map.Entry e4 = map.floorEntry(zero);
- assertNull(e4);
- }
-
- /**
- * ceilingEntry returns next entry.
- */
- public void testCeilingEntry() {
- ConcurrentNavigableMap map = map5();
- Map.Entry e1 = map.ceilingEntry(three);
- assertEquals(three, e1.getKey());
-
- Map.Entry e2 = map.ceilingEntry(zero);
- assertEquals(one, e2.getKey());
-
- Map.Entry e3 = map.ceilingEntry(five);
- assertEquals(five, e3.getKey());
-
- Map.Entry e4 = map.ceilingEntry(six);
- assertNull(e4);
- }
-
- /**
- * pollFirstEntry returns entries in order
- */
- public void testPollFirstEntry() {
- ConcurrentNavigableMap map = map5();
- Map.Entry e = map.pollFirstEntry();
- assertEquals(one, e.getKey());
- assertEquals("A", e.getValue());
- e = map.pollFirstEntry();
- assertEquals(two, e.getKey());
- map.put(one, "A");
- e = map.pollFirstEntry();
- assertEquals(one, e.getKey());
- assertEquals("A", e.getValue());
- e = map.pollFirstEntry();
- assertEquals(three, e.getKey());
- map.remove(four);
- e = map.pollFirstEntry();
- assertEquals(five, e.getKey());
- try {
- e.setValue("A");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.pollFirstEntry();
- assertNull(e);
- }
-
- /**
- * pollLastEntry returns entries in order
- */
- public void testPollLastEntry() {
- ConcurrentNavigableMap map = map5();
- Map.Entry e = map.pollLastEntry();
- assertEquals(five, e.getKey());
- assertEquals("E", e.getValue());
- e = map.pollLastEntry();
- assertEquals(four, e.getKey());
- map.put(five, "E");
- e = map.pollLastEntry();
- assertEquals(five, e.getKey());
- assertEquals("E", e.getValue());
- e = map.pollLastEntry();
- assertEquals(three, e.getKey());
- map.remove(two);
- e = map.pollLastEntry();
- assertEquals(one, e.getKey());
- try {
- e.setValue("E");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.pollLastEntry();
- assertNull(e);
- }
-
- /**
- * size returns the correct values
- */
- public void testSize() {
- ConcurrentNavigableMap map = map5();
- ConcurrentNavigableMap empty = map0();
- assertEquals(0, empty.size());
- assertEquals(5, map.size());
- }
-
- /**
- * toString contains toString of elements
- */
- public void testToString() {
- ConcurrentNavigableMap map = map5();
- String s = map.toString();
- for (int i = 1; i <= 5; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- // Exception tests
-
- /**
- * get(null) of nonempty map throws NPE
- */
- public void testGet_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.get(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsKey(null) of nonempty map throws NPE
- */
- public void testContainsKey_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.containsKey(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsValue(null) throws NPE
- */
- public void testContainsValue_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map0();
- c.containsValue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * put(null,x) throws NPE
- */
- public void testPut1_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.put(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * putIfAbsent(null, x) throws NPE
- */
- public void testPutIfAbsent1_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.putIfAbsent(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x) throws NPE
- */
- public void testReplace_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.replace(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x, y) throws NPE
- */
- public void testReplaceValue_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.replace(null, one, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null) throws NPE
- */
- public void testRemove1_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.remove(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null, x) throws NPE
- */
- public void testRemove2_NullPointerException() {
- try {
- ConcurrentNavigableMap c = map5();
- c.remove(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * A deserialized map equals original
- */
- public void testSerialization() throws Exception {
- ConcurrentNavigableMap q = map5();
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ConcurrentNavigableMap r = (ConcurrentNavigableMap)in.readObject();
- assertEquals(q.size(), r.size());
- assertTrue(q.equals(r));
- assertTrue(r.equals(q));
- }
-
-
-
- /**
- * subMap returns map with keys in requested range
- */
- public void testSubMapContents() {
- ConcurrentNavigableMap map = map5();
- SortedMap sm = map.subMap(two, four);
- assertEquals(two, sm.firstKey());
- assertEquals(three, sm.lastKey());
- assertEquals(2, sm.size());
- assertFalse(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertTrue(sm.containsKey(three));
- assertFalse(sm.containsKey(four));
- assertFalse(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- Iterator j = sm.keySet().iterator();
- j.next();
- j.remove();
- assertFalse(map.containsKey(two));
- assertEquals(4, map.size());
- assertEquals(1, sm.size());
- assertEquals(three, sm.firstKey());
- assertEquals(three, sm.lastKey());
- assertEquals("C", sm.remove(three));
- assertTrue(sm.isEmpty());
- assertEquals(3, map.size());
- }
-
- public void testSubMapContents2() {
- ConcurrentNavigableMap map = map5();
- SortedMap sm = map.subMap(two, three);
- assertEquals(1, sm.size());
- assertEquals(two, sm.firstKey());
- assertEquals(two, sm.lastKey());
- assertFalse(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertFalse(sm.containsKey(three));
- assertFalse(sm.containsKey(four));
- assertFalse(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- assertFalse(i.hasNext());
- Iterator j = sm.keySet().iterator();
- j.next();
- j.remove();
- assertFalse(map.containsKey(two));
- assertEquals(4, map.size());
- assertEquals(0, sm.size());
- assertTrue(sm.isEmpty());
- assertSame(sm.remove(three), null);
- assertEquals(4, map.size());
- }
-
- /**
- * headMap returns map with keys in requested range
- */
- public void testHeadMapContents() {
- ConcurrentNavigableMap map = map5();
- SortedMap sm = map.headMap(four);
- assertTrue(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertTrue(sm.containsKey(three));
- assertFalse(sm.containsKey(four));
- assertFalse(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(one, k);
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- sm.clear();
- assertTrue(sm.isEmpty());
- assertEquals(2, map.size());
- assertEquals(four, map.firstKey());
- }
-
- /**
- * headMap returns map with keys in requested range
- */
- public void testTailMapContents() {
- ConcurrentNavigableMap map = map5();
- SortedMap sm = map.tailMap(two);
- assertFalse(sm.containsKey(one));
- assertTrue(sm.containsKey(two));
- assertTrue(sm.containsKey(three));
- assertTrue(sm.containsKey(four));
- assertTrue(sm.containsKey(five));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- k = (Integer)(i.next());
- assertEquals(four, k);
- k = (Integer)(i.next());
- assertEquals(five, k);
- assertFalse(i.hasNext());
-
- Iterator ei = sm.entrySet().iterator();
- Map.Entry e;
- e = (Map.Entry)(ei.next());
- assertEquals(two, e.getKey());
- assertEquals("B", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(three, e.getKey());
- assertEquals("C", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(four, e.getKey());
- assertEquals("D", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(five, e.getKey());
- assertEquals("E", e.getValue());
- assertFalse(i.hasNext());
-
- SortedMap ssm = sm.tailMap(four);
- assertEquals(four, ssm.firstKey());
- assertEquals(five, ssm.lastKey());
- assertEquals("D", ssm.remove(four));
- assertEquals(1, ssm.size());
- assertEquals(3, sm.size());
- assertEquals(4, map.size());
- }
-
- /**
- * clear removes all pairs
- */
- public void testDescendingClear() {
- ConcurrentNavigableMap map = dmap5();
- map.clear();
- assertEquals(map.size(), 0);
- }
-
-
- /**
- * Maps with same contents are equal
- */
- public void testDescendingEquals() {
- ConcurrentNavigableMap map1 = dmap5();
- ConcurrentNavigableMap map2 = dmap5();
- assertEquals(map1, map2);
- assertEquals(map2, map1);
- map1.clear();
- assertFalse(map1.equals(map2));
- assertFalse(map2.equals(map1));
- }
-
- /**
- * containsKey returns true for contained key
- */
- public void testDescendingContainsKey() {
- ConcurrentNavigableMap map = dmap5();
- assertTrue(map.containsKey(m1));
- assertFalse(map.containsKey(zero));
- }
-
- /**
- * containsValue returns true for held values
- */
- public void testDescendingContainsValue() {
- ConcurrentNavigableMap map = dmap5();
- assertTrue(map.containsValue("A"));
- assertFalse(map.containsValue("Z"));
- }
-
- /**
- * get returns the correct element at the given key,
- * or null if not present
- */
- public void testDescendingGet() {
- ConcurrentNavigableMap map = dmap5();
- assertEquals("A", (String)map.get(m1));
- ConcurrentNavigableMap empty = dmap0();
- assertNull(empty.get(m1));
- }
-
- /**
- * isEmpty is true of empty map and false for non-empty
- */
- public void testDescendingIsEmpty() {
- ConcurrentNavigableMap empty = dmap0();
- ConcurrentNavigableMap map = dmap5();
- assertTrue(empty.isEmpty());
- assertFalse(map.isEmpty());
- }
-
- /**
- * firstKey returns first key
- */
- public void testDescendingFirstKey() {
- ConcurrentNavigableMap map = dmap5();
- assertEquals(m1, map.firstKey());
- }
-
- /**
- * lastKey returns last key
- */
- public void testDescendingLastKey() {
- ConcurrentNavigableMap map = dmap5();
- assertEquals(m5, map.lastKey());
- }
-
-
- /**
- * keySet returns a Set containing all the keys
- */
- public void testDescendingKeySet() {
- ConcurrentNavigableMap map = dmap5();
- Set s = map.keySet();
- assertEquals(5, s.size());
- assertTrue(s.contains(m1));
- assertTrue(s.contains(m2));
- assertTrue(s.contains(m3));
- assertTrue(s.contains(m4));
- assertTrue(s.contains(m5));
- }
-
- /**
- * keySet is ordered
- */
- public void testDescendingKeySetOrder() {
- ConcurrentNavigableMap map = dmap5();
- Set s = map.keySet();
- Iterator i = s.iterator();
- Integer last = (Integer)i.next();
- assertEquals(last, m1);
- while (i.hasNext()) {
- Integer k = (Integer)i.next();
- assertTrue(last.compareTo(k) > 0);
- last = k;
- }
- }
-
- /**
- * values collection contains all values
- */
- public void testDescendingValues() {
- ConcurrentNavigableMap map = dmap5();
- Collection s = map.values();
- assertEquals(5, s.size());
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
- /**
- * keySet.toArray returns contains all keys
- */
- public void testDescendingAscendingKeySetToArray() {
- ConcurrentNavigableMap map = dmap5();
- Set s = map.keySet();
- Object[] ar = s.toArray();
- assertTrue(s.containsAll(Arrays.asList(ar)));
- assertEquals(5, ar.length);
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * descendingkeySet.toArray returns contains all keys
- */
- public void testDescendingDescendingKeySetToArray() {
- ConcurrentNavigableMap map = dmap5();
- Set s = map.descendingKeySet();
- Object[] ar = s.toArray();
- assertEquals(5, ar.length);
- assertTrue(s.containsAll(Arrays.asList(ar)));
- ar[0] = m10;
- assertFalse(s.containsAll(Arrays.asList(ar)));
- }
-
- /**
- * Values.toArray contains all values
- */
- public void testDescendingValuesToArray() {
- ConcurrentNavigableMap map = dmap5();
- Collection v = map.values();
- Object[] ar = v.toArray();
- ArrayList s = new ArrayList(Arrays.asList(ar));
- assertEquals(5, ar.length);
- assertTrue(s.contains("A"));
- assertTrue(s.contains("B"));
- assertTrue(s.contains("C"));
- assertTrue(s.contains("D"));
- assertTrue(s.contains("E"));
- }
-
-
- /**
- * entrySet contains all pairs
- */
- public void testDescendingEntrySet() {
- ConcurrentNavigableMap map = dmap5();
- Set s = map.entrySet();
- assertEquals(5, s.size());
- Iterator it = s.iterator();
- while (it.hasNext()) {
- Map.Entry e = (Map.Entry) it.next();
- assertTrue(
- (e.getKey().equals(m1) && e.getValue().equals("A")) ||
- (e.getKey().equals(m2) && e.getValue().equals("B")) ||
- (e.getKey().equals(m3) && e.getValue().equals("C")) ||
- (e.getKey().equals(m4) && e.getValue().equals("D")) ||
- (e.getKey().equals(m5) && e.getValue().equals("E")));
- }
- }
-
- /**
- * putAll adds all key-value pairs from the given map
- */
- public void testDescendingPutAll() {
- ConcurrentNavigableMap empty = dmap0();
- ConcurrentNavigableMap map = dmap5();
- empty.putAll(map);
- assertEquals(5, empty.size());
- assertTrue(empty.containsKey(m1));
- assertTrue(empty.containsKey(m2));
- assertTrue(empty.containsKey(m3));
- assertTrue(empty.containsKey(m4));
- assertTrue(empty.containsKey(m5));
- }
-
- /**
- * putIfAbsent works when the given key is not present
- */
- public void testDescendingPutIfAbsent() {
- ConcurrentNavigableMap map = dmap5();
- map.putIfAbsent(six, "Z");
- assertTrue(map.containsKey(six));
- }
-
- /**
- * putIfAbsent does not add the pair if the key is already present
- */
- public void testDescendingPutIfAbsent2() {
- ConcurrentNavigableMap map = dmap5();
- assertEquals("A", map.putIfAbsent(m1, "Z"));
- }
-
- /**
- * replace fails when the given key is not present
- */
- public void testDescendingReplace() {
- ConcurrentNavigableMap map = dmap5();
- assertNull(map.replace(six, "Z"));
- assertFalse(map.containsKey(six));
- }
-
- /**
- * replace succeeds if the key is already present
- */
- public void testDescendingReplace2() {
- ConcurrentNavigableMap map = dmap5();
- assertNotNull(map.replace(m1, "Z"));
- assertEquals("Z", map.get(m1));
- }
-
-
- /**
- * replace value fails when the given key not mapped to expected value
- */
- public void testDescendingReplaceValue() {
- ConcurrentNavigableMap map = dmap5();
- assertEquals("A", map.get(m1));
- assertFalse(map.replace(m1, "Z", "Z"));
- assertEquals("A", map.get(m1));
- }
-
- /**
- * replace value succeeds when the given key mapped to expected value
- */
- public void testDescendingReplaceValue2() {
- ConcurrentNavigableMap map = dmap5();
- assertEquals("A", map.get(m1));
- assertTrue(map.replace(m1, "A", "Z"));
- assertEquals("Z", map.get(m1));
- }
-
-
- /**
- * remove removes the correct key-value pair from the map
- */
- public void testDescendingRemove() {
- ConcurrentNavigableMap map = dmap5();
- map.remove(m5);
- assertEquals(4, map.size());
- assertFalse(map.containsKey(m5));
- }
-
- /**
- * remove(key,value) removes only if pair present
- */
- public void testDescendingRemove2() {
- ConcurrentNavigableMap map = dmap5();
- assertTrue(map.containsKey(m5));
- assertEquals("E", map.get(m5));
- map.remove(m5, "E");
- assertEquals(4, map.size());
- assertFalse(map.containsKey(m5));
- map.remove(m4, "A");
- assertEquals(4, map.size());
- assertTrue(map.containsKey(m4));
- }
-
- /**
- * lowerEntry returns preceding entry.
- */
- public void testDescendingLowerEntry() {
- ConcurrentNavigableMap map = dmap5();
- Map.Entry e1 = map.lowerEntry(m3);
- assertEquals(m2, e1.getKey());
-
- Map.Entry e2 = map.lowerEntry(m6);
- assertEquals(m5, e2.getKey());
-
- Map.Entry e3 = map.lowerEntry(m1);
- assertNull(e3);
-
- Map.Entry e4 = map.lowerEntry(zero);
- assertNull(e4);
- }
-
- /**
- * higherEntry returns next entry.
- */
- public void testDescendingHigherEntry() {
- ConcurrentNavigableMap map = dmap5();
- Map.Entry e1 = map.higherEntry(m3);
- assertEquals(m4, e1.getKey());
-
- Map.Entry e2 = map.higherEntry(zero);
- assertEquals(m1, e2.getKey());
-
- Map.Entry e3 = map.higherEntry(m5);
- assertNull(e3);
-
- Map.Entry e4 = map.higherEntry(m6);
- assertNull(e4);
- }
-
- /**
- * floorEntry returns preceding entry.
- */
- public void testDescendingFloorEntry() {
- ConcurrentNavigableMap map = dmap5();
- Map.Entry e1 = map.floorEntry(m3);
- assertEquals(m3, e1.getKey());
-
- Map.Entry e2 = map.floorEntry(m6);
- assertEquals(m5, e2.getKey());
-
- Map.Entry e3 = map.floorEntry(m1);
- assertEquals(m1, e3.getKey());
-
- Map.Entry e4 = map.floorEntry(zero);
- assertNull(e4);
- }
-
- /**
- * ceilingEntry returns next entry.
- */
- public void testDescendingCeilingEntry() {
- ConcurrentNavigableMap map = dmap5();
- Map.Entry e1 = map.ceilingEntry(m3);
- assertEquals(m3, e1.getKey());
-
- Map.Entry e2 = map.ceilingEntry(zero);
- assertEquals(m1, e2.getKey());
-
- Map.Entry e3 = map.ceilingEntry(m5);
- assertEquals(m5, e3.getKey());
-
- Map.Entry e4 = map.ceilingEntry(m6);
- assertNull(e4);
- }
-
- /**
- * pollFirstEntry returns entries in order
- */
- public void testDescendingPollFirstEntry() {
- ConcurrentNavigableMap map = dmap5();
- Map.Entry e = map.pollFirstEntry();
- assertEquals(m1, e.getKey());
- assertEquals("A", e.getValue());
- e = map.pollFirstEntry();
- assertEquals(m2, e.getKey());
- map.put(m1, "A");
- e = map.pollFirstEntry();
- assertEquals(m1, e.getKey());
- assertEquals("A", e.getValue());
- e = map.pollFirstEntry();
- assertEquals(m3, e.getKey());
- map.remove(m4);
- e = map.pollFirstEntry();
- assertEquals(m5, e.getKey());
- try {
- e.setValue("A");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.pollFirstEntry();
- assertNull(e);
- }
-
- /**
- * pollLastEntry returns entries in order
- */
- public void testDescendingPollLastEntry() {
- ConcurrentNavigableMap map = dmap5();
- Map.Entry e = map.pollLastEntry();
- assertEquals(m5, e.getKey());
- assertEquals("E", e.getValue());
- e = map.pollLastEntry();
- assertEquals(m4, e.getKey());
- map.put(m5, "E");
- e = map.pollLastEntry();
- assertEquals(m5, e.getKey());
- assertEquals("E", e.getValue());
- e = map.pollLastEntry();
- assertEquals(m3, e.getKey());
- map.remove(m2);
- e = map.pollLastEntry();
- assertEquals(m1, e.getKey());
- try {
- e.setValue("E");
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- e = map.pollLastEntry();
- assertNull(e);
- }
-
- /**
- * size returns the correct values
- */
- public void testDescendingSize() {
- ConcurrentNavigableMap map = dmap5();
- ConcurrentNavigableMap empty = dmap0();
- assertEquals(0, empty.size());
- assertEquals(5, map.size());
- }
-
- /**
- * toString contains toString of elements
- */
- public void testDescendingToString() {
- ConcurrentNavigableMap map = dmap5();
- String s = map.toString();
- for (int i = 1; i <= 5; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- // Exception testDescendings
-
- /**
- * get(null) of empty map throws NPE
- */
- public void testDescendingGet_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.get(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsKey(null) of empty map throws NPE
- */
- public void testDescendingContainsKey_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.containsKey(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * containsValue(null) throws NPE
- */
- public void testDescendingContainsValue_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap0();
- c.containsValue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * put(null,x) throws NPE
- */
- public void testDescendingPut1_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.put(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * putIfAbsent(null, x) throws NPE
- */
- public void testDescendingPutIfAbsent1_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.putIfAbsent(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x) throws NPE
- */
- public void testDescendingReplace_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.replace(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * replace(null, x, y) throws NPE
- */
- public void testDescendingReplaceValue_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.replace(null, m1, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null) throws NPE
- */
- public void testDescendingRemove1_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.remove(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * remove(null, x) throws NPE
- */
- public void testDescendingRemove2_NullPointerException() {
- try {
- ConcurrentNavigableMap c = dmap5();
- c.remove(null, "whatever");
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * A deserialized map equals original
- */
- public void testDescendingSerialization() throws Exception {
- ConcurrentNavigableMap q = dmap5();
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ConcurrentNavigableMap r = (ConcurrentNavigableMap)in.readObject();
- assertEquals(q.size(), r.size());
- assertTrue(q.equals(r));
- assertTrue(r.equals(q));
- }
-
-
- /**
- * subMap returns map with keys in requested range
- */
- public void testDescendingSubMapContents() {
- ConcurrentNavigableMap map = dmap5();
- SortedMap sm = map.subMap(m2, m4);
- assertEquals(m2, sm.firstKey());
- assertEquals(m3, sm.lastKey());
- assertEquals(2, sm.size());
- assertFalse(sm.containsKey(m1));
- assertTrue(sm.containsKey(m2));
- assertTrue(sm.containsKey(m3));
- assertFalse(sm.containsKey(m4));
- assertFalse(sm.containsKey(m5));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m2, k);
- k = (Integer)(i.next());
- assertEquals(m3, k);
- assertFalse(i.hasNext());
- Iterator j = sm.keySet().iterator();
- j.next();
- j.remove();
- assertFalse(map.containsKey(m2));
- assertEquals(4, map.size());
- assertEquals(1, sm.size());
- assertEquals(m3, sm.firstKey());
- assertEquals(m3, sm.lastKey());
- assertEquals("C", sm.remove(m3));
- assertTrue(sm.isEmpty());
- assertEquals(3, map.size());
- }
-
- public void testDescendingSubMapContents2() {
- ConcurrentNavigableMap map = dmap5();
- SortedMap sm = map.subMap(m2, m3);
- assertEquals(1, sm.size());
- assertEquals(m2, sm.firstKey());
- assertEquals(m2, sm.lastKey());
- assertFalse(sm.containsKey(m1));
- assertTrue(sm.containsKey(m2));
- assertFalse(sm.containsKey(m3));
- assertFalse(sm.containsKey(m4));
- assertFalse(sm.containsKey(m5));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m2, k);
- assertFalse(i.hasNext());
- Iterator j = sm.keySet().iterator();
- j.next();
- j.remove();
- assertFalse(map.containsKey(m2));
- assertEquals(4, map.size());
- assertEquals(0, sm.size());
- assertTrue(sm.isEmpty());
- assertSame(sm.remove(m3), null);
- assertEquals(4, map.size());
- }
-
- /**
- * headMap returns map with keys in requested range
- */
- public void testDescendingHeadMapContents() {
- ConcurrentNavigableMap map = dmap5();
- SortedMap sm = map.headMap(m4);
- assertTrue(sm.containsKey(m1));
- assertTrue(sm.containsKey(m2));
- assertTrue(sm.containsKey(m3));
- assertFalse(sm.containsKey(m4));
- assertFalse(sm.containsKey(m5));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m1, k);
- k = (Integer)(i.next());
- assertEquals(m2, k);
- k = (Integer)(i.next());
- assertEquals(m3, k);
- assertFalse(i.hasNext());
- sm.clear();
- assertTrue(sm.isEmpty());
- assertEquals(2, map.size());
- assertEquals(m4, map.firstKey());
- }
-
- /**
- * headMap returns map with keys in requested range
- */
- public void testDescendingTailMapContents() {
- ConcurrentNavigableMap map = dmap5();
- SortedMap sm = map.tailMap(m2);
- assertFalse(sm.containsKey(m1));
- assertTrue(sm.containsKey(m2));
- assertTrue(sm.containsKey(m3));
- assertTrue(sm.containsKey(m4));
- assertTrue(sm.containsKey(m5));
- Iterator i = sm.keySet().iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m2, k);
- k = (Integer)(i.next());
- assertEquals(m3, k);
- k = (Integer)(i.next());
- assertEquals(m4, k);
- k = (Integer)(i.next());
- assertEquals(m5, k);
- assertFalse(i.hasNext());
-
- Iterator ei = sm.entrySet().iterator();
- Map.Entry e;
- e = (Map.Entry)(ei.next());
- assertEquals(m2, e.getKey());
- assertEquals("B", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(m3, e.getKey());
- assertEquals("C", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(m4, e.getKey());
- assertEquals("D", e.getValue());
- e = (Map.Entry)(ei.next());
- assertEquals(m5, e.getKey());
- assertEquals("E", e.getValue());
- assertFalse(i.hasNext());
-
- SortedMap ssm = sm.tailMap(m4);
- assertEquals(m4, ssm.firstKey());
- assertEquals(m5, ssm.lastKey());
- assertEquals("D", ssm.remove(m4));
- assertEquals(1, ssm.size());
- assertEquals(3, sm.size());
- assertEquals(4, map.size());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSubSetTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSubSetTest.java
deleted file mode 100644
index 9f0a496..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ConcurrentSkipListSubSetTest.java
+++ /dev/null
@@ -1,1117 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class ConcurrentSkipListSubSetTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ConcurrentSkipListSubSetTest.class);
- }
-
- static class MyReverseComparator implements Comparator {
- public int compare(Object x, Object y) {
- return ((Comparable)y).compareTo(x);
- }
- }
-
- /**
- * Create a set of given size containing consecutive
- * Integers 0 ... n.
- */
- private NavigableSet populatedSet(int n) {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.isEmpty());
-
- for (int i = n-1; i >= 0; i-=2)
- assertTrue(q.add(new Integer(i)));
- for (int i = (n & 1); i < n; i+=2)
- assertTrue(q.add(new Integer(i)));
- assertTrue(q.add(new Integer(-n)));
- assertTrue(q.add(new Integer(n)));
- NavigableSet s = q.subSet(new Integer(0), true, new Integer(n), false);
- assertFalse(s.isEmpty());
- assertEquals(n, s.size());
- return s;
- }
-
- /**
- * Create set of first 5 ints
- */
- private NavigableSet set5() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.isEmpty());
- q.add(one);
- q.add(two);
- q.add(three);
- q.add(four);
- q.add(five);
- q.add(zero);
- q.add(seven);
- NavigableSet s = q.subSet(one, true, seven, false);
- assertEquals(5, s.size());
- return s;
- }
-
- /**
- * Create set of first 5 negative ints
- */
- private NavigableSet dset5() {
- ConcurrentSkipListSet q = new ConcurrentSkipListSet();
- assertTrue(q.isEmpty());
- q.add(m1);
- q.add(m2);
- q.add(m3);
- q.add(m4);
- q.add(m5);
- NavigableSet s = q.descendingSet();
- assertEquals(5, s.size());
- return s;
- }
-
- private static NavigableSet set0() {
- ConcurrentSkipListSet set = new ConcurrentSkipListSet();
- assertTrue(set.isEmpty());
- return set.tailSet(m1, true);
- }
-
- private static NavigableSet dset0() {
- ConcurrentSkipListSet set = new ConcurrentSkipListSet();
- assertTrue(set.isEmpty());
- return set;
- }
-
- /**
- * A new set has unbounded capacity
- */
- public void testConstructor1() {
- assertEquals(0, set0().size());
- }
-
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- NavigableSet q = set0();
- assertTrue(q.isEmpty());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.add(new Integer(2));
- q.pollFirst();
- q.pollFirst();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.pollFirst();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- NavigableSet q = set0();
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Add of comparable element succeeds
- */
- public void testAdd() {
- NavigableSet q = set0();
- assertTrue(q.add(six));
- }
-
- /**
- * Add of duplicate element fails
- */
- public void testAddDup() {
- NavigableSet q = set0();
- assertTrue(q.add(six));
- assertFalse(q.add(six));
- }
-
- /**
- * Add of non-Comparable throws CCE
- */
- public void testAddNonComparable() {
- try {
- NavigableSet q = set0();
- q.add(new Object());
- q.add(new Object());
- q.add(new Object());
- shouldThrow();
- } catch (ClassCastException success) {}
- }
-
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- NavigableSet q = set0();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- NavigableSet q = set0();
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- NavigableSet q = set0();
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i+SIZE);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Set contains all elements of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(SIZE-1- i);
- NavigableSet q = set0();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(new Integer(i), q.pollFirst());
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst());
- }
- assertNull(q.pollFirst());
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.pollFirst();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- NavigableSet q = populatedSet(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- NavigableSet q = populatedSet(SIZE);
- NavigableSet p = set0();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- NavigableSet q = populatedSet(SIZE);
- NavigableSet p = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.pollFirst();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- NavigableSet q = populatedSet(SIZE);
- NavigableSet p = populatedSet(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.pollFirst());
- assertFalse(q.contains(I));
- }
- }
- }
-
-
-
- /**
- * lower returns preceding element
- */
- public void testLower() {
- NavigableSet q = set5();
- Object e1 = q.lower(three);
- assertEquals(two, e1);
-
- Object e2 = q.lower(six);
- assertEquals(five, e2);
-
- Object e3 = q.lower(one);
- assertNull(e3);
-
- Object e4 = q.lower(zero);
- assertNull(e4);
- }
-
- /**
- * higher returns next element
- */
- public void testHigher() {
- NavigableSet q = set5();
- Object e1 = q.higher(three);
- assertEquals(four, e1);
-
- Object e2 = q.higher(zero);
- assertEquals(one, e2);
-
- Object e3 = q.higher(five);
- assertNull(e3);
-
- Object e4 = q.higher(six);
- assertNull(e4);
- }
-
- /**
- * floor returns preceding element
- */
- public void testFloor() {
- NavigableSet q = set5();
- Object e1 = q.floor(three);
- assertEquals(three, e1);
-
- Object e2 = q.floor(six);
- assertEquals(five, e2);
-
- Object e3 = q.floor(one);
- assertEquals(one, e3);
-
- Object e4 = q.floor(zero);
- assertNull(e4);
- }
-
- /**
- * ceiling returns next element
- */
- public void testCeiling() {
- NavigableSet q = set5();
- Object e1 = q.ceiling(three);
- assertEquals(three, e1);
-
- Object e2 = q.ceiling(zero);
- assertEquals(one, e2);
-
- Object e3 = q.ceiling(five);
- assertEquals(five, e3);
-
- Object e4 = q.ceiling(six);
- assertNull(e4);
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() {
- NavigableSet q = populatedSet(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.pollFirst());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() {
- NavigableSet q = populatedSet(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- NavigableSet q = populatedSet(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator of empty set has no elements
- */
- public void testEmptyIterator() {
- NavigableSet q = set0();
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, 0);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final NavigableSet q = set0();
- q.add(new Integer(2));
- q.add(new Integer(1));
- q.add(new Integer(3));
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- NavigableSet q = populatedSet(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * A deserialized serialized set has same elements
- */
- public void testSerialization() throws Exception {
- NavigableSet q = populatedSet(SIZE);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- NavigableSet r = (NavigableSet)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.pollFirst(), r.pollFirst());
- }
-
- /**
- * subSet returns set with keys in requested range
- */
- public void testSubSetContents() {
- NavigableSet set = set5();
- SortedSet sm = set.subSet(two, four);
- assertEquals(two, sm.first());
- assertEquals(three, sm.last());
- assertEquals(2, sm.size());
- assertFalse(sm.contains(one));
- assertTrue(sm.contains(two));
- assertTrue(sm.contains(three));
- assertFalse(sm.contains(four));
- assertFalse(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- Iterator j = sm.iterator();
- j.next();
- j.remove();
- assertFalse(set.contains(two));
- assertEquals(4, set.size());
- assertEquals(1, sm.size());
- assertEquals(three, sm.first());
- assertEquals(three, sm.last());
- assertTrue(sm.remove(three));
- assertTrue(sm.isEmpty());
- assertEquals(3, set.size());
- }
-
- public void testSubSetContents2() {
- NavigableSet set = set5();
- SortedSet sm = set.subSet(two, three);
- assertEquals(1, sm.size());
- assertEquals(two, sm.first());
- assertEquals(two, sm.last());
- assertFalse(sm.contains(one));
- assertTrue(sm.contains(two));
- assertFalse(sm.contains(three));
- assertFalse(sm.contains(four));
- assertFalse(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- assertFalse(i.hasNext());
- Iterator j = sm.iterator();
- j.next();
- j.remove();
- assertFalse(set.contains(two));
- assertEquals(4, set.size());
- assertEquals(0, sm.size());
- assertTrue(sm.isEmpty());
- assertFalse(sm.remove(three));
- assertEquals(4, set.size());
- }
-
- /**
- * headSet returns set with keys in requested range
- */
- public void testHeadSetContents() {
- NavigableSet set = set5();
- SortedSet sm = set.headSet(four);
- assertTrue(sm.contains(one));
- assertTrue(sm.contains(two));
- assertTrue(sm.contains(three));
- assertFalse(sm.contains(four));
- assertFalse(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(one, k);
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- assertFalse(i.hasNext());
- sm.clear();
- assertTrue(sm.isEmpty());
- assertEquals(2, set.size());
- assertEquals(four, set.first());
- }
-
- /**
- * tailSet returns set with keys in requested range
- */
- public void testTailSetContents() {
- NavigableSet set = set5();
- SortedSet sm = set.tailSet(two);
- assertFalse(sm.contains(one));
- assertTrue(sm.contains(two));
- assertTrue(sm.contains(three));
- assertTrue(sm.contains(four));
- assertTrue(sm.contains(five));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(two, k);
- k = (Integer)(i.next());
- assertEquals(three, k);
- k = (Integer)(i.next());
- assertEquals(four, k);
- k = (Integer)(i.next());
- assertEquals(five, k);
- assertFalse(i.hasNext());
-
- SortedSet ssm = sm.tailSet(four);
- assertEquals(four, ssm.first());
- assertEquals(five, ssm.last());
- assertTrue(ssm.remove(four));
- assertEquals(1, ssm.size());
- assertEquals(3, sm.size());
- assertEquals(4, set.size());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testDescendingSize() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.pollFirst();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * add(null) throws NPE
- */
- public void testDescendingAddNull() {
- try {
- NavigableSet q = dset0();
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Add of comparable element succeeds
- */
- public void testDescendingAdd() {
- NavigableSet q = dset0();
- assertTrue(q.add(m6));
- }
-
- /**
- * Add of duplicate element fails
- */
- public void testDescendingAddDup() {
- NavigableSet q = dset0();
- assertTrue(q.add(m6));
- assertFalse(q.add(m6));
- }
-
- /**
- * Add of non-Comparable throws CCE
- */
- public void testDescendingAddNonComparable() {
- try {
- NavigableSet q = dset0();
- q.add(new Object());
- q.add(new Object());
- q.add(new Object());
- shouldThrow();
- } catch (ClassCastException success) {}
- }
-
-
- /**
- * addAll(null) throws NPE
- */
- public void testDescendingAddAll1() {
- try {
- NavigableSet q = dset0();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testDescendingAddAll2() {
- try {
- NavigableSet q = dset0();
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testDescendingAddAll3() {
- try {
- NavigableSet q = dset0();
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i+SIZE);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Set contains all elements of successful addAll
- */
- public void testDescendingAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(SIZE-1- i);
- NavigableSet q = dset0();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(new Integer(i), q.pollFirst());
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testDescendingPoll() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst());
- }
- assertNull(q.pollFirst());
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testDescendingRemoveElement() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testDescendingContains() {
- NavigableSet q = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.pollFirst();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testDescendingClear() {
- NavigableSet q = populatedSet(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testDescendingContainsAll() {
- NavigableSet q = populatedSet(SIZE);
- NavigableSet p = dset0();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testDescendingRetainAll() {
- NavigableSet q = populatedSet(SIZE);
- NavigableSet p = populatedSet(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.pollFirst();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testDescendingRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- NavigableSet q = populatedSet(SIZE);
- NavigableSet p = populatedSet(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.pollFirst());
- assertFalse(q.contains(I));
- }
- }
- }
-
-
-
- /**
- * lower returns preceding element
- */
- public void testDescendingLower() {
- NavigableSet q = dset5();
- Object e1 = q.lower(m3);
- assertEquals(m2, e1);
-
- Object e2 = q.lower(m6);
- assertEquals(m5, e2);
-
- Object e3 = q.lower(m1);
- assertNull(e3);
-
- Object e4 = q.lower(zero);
- assertNull(e4);
- }
-
- /**
- * higher returns next element
- */
- public void testDescendingHigher() {
- NavigableSet q = dset5();
- Object e1 = q.higher(m3);
- assertEquals(m4, e1);
-
- Object e2 = q.higher(zero);
- assertEquals(m1, e2);
-
- Object e3 = q.higher(m5);
- assertNull(e3);
-
- Object e4 = q.higher(m6);
- assertNull(e4);
- }
-
- /**
- * floor returns preceding element
- */
- public void testDescendingFloor() {
- NavigableSet q = dset5();
- Object e1 = q.floor(m3);
- assertEquals(m3, e1);
-
- Object e2 = q.floor(m6);
- assertEquals(m5, e2);
-
- Object e3 = q.floor(m1);
- assertEquals(m1, e3);
-
- Object e4 = q.floor(zero);
- assertNull(e4);
- }
-
- /**
- * ceiling returns next element
- */
- public void testDescendingCeiling() {
- NavigableSet q = dset5();
- Object e1 = q.ceiling(m3);
- assertEquals(m3, e1);
-
- Object e2 = q.ceiling(zero);
- assertEquals(m1, e2);
-
- Object e3 = q.ceiling(m5);
- assertEquals(m5, e3);
-
- Object e4 = q.ceiling(m6);
- assertNull(e4);
- }
-
- /**
- * toArray contains all elements
- */
- public void testDescendingToArray() {
- NavigableSet q = populatedSet(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.pollFirst());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testDescendingToArray2() {
- NavigableSet q = populatedSet(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.pollFirst());
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testDescendingIterator() {
- NavigableSet q = populatedSet(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator of empty set has no elements
- */
- public void testDescendingEmptyIterator() {
- NavigableSet q = dset0();
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, 0);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testDescendingIteratorRemove () {
- final NavigableSet q = dset0();
- q.add(new Integer(2));
- q.add(new Integer(1));
- q.add(new Integer(3));
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testDescendingToString() {
- NavigableSet q = populatedSet(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * A deserialized serialized set has same elements
- */
- public void testDescendingSerialization() throws Exception {
- NavigableSet q = populatedSet(SIZE);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- NavigableSet r = (NavigableSet)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.pollFirst(), r.pollFirst());
- }
-
- /**
- * subSet returns set with keys in requested range
- */
- public void testDescendingSubSetContents() {
- NavigableSet set = dset5();
- SortedSet sm = set.subSet(m2, m4);
- assertEquals(m2, sm.first());
- assertEquals(m3, sm.last());
- assertEquals(2, sm.size());
- assertFalse(sm.contains(m1));
- assertTrue(sm.contains(m2));
- assertTrue(sm.contains(m3));
- assertFalse(sm.contains(m4));
- assertFalse(sm.contains(m5));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m2, k);
- k = (Integer)(i.next());
- assertEquals(m3, k);
- assertFalse(i.hasNext());
- Iterator j = sm.iterator();
- j.next();
- j.remove();
- assertFalse(set.contains(m2));
- assertEquals(4, set.size());
- assertEquals(1, sm.size());
- assertEquals(m3, sm.first());
- assertEquals(m3, sm.last());
- assertTrue(sm.remove(m3));
- assertTrue(sm.isEmpty());
- assertEquals(3, set.size());
- }
-
- public void testDescendingSubSetContents2() {
- NavigableSet set = dset5();
- SortedSet sm = set.subSet(m2, m3);
- assertEquals(1, sm.size());
- assertEquals(m2, sm.first());
- assertEquals(m2, sm.last());
- assertFalse(sm.contains(m1));
- assertTrue(sm.contains(m2));
- assertFalse(sm.contains(m3));
- assertFalse(sm.contains(m4));
- assertFalse(sm.contains(m5));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m2, k);
- assertFalse(i.hasNext());
- Iterator j = sm.iterator();
- j.next();
- j.remove();
- assertFalse(set.contains(m2));
- assertEquals(4, set.size());
- assertEquals(0, sm.size());
- assertTrue(sm.isEmpty());
- assertFalse(sm.remove(m3));
- assertEquals(4, set.size());
- }
-
- /**
- * headSet returns set with keys in requested range
- */
- public void testDescendingHeadSetContents() {
- NavigableSet set = dset5();
- SortedSet sm = set.headSet(m4);
- assertTrue(sm.contains(m1));
- assertTrue(sm.contains(m2));
- assertTrue(sm.contains(m3));
- assertFalse(sm.contains(m4));
- assertFalse(sm.contains(m5));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m1, k);
- k = (Integer)(i.next());
- assertEquals(m2, k);
- k = (Integer)(i.next());
- assertEquals(m3, k);
- assertFalse(i.hasNext());
- sm.clear();
- assertTrue(sm.isEmpty());
- assertEquals(2, set.size());
- assertEquals(m4, set.first());
- }
-
- /**
- * tailSet returns set with keys in requested range
- */
- public void testDescendingTailSetContents() {
- NavigableSet set = dset5();
- SortedSet sm = set.tailSet(m2);
- assertFalse(sm.contains(m1));
- assertTrue(sm.contains(m2));
- assertTrue(sm.contains(m3));
- assertTrue(sm.contains(m4));
- assertTrue(sm.contains(m5));
- Iterator i = sm.iterator();
- Object k;
- k = (Integer)(i.next());
- assertEquals(m2, k);
- k = (Integer)(i.next());
- assertEquals(m3, k);
- k = (Integer)(i.next());
- assertEquals(m4, k);
- k = (Integer)(i.next());
- assertEquals(m5, k);
- assertFalse(i.hasNext());
-
- SortedSet ssm = sm.tailSet(m4);
- assertEquals(m4, ssm.first());
- assertEquals(m5, ssm.last());
- assertTrue(ssm.remove(m4));
- assertEquals(1, ssm.size());
- assertEquals(3, sm.size());
- assertEquals(4, set.size());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java b/luni/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java
deleted file mode 100755
index 90d708a..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class CopyOnWriteArrayListTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(CopyOnWriteArrayListTest.class);
- }
-
- static CopyOnWriteArrayList populatedArray(int n) {
- CopyOnWriteArrayList a = new CopyOnWriteArrayList();
- assertTrue(a.isEmpty());
- for (int i = 0; i < n; ++i)
- a.add(new Integer(i));
- assertFalse(a.isEmpty());
- assertEquals(n, a.size());
- return a;
- }
-
-
- /**
- * a new list is empty
- */
- public void testConstructor() {
- CopyOnWriteArrayList a = new CopyOnWriteArrayList();
- assertTrue(a.isEmpty());
- }
-
- /**
- * new list contains all elements of initializing array
- */
- public void testConstructor2() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- CopyOnWriteArrayList a = new CopyOnWriteArrayList(ints);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], a.get(i));
- }
-
- /**
- * new list contains all elements of initializing collection
- */
- public void testConstructor3() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- CopyOnWriteArrayList a = new CopyOnWriteArrayList(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], a.get(i));
- }
-
-
- /**
- * addAll adds each element from the given collection
- */
- public void testAddAll() {
- CopyOnWriteArrayList full = populatedArray(3);
- Vector v = new Vector();
- v.add(three);
- v.add(four);
- v.add(five);
- full.addAll(v);
- assertEquals(6, full.size());
- }
-
- /**
- * addAllAbsent adds each element from the given collection that did not
- * already exist in the List
- */
- public void testAddAllAbsent() {
- CopyOnWriteArrayList full = populatedArray(3);
- Vector v = new Vector();
- v.add(three);
- v.add(four);
- v.add(one); // will not add this element
- full.addAllAbsent(v);
- assertEquals(5, full.size());
- }
-
- /**
- * addIfAbsent will not add the element if it already exists in the list
- */
- public void testAddIfAbsent() {
- CopyOnWriteArrayList full = populatedArray(SIZE);
- full.addIfAbsent(one);
- assertEquals(SIZE, full.size());
- }
-
- /**
- * addIfAbsent adds the element when it does not exist in the list
- */
- public void testAddIfAbsent2() {
- CopyOnWriteArrayList full = populatedArray(SIZE);
- full.addIfAbsent(three);
- assertTrue(full.contains(three));
- }
-
- /**
- * clear removes all elements from the list
- */
- public void testClear() {
- CopyOnWriteArrayList full = populatedArray(SIZE);
- full.clear();
- assertEquals(0, full.size());
- }
-
-
- /**
- * Cloned list is equal
- */
- public void testClone() {
- CopyOnWriteArrayList l1 = populatedArray(SIZE);
- CopyOnWriteArrayList l2 = (CopyOnWriteArrayList)(l1.clone());
- assertEquals(l1, l2);
- l1.clear();
- assertFalse(l1.equals(l2));
- }
-
- /**
- * contains is true for added elements
- */
- public void testContains() {
- CopyOnWriteArrayList full = populatedArray(3);
- assertTrue(full.contains(one));
- assertFalse(full.contains(five));
- }
-
- /**
- * adding at an index places it in the indicated index
- */
- public void testAddIndex() {
- CopyOnWriteArrayList full = populatedArray(3);
- full.add(0, m1);
- assertEquals(4, full.size());
- assertEquals(m1, full.get(0));
- assertEquals(zero, full.get(1));
-
- full.add(2, m2);
- assertEquals(5, full.size());
- assertEquals(m2, full.get(2));
- assertEquals(two, full.get(4));
- }
-
- /**
- * lists with same elements are equal and have same hashCode
- */
- public void testEquals() {
- CopyOnWriteArrayList a = populatedArray(3);
- CopyOnWriteArrayList b = populatedArray(3);
- assertTrue(a.equals(b));
- assertTrue(b.equals(a));
- assertEquals(a.hashCode(), b.hashCode());
- a.add(m1);
- assertFalse(a.equals(b));
- assertFalse(b.equals(a));
- b.add(m1);
- assertTrue(a.equals(b));
- assertTrue(b.equals(a));
- assertEquals(a.hashCode(), b.hashCode());
- }
-
-
- /**
- * containsAll returns true for collection with subset of elements
- */
- public void testContainsAll() {
- CopyOnWriteArrayList full = populatedArray(3);
- Vector v = new Vector();
- v.add(one);
- v.add(two);
- assertTrue(full.containsAll(v));
- v.add(six);
- assertFalse(full.containsAll(v));
- }
-
- /**
- * get returns the value at the given index
- */
- public void testGet() {
- CopyOnWriteArrayList full = populatedArray(3);
- assertEquals(0, full.get(0));
- }
-
- /**
- * indexOf gives the index for the given object
- */
- public void testIndexOf() {
- CopyOnWriteArrayList full = populatedArray(3);
- assertEquals(1, full.indexOf(one));
- assertEquals(-1, full.indexOf("puppies"));
- }
-
- /**
- * indexOf gives the index based on the given index
- * at which to start searching
- */
- public void testIndexOf2() {
- CopyOnWriteArrayList full = populatedArray(3);
- assertEquals(1, full.indexOf(one, 0));
- assertEquals(-1, full.indexOf(one, 2));
- }
-
- /**
- * isEmpty returns true when empty, else false
- */
- public void testIsEmpty() {
- CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
- CopyOnWriteArrayList full = populatedArray(SIZE);
- assertTrue(empty.isEmpty());
- assertFalse(full.isEmpty());
- }
-
- /**
- * iterator() returns an iterator containing the elements of the list
- */
- public void testIterator() {
- CopyOnWriteArrayList full = populatedArray(SIZE);
- Iterator i = full.iterator();
- int j;
- for (j = 0; i.hasNext(); j++)
- assertEquals(j, i.next());
- assertEquals(SIZE, j);
- }
-
- /**
- * iterator.remove throws UnsupportedOperationException
- */
- public void testIteratorRemove () {
- CopyOnWriteArrayList full = populatedArray(SIZE);
- Iterator it = full.iterator();
- it.next();
- try {
- it.remove();
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- }
-
- /**
- * toString contains toString of elements
- */
- public void testToString() {
- CopyOnWriteArrayList full = populatedArray(3);
- String s = full.toString();
- for (int i = 0; i < 3; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * lastIndexOf returns the index for the given object
- */
- public void testLastIndexOf1() {
- CopyOnWriteArrayList full = populatedArray(3);
- full.add(one);
- full.add(three);
- assertEquals(3, full.lastIndexOf(one));
- assertEquals(-1, full.lastIndexOf(six));
- }
-
- /**
- * lastIndexOf returns the index from the given starting point
- */
- public void testlastIndexOf2() {
- CopyOnWriteArrayList full = populatedArray(3);
- full.add(one);
- full.add(three);
- assertEquals(3, full.lastIndexOf(one, 4));
- assertEquals(-1, full.lastIndexOf(three, 3));
- }
-
- /**
- * listIterator traverses all elements
- */
- public void testListIterator1() {
- CopyOnWriteArrayList full = populatedArray(SIZE);
- ListIterator i = full.listIterator();
- int j;
- for (j = 0; i.hasNext(); j++)
- assertEquals(j, i.next());
- assertEquals(SIZE, j);
- }
-
- /**
- * listIterator only returns those elements after the given index
- */
- public void testListIterator2() {
- CopyOnWriteArrayList full = populatedArray(3);
- ListIterator i = full.listIterator(1);
- int j;
- for (j = 0; i.hasNext(); j++)
- assertEquals(j+1, i.next());
- assertEquals(2, j);
- }
-
- /**
- * remove removes and returns the object at the given index
- */
- public void testRemove() {
- CopyOnWriteArrayList full = populatedArray(3);
- assertEquals(2, full.remove(2));
- assertEquals(2, full.size());
- }
-
- /**
- * removeAll removes all elements from the given collection
- */
- public void testRemoveAll() {
- CopyOnWriteArrayList full = populatedArray(3);
- Vector v = new Vector();
- v.add(one);
- v.add(two);
- full.removeAll(v);
- assertEquals(1, full.size());
- }
-
- /**
- * set changes the element at the given index
- */
- public void testSet() {
- CopyOnWriteArrayList full = populatedArray(3);
- assertEquals(2, full.set(2, four));
- assertEquals(4, full.get(2));
- }
-
- /**
- * size returns the number of elements
- */
- public void testSize() {
- CopyOnWriteArrayList empty = new CopyOnWriteArrayList();
- CopyOnWriteArrayList full = populatedArray(SIZE);
- assertEquals(SIZE, full.size());
- assertEquals(0, empty.size());
- }
-
- /**
- * toArray returns an Object array containing all elements from the list
- */
- public void testToArray() {
- CopyOnWriteArrayList full = populatedArray(3);
- Object[] o = full.toArray();
- assertEquals(3, o.length);
- assertEquals(0, o[0]);
- assertEquals(1, o[1]);
- assertEquals(2, o[2]);
- }
-
- /**
- * toArray returns an Integer array containing all elements from
- * the list
- */
- public void testToArray2() {
- CopyOnWriteArrayList full = populatedArray(3);
- Integer[] i = new Integer[3];
- i = (Integer[])full.toArray(i);
- assertEquals(3, i.length);
- assertEquals(0, i[0].intValue());
- assertEquals(1, i[1].intValue());
- assertEquals(2, i[2].intValue());
- }
-
-
- /**
- * sublists contains elements at indexes offset from their base
- */
- public void testSubList() {
- CopyOnWriteArrayList a = populatedArray(10);
- assertTrue(a.subList(1,1).isEmpty());
- for (int j = 0; j < 9; ++j) {
- for (int i = j ; i < 10; ++i) {
- List b = a.subList(j,i);
- for (int k = j; k < i; ++k) {
- assertEquals(new Integer(k), b.get(k-j));
- }
- }
- }
-
- List s = a.subList(2, 5);
- assertEquals(s.size(), 3);
- s.set(2, m1);
- assertEquals(a.get(4), m1);
- s.clear();
- assertEquals(a.size(), 7);
- }
-
- // Exception tests
-
- /**
- * toArray throws an ArrayStoreException when the given array
- * can not store the objects inside the list
- */
- public void testToArray_ArrayStoreException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("zfasdfsdf");
- c.add("asdadasd");
- c.toArray(new Long[5]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
- /**
- * get throws an IndexOutOfBoundsException on a negative index
- */
- public void testGet1_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.get(-1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * get throws an IndexOutOfBoundsException on a too high index
- */
- public void testGet2_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("asdasd");
- c.add("asdad");
- c.get(100);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * set throws an IndexOutOfBoundsException on a negative index
- */
- public void testSet1_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.set(-1,"qwerty");
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * set throws an IndexOutOfBoundsException on a too high index
- */
- public void testSet2() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("asdasd");
- c.add("asdad");
- c.set(100, "qwerty");
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * add throws an IndexOutOfBoundsException on a negative index
- */
- public void testAdd1_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add(-1,"qwerty");
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * add throws an IndexOutOfBoundsException on a too high index
- */
- public void testAdd2_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("asdasd");
- c.add("asdasdasd");
- c.add(100, "qwerty");
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * remove throws an IndexOutOfBoundsException on a negative index
- */
- public void testRemove1_IndexOutOfBounds() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.remove(-1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * remove throws an IndexOutOfBoundsException on a too high index
- */
- public void testRemove2_IndexOutOfBounds() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("asdasd");
- c.add("adasdasd");
- c.remove(100);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * addAll throws an IndexOutOfBoundsException on a negative index
- */
- public void testAddAll1_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.addAll(-1,new LinkedList());
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * addAll throws an IndexOutOfBoundsException on a too high index
- */
- public void testAddAll2_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("asdasd");
- c.add("asdasdasd");
- c.addAll(100, new LinkedList());
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * listIterator throws an IndexOutOfBoundsException on a negative index
- */
- public void testListIterator1_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.listIterator(-1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * listIterator throws an IndexOutOfBoundsException on a too high index
- */
- public void testListIterator2_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("adasd");
- c.add("asdasdas");
- c.listIterator(100);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * subList throws an IndexOutOfBoundsException on a negative index
- */
- public void testSubList1_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.subList(-1,100);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * subList throws an IndexOutOfBoundsException on a too high index
- */
- public void testSubList2_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.add("asdasd");
- c.subList(1,100);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * subList throws IndexOutOfBoundsException when the second index
- * is lower then the first
- */
- public void testSubList3_IndexOutOfBoundsException() {
- try {
- CopyOnWriteArrayList c = new CopyOnWriteArrayList();
- c.subList(3,1);
- shouldThrow();
- } catch (IndexOutOfBoundsException success) {}
- }
-
- /**
- * a deserialized serialized list is equal
- */
- public void testSerialization() throws Exception {
- CopyOnWriteArrayList q = populatedArray(SIZE);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- CopyOnWriteArrayList r = (CopyOnWriteArrayList)in.readObject();
- assertEquals(q.size(), r.size());
- assertTrue(q.equals(r));
- assertTrue(r.equals(q));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java b/luni/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java
deleted file mode 100755
index c78ac50..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class CopyOnWriteArraySetTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(CopyOnWriteArraySetTest.class);
- }
-
- static CopyOnWriteArraySet populatedSet(int n) {
- CopyOnWriteArraySet a = new CopyOnWriteArraySet();
- assertTrue(a.isEmpty());
- for (int i = 0; i < n; ++i)
- a.add(new Integer(i));
- assertFalse(a.isEmpty());
- assertEquals(n, a.size());
- return a;
- }
-
- /**
- * Default-constructed set is empty
- */
- public void testConstructor() {
- CopyOnWriteArraySet a = new CopyOnWriteArraySet();
- assertTrue(a.isEmpty());
- }
-
- /**
- * Collection-constructed set holds all of its elements
- */
- public void testConstructor3() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- CopyOnWriteArraySet a = new CopyOnWriteArraySet(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertTrue(a.contains(ints[i]));
- }
-
-
- /**
- * addAll adds each element from the given collection
- */
- public void testAddAll() {
- CopyOnWriteArraySet full = populatedSet(3);
- Vector v = new Vector();
- v.add(three);
- v.add(four);
- v.add(five);
- full.addAll(v);
- assertEquals(6, full.size());
- }
-
- /**
- * addAll adds each element from the given collection that did not
- * already exist in the set
- */
- public void testAddAll2() {
- CopyOnWriteArraySet full = populatedSet(3);
- Vector v = new Vector();
- v.add(three);
- v.add(four);
- v.add(one); // will not add this element
- full.addAll(v);
- assertEquals(5, full.size());
- }
-
- /**
- * add will not add the element if it already exists in the set
- */
- public void testAdd2() {
- CopyOnWriteArraySet full = populatedSet(3);
- full.add(one);
- assertEquals(3, full.size());
- }
-
- /**
- * add adds the element when it does not exist
- * in the set
- */
- public void testAdd3() {
- CopyOnWriteArraySet full = populatedSet(3);
- full.add(three);
- assertTrue(full.contains(three));
- }
-
- /**
- * clear removes all elements from the set
- */
- public void testClear() {
- CopyOnWriteArraySet full = populatedSet(3);
- full.clear();
- assertEquals(0, full.size());
- }
-
- /**
- * contains returns true for added elements
- */
- public void testContains() {
- CopyOnWriteArraySet full = populatedSet(3);
- assertTrue(full.contains(one));
- assertFalse(full.contains(five));
- }
-
- /**
- * Sets with equal elements are equal
- */
- public void testEquals() {
- CopyOnWriteArraySet a = populatedSet(3);
- CopyOnWriteArraySet b = populatedSet(3);
- assertTrue(a.equals(b));
- assertTrue(b.equals(a));
- assertEquals(a.hashCode(), b.hashCode());
- a.add(m1);
- assertFalse(a.equals(b));
- assertFalse(b.equals(a));
- b.add(m1);
- assertTrue(a.equals(b));
- assertTrue(b.equals(a));
- assertEquals(a.hashCode(), b.hashCode());
- }
-
-
- /**
- * containsAll returns true for collections with subset of elements
- */
- public void testContainsAll() {
- CopyOnWriteArraySet full = populatedSet(3);
- Vector v = new Vector();
- v.add(one);
- v.add(two);
- assertTrue(full.containsAll(v));
- v.add(six);
- assertFalse(full.containsAll(v));
- }
-
- /**
- * isEmpty is true when empty, else false
- */
- public void testIsEmpty() {
- CopyOnWriteArraySet empty = new CopyOnWriteArraySet();
- CopyOnWriteArraySet full = populatedSet(3);
- assertTrue(empty.isEmpty());
- assertFalse(full.isEmpty());
- }
-
- /**
- * iterator() returns an iterator containing the elements of the set
- */
- public void testIterator() {
- CopyOnWriteArraySet full = populatedSet(3);
- Iterator i = full.iterator();
- int j;
- for (j = 0; i.hasNext(); j++)
- assertEquals(j, i.next());
- assertEquals(3, j);
- }
-
- /**
- * iterator remove is unsupported
- */
- public void testIteratorRemove () {
- CopyOnWriteArraySet full = populatedSet(3);
- Iterator it = full.iterator();
- it.next();
- try {
- it.remove();
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- }
-
- /**
- * toString holds toString of elements
- */
- public void testToString() {
- CopyOnWriteArraySet full = populatedSet(3);
- String s = full.toString();
- for (int i = 0; i < 3; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
-
- /**
- * removeAll removes all elements from the given collection
- */
- public void testRemoveAll() {
- CopyOnWriteArraySet full = populatedSet(3);
- Vector v = new Vector();
- v.add(one);
- v.add(two);
- full.removeAll(v);
- assertEquals(1, full.size());
- }
-
-
- /**
- * remove removes an element
- */
- public void testRemove() {
- CopyOnWriteArraySet full = populatedSet(3);
- full.remove(one);
- assertFalse(full.contains(one));
- assertEquals(2, full.size());
- }
-
- /**
- * size returns the number of elements
- */
- public void testSize() {
- CopyOnWriteArraySet empty = new CopyOnWriteArraySet();
- CopyOnWriteArraySet full = populatedSet(3);
- assertEquals(3, full.size());
- assertEquals(0, empty.size());
- }
-
- /**
- * toArray returns an Object array containing all elements from the set
- */
- public void testToArray() {
- CopyOnWriteArraySet full = populatedSet(3);
- Object[] o = full.toArray();
- assertEquals(3, o.length);
- assertEquals(0, o[0]);
- assertEquals(1, o[1]);
- assertEquals(2, o[2]);
- }
-
- /**
- * toArray returns an Integer array containing all elements from
- * the set
- */
- public void testToArray2() {
- CopyOnWriteArraySet full = populatedSet(3);
- Integer[] i = new Integer[3];
- i = (Integer[])full.toArray(i);
- assertEquals(3, i.length);
- assertEquals(0, (int) i[0]);
- assertEquals(1, (int) i[1]);
- assertEquals(2, (int) i[2]);
- }
-
-
- /**
- * toArray throws an ArrayStoreException when the given array can
- * not store the objects inside the set
- */
- public void testToArray_ArrayStoreException() {
- try {
- CopyOnWriteArraySet c = new CopyOnWriteArraySet();
- c.add("zfasdfsdf");
- c.add("asdadasd");
- c.toArray(new Long[5]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
- /**
- * A deserialized serialized set is equal
- */
- public void testSerialization() throws Exception {
- CopyOnWriteArraySet q = populatedSet(SIZE);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- CopyOnWriteArraySet r = (CopyOnWriteArraySet)in.readObject();
- assertEquals(q.size(), r.size());
- assertTrue(q.equals(r));
- assertTrue(r.equals(q));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java b/luni/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java
deleted file mode 100755
index b06004e4..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-
-public class CountDownLatchTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(CountDownLatchTest.class);
- }
-
- /**
- * negative constructor argument throws IAE
- */
- public void testConstructor() {
- try {
- new CountDownLatch(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getCount returns initial count and decreases after countDown
- */
- public void testGetCount() {
- final CountDownLatch l = new CountDownLatch(2);
- assertEquals(2, l.getCount());
- l.countDown();
- assertEquals(1, l.getCount());
- }
-
- /**
- * countDown decrements count when positive and has no effect when zero
- */
- public void testCountDown() {
- final CountDownLatch l = new CountDownLatch(1);
- assertEquals(1, l.getCount());
- l.countDown();
- assertEquals(0, l.getCount());
- l.countDown();
- assertEquals(0, l.getCount());
- }
-
- /**
- * await returns after countDown to zero, but not before
- */
- public void testAwait() throws InterruptedException {
- final CountDownLatch l = new CountDownLatch(2);
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertTrue(l.getCount() > 0);
- l.await();
- threadAssertTrue(l.getCount() == 0);
- }});
-
- t.start();
- assertEquals(l.getCount(), 2);
- Thread.sleep(SHORT_DELAY_MS);
- l.countDown();
- assertEquals(l.getCount(), 1);
- l.countDown();
- assertEquals(l.getCount(), 0);
- t.join();
- }
-
-
- /**
- * timed await returns after countDown to zero
- */
- public void testTimedAwait() throws InterruptedException {
- final CountDownLatch l = new CountDownLatch(2);
-
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertTrue(l.getCount() > 0);
- threadAssertTrue(l.await(SMALL_DELAY_MS, MILLISECONDS));
- }});
-
- t.start();
- assertEquals(l.getCount(), 2);
- Thread.sleep(SHORT_DELAY_MS);
- l.countDown();
- assertEquals(l.getCount(), 1);
- l.countDown();
- assertEquals(l.getCount(), 0);
- t.join();
- }
-
- /**
- * await throws IE if interrupted before counted down
- */
- public void testAwait_InterruptedException() throws InterruptedException {
- final CountDownLatch l = new CountDownLatch(1);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertTrue(l.getCount() > 0);
- l.await();
- }});
-
- t.start();
- assertEquals(l.getCount(), 1);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed await throws IE if interrupted before counted down
- */
- public void testTimedAwait_InterruptedException() throws InterruptedException {
- final CountDownLatch l = new CountDownLatch(1);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertTrue(l.getCount() > 0);
- l.await(MEDIUM_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(l.getCount(), 1);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed await times out if not counted down before timeout
- */
- public void testAwaitTimeout() throws InterruptedException {
- final CountDownLatch l = new CountDownLatch(1);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertTrue(l.getCount() > 0);
- threadAssertFalse(l.await(SHORT_DELAY_MS, MILLISECONDS));
- threadAssertTrue(l.getCount() > 0);
- }});
-
- t.start();
- assertEquals(l.getCount(), 1);
- t.join();
- }
-
- /**
- * toString indicates current count
- */
- public void testToString() {
- CountDownLatch s = new CountDownLatch(2);
- String us = s.toString();
- assertTrue(us.indexOf("Count = 2") >= 0);
- s.countDown();
- String s1 = s.toString();
- assertTrue(s1.indexOf("Count = 1") >= 0);
- s.countDown();
- String s2 = s.toString();
- assertTrue(s2.indexOf("Count = 0") >= 0);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java b/luni/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java
deleted file mode 100755
index b8f8b24..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.concurrent.locks.*;
-import java.util.concurrent.atomic.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-
-public class CyclicBarrierTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(CyclicBarrierTest.class);
- }
-
- private volatile int countAction;
- private class MyAction implements Runnable {
- public void run() { ++countAction; }
- }
-
- /**
- * Creating with negative parties throws IAE
- */
- public void testConstructor1() {
- try {
- new CyclicBarrier(-1, (Runnable)null);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Creating with negative parties and no action throws IAE
- */
- public void testConstructor2() {
- try {
- new CyclicBarrier(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getParties returns the number of parties given in constructor
- */
- public void testGetParties() {
- CyclicBarrier b = new CyclicBarrier(2);
- assertEquals(2, b.getParties());
- assertEquals(0, b.getNumberWaiting());
- }
-
- /**
- * A 1-party barrier triggers after single await
- */
- public void testSingleParty() throws Exception {
- CyclicBarrier b = new CyclicBarrier(1);
- assertEquals(1, b.getParties());
- assertEquals(0, b.getNumberWaiting());
- b.await();
- b.await();
- assertEquals(0, b.getNumberWaiting());
- }
-
- /**
- * The supplied barrier action is run at barrier
- */
- public void testBarrierAction() throws Exception {
- countAction = 0;
- CyclicBarrier b = new CyclicBarrier(1, new MyAction());
- assertEquals(1, b.getParties());
- assertEquals(0, b.getNumberWaiting());
- b.await();
- b.await();
- assertEquals(0, b.getNumberWaiting());
- assertEquals(countAction, 2);
- }
-
- /**
- * A 2-party/thread barrier triggers after both threads invoke await
- */
- public void testTwoParties() throws Exception {
- final CyclicBarrier b = new CyclicBarrier(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- b.await();
- b.await();
- b.await();
- b.await();
- }});
-
- t.start();
- b.await();
- b.await();
- b.await();
- b.await();
- t.join();
- }
-
-
- /**
- * An interruption in one party causes others waiting in await to
- * throw BrokenBarrierException
- */
- public void testAwait1_Interrupted_BrokenBarrier() throws Exception {
- final CyclicBarrier c = new CyclicBarrier(3);
- Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws Exception {
- c.await();
- }};
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- c.await();
- }};
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- t1.interrupt();
- t1.join();
- t2.join();
- }
-
- /**
- * An interruption in one party causes others waiting in timed await to
- * throw BrokenBarrierException
- */
- public void testAwait2_Interrupted_BrokenBarrier() throws Exception {
- final CyclicBarrier c = new CyclicBarrier(3);
- Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws Exception {
- c.await(LONG_DELAY_MS, MILLISECONDS);
- }};
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- c.await(LONG_DELAY_MS, MILLISECONDS);
- }};
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- t1.interrupt();
- t1.join();
- t2.join();
- }
-
- /**
- * A timeout in timed await throws TimeoutException
- */
- public void testAwait3_TimeOutException() throws InterruptedException {
- final CyclicBarrier c = new CyclicBarrier(2);
- Thread t = new ThreadShouldThrow(TimeoutException.class) {
- public void realRun() throws Exception {
- c.await(SHORT_DELAY_MS, MILLISECONDS);
- }};
-
- t.start();
- t.join();
- }
-
- /**
- * A timeout in one party causes others waiting in timed await to
- * throw BrokenBarrierException
- */
- public void testAwait4_Timeout_BrokenBarrier() throws InterruptedException {
- final CyclicBarrier c = new CyclicBarrier(3);
- Thread t1 = new ThreadShouldThrow(TimeoutException.class) {
- public void realRun() throws Exception {
- c.await(SHORT_DELAY_MS, MILLISECONDS);
- }};
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- c.await(MEDIUM_DELAY_MS, MILLISECONDS);
- }};
-
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- }
-
- /**
- * A timeout in one party causes others waiting in await to
- * throw BrokenBarrierException
- */
- public void testAwait5_Timeout_BrokenBarrier() throws InterruptedException {
- final CyclicBarrier c = new CyclicBarrier(3);
- Thread t1 = new ThreadShouldThrow(TimeoutException.class) {
- public void realRun() throws Exception {
- c.await(SHORT_DELAY_MS, MILLISECONDS);
- }};
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- c.await();
- }};
-
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- }
-
- /**
- * A reset of an active barrier causes waiting threads to throw
- * BrokenBarrierException
- */
- public void testReset_BrokenBarrier() throws InterruptedException {
- final CyclicBarrier c = new CyclicBarrier(3);
- Thread t1 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- c.await();
- }};
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- c.await();
- }};
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- c.reset();
- t1.join();
- t2.join();
- }
-
- /**
- * A reset before threads enter barrier does not throw
- * BrokenBarrierException
- */
- public void testReset_NoBrokenBarrier() throws Exception {
- final CyclicBarrier c = new CyclicBarrier(3);
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- c.await();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- c.await();
- }});
-
- c.reset();
- t1.start();
- t2.start();
- c.await();
- t1.join();
- t2.join();
- }
-
- /**
- * All threads block while a barrier is broken.
- */
- public void testReset_Leakage() throws InterruptedException {
- final CyclicBarrier c = new CyclicBarrier(2);
- final AtomicBoolean done = new AtomicBoolean();
- Thread t = new Thread() {
- public void run() {
- while (!done.get()) {
- try {
- while (c.isBroken())
- c.reset();
-
- c.await();
- threadFail("await should not return");
- }
- catch (BrokenBarrierException e) {
- }
- catch (InterruptedException ie) {
- }
- }
- }
- };
-
- t.start();
- for (int i = 0; i < 4; i++) {
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- }
- done.set(true);
- t.interrupt();
- t.join();
- }
-
- /**
- * Reset of a non-broken barrier does not break barrier
- */
- public void testResetWithoutBreakage() throws Exception {
- final CyclicBarrier start = new CyclicBarrier(3);
- final CyclicBarrier barrier = new CyclicBarrier(3);
- for (int i = 0; i < 3; i++) {
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }});
-
- t1.start();
- t2.start();
- start.await();
- barrier.await();
- t1.join();
- t2.join();
- assertFalse(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- if (i == 1) barrier.reset();
- assertFalse(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- }
- }
-
- /**
- * Reset of a barrier after interruption reinitializes it.
- */
- public void testResetAfterInterrupt() throws Exception {
- final CyclicBarrier start = new CyclicBarrier(3);
- final CyclicBarrier barrier = new CyclicBarrier(3);
- for (int i = 0; i < 2; i++) {
- Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }};
-
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }};
-
- t1.start();
- t2.start();
- start.await();
- t1.interrupt();
- t1.join();
- t2.join();
- assertTrue(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- barrier.reset();
- assertFalse(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- }
- }
-
- /**
- * Reset of a barrier after timeout reinitializes it.
- */
- public void testResetAfterTimeout() throws Exception {
- final CyclicBarrier start = new CyclicBarrier(3);
- final CyclicBarrier barrier = new CyclicBarrier(3);
- for (int i = 0; i < 2; i++) {
- Thread t1 = new ThreadShouldThrow(TimeoutException.class) {
- public void realRun() throws Exception {
- start.await();
- barrier.await(MEDIUM_DELAY_MS, MILLISECONDS);
- }};
-
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }};
-
- t1.start();
- t2.start();
- start.await();
- t1.join();
- t2.join();
- assertTrue(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- barrier.reset();
- assertFalse(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- }
- }
-
-
- /**
- * Reset of a barrier after a failed command reinitializes it.
- */
- public void testResetAfterCommandException() throws Exception {
- final CyclicBarrier start = new CyclicBarrier(3);
- final CyclicBarrier barrier =
- new CyclicBarrier(3, new Runnable() {
- public void run() {
- throw new NullPointerException(); }});
- for (int i = 0; i < 2; i++) {
- Thread t1 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }};
-
- Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
- public void realRun() throws Exception {
- start.await();
- barrier.await();
- }};
-
- t1.start();
- t2.start();
- start.await();
- while (barrier.getNumberWaiting() < 2) { Thread.yield(); }
- try {
- barrier.await();
- shouldThrow();
- } catch (NullPointerException success) {}
- t1.join();
- t2.join();
- assertTrue(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- barrier.reset();
- assertFalse(barrier.isBroken());
- assertEquals(0, barrier.getNumberWaiting());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java
deleted file mode 100755
index 7aeceda..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java
+++ /dev/null
@@ -1,915 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.*;
-
-public class DelayQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(DelayQueueTest.class);
- }
-
- private static final int NOCAP = Integer.MAX_VALUE;
-
- /**
- * A delayed implementation for testing.
- * Most tests use Pseudodelays, where delays are all elapsed
- * (so, no blocking solely for delays) but are still ordered
- */
- static class PDelay implements Delayed {
- int pseudodelay;
- PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
- public int compareTo(PDelay y) {
- int i = pseudodelay;
- int j = y.pseudodelay;
- if (i < j) return -1;
- if (i > j) return 1;
- return 0;
- }
-
- public int compareTo(Delayed y) {
- return compareTo((PDelay)y);
- }
-
- public boolean equals(Object other) {
- return equals((PDelay)other);
- }
- public boolean equals(PDelay other) {
- return other.pseudodelay == pseudodelay;
- }
-
-
- public long getDelay(TimeUnit ignore) {
- return pseudodelay;
- }
- public int intValue() {
- return pseudodelay;
- }
-
- public String toString() {
- return String.valueOf(pseudodelay);
- }
- }
-
-
- /**
- * Delayed implementation that actually delays
- */
- static class NanoDelay implements Delayed {
- long trigger;
- NanoDelay(long i) {
- trigger = System.nanoTime() + i;
- }
- public int compareTo(NanoDelay y) {
- long i = trigger;
- long j = y.trigger;
- if (i < j) return -1;
- if (i > j) return 1;
- return 0;
- }
-
- public int compareTo(Delayed y) {
- return compareTo((NanoDelay)y);
- }
-
- public boolean equals(Object other) {
- return equals((NanoDelay)other);
- }
- public boolean equals(NanoDelay other) {
- return other.trigger == trigger;
- }
-
- public long getDelay(TimeUnit unit) {
- long n = trigger - System.nanoTime();
- return unit.convert(n, TimeUnit.NANOSECONDS);
- }
-
- public long getTriggerTime() {
- return trigger;
- }
-
- public String toString() {
- return String.valueOf(trigger);
- }
- }
-
-
- /**
- * Create a queue of given size containing consecutive
- * PDelays 0 ... n.
- */
- private DelayQueue populatedQueue(int n) {
- DelayQueue q = new DelayQueue();
- assertTrue(q.isEmpty());
- for (int i = n-1; i >= 0; i-=2)
- assertTrue(q.offer(new PDelay(i)));
- for (int i = (n & 1); i < n; i+=2)
- assertTrue(q.offer(new PDelay(i)));
- assertFalse(q.isEmpty());
- assertEquals(NOCAP, q.remainingCapacity());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * A new queue has unbounded capacity
- */
- public void testConstructor1() {
- assertEquals(NOCAP, new DelayQueue().remainingCapacity());
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- DelayQueue q = new DelayQueue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- PDelay[] ints = new PDelay[SIZE];
- DelayQueue q = new DelayQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- PDelay[] ints = new PDelay[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new PDelay(i);
- DelayQueue q = new DelayQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- PDelay[] ints = new PDelay[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new PDelay(i);
- DelayQueue q = new DelayQueue(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- DelayQueue q = new DelayQueue();
- assertTrue(q.isEmpty());
- assertEquals(NOCAP, q.remainingCapacity());
- q.add(new PDelay(1));
- assertFalse(q.isEmpty());
- q.add(new PDelay(2));
- q.remove();
- q.remove();
- assertTrue(q.isEmpty());
- }
-
- /**
- * remainingCapacity does not change when elements added or removed,
- * but size does
- */
- public void testRemainingCapacity() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(NOCAP, q.remainingCapacity());
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(NOCAP, q.remainingCapacity());
- assertEquals(i, q.size());
- q.add(new PDelay(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- DelayQueue q = new DelayQueue();
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- DelayQueue q = new DelayQueue();
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * offer non-null succeeds
- */
- public void testOffer() {
- DelayQueue q = new DelayQueue();
- assertTrue(q.offer(new PDelay(0)));
- assertTrue(q.offer(new PDelay(1)));
- }
-
- /**
- * add succeeds
- */
- public void testAdd() {
- DelayQueue q = new DelayQueue();
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- assertTrue(q.add(new PDelay(i)));
- }
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- DelayQueue q = new DelayQueue();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- DelayQueue q = populatedQueue(SIZE);
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- DelayQueue q = new DelayQueue();
- PDelay[] ints = new PDelay[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- DelayQueue q = new DelayQueue();
- PDelay[] ints = new PDelay[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new PDelay(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of successful addAll
- */
- public void testAddAll5() {
- PDelay[] empty = new PDelay[0];
- PDelay[] ints = new PDelay[SIZE];
- for (int i = SIZE-1; i >= 0; --i)
- ints[i] = new PDelay(i);
- DelayQueue q = new DelayQueue();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * put(null) throws NPE
- */
- public void testPutNull() {
- try {
- DelayQueue q = new DelayQueue();
- q.put(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully put are contained
- */
- public void testPut() {
- DelayQueue q = new DelayQueue();
- for (int i = 0; i < SIZE; ++i) {
- PDelay I = new PDelay(i);
- q.put(I);
- assertTrue(q.contains(I));
- }
- assertEquals(SIZE, q.size());
- }
-
- /**
- * put doesn't block waiting for take
- */
- public void testPutWithTake() throws InterruptedException {
- final DelayQueue q = new DelayQueue();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- q.put(new PDelay(0));
- q.put(new PDelay(0));
- q.put(new PDelay(0));
- q.put(new PDelay(0));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- q.take();
- t.interrupt();
- t.join();
- }
-
- /**
- * timed offer does not time out
- */
- public void testTimedOffer() throws InterruptedException {
- final DelayQueue q = new DelayQueue();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new PDelay(0));
- q.put(new PDelay(0));
- assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, MILLISECONDS));
- assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, MILLISECONDS));
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * take retrieves elements in priority order
- */
- public void testTake() throws InterruptedException {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.take()));
- }
- }
-
- /**
- * take blocks interruptibly when empty
- */
- public void testTakeFromEmpty() throws InterruptedException {
- final DelayQueue q = new DelayQueue();
- Thread t = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- q.take();
- }};
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * Take removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTake() throws InterruptedException {
- final DelayQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.take()));
- }
- try {
- q.take();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.poll()));
- }
- assertNull(q.poll());
- }
-
- /**
- * timed pool with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll0() throws InterruptedException {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.poll(0, MILLISECONDS)));
- }
- assertNull(q.poll(0, MILLISECONDS));
- }
-
- /**
- * timed pool with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll() throws InterruptedException {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, MILLISECONDS)));
- }
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPoll() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, MILLISECONDS)));
- }
- try {
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOffer() throws InterruptedException {
- final DelayQueue q = new DelayQueue();
- final PDelay pdelay = new PDelay(0);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(pdelay, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(pdelay, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.peek()));
- assertEquals(new PDelay(i), ((PDelay)q.poll()));
- if (q.isEmpty())
- assertNull(q.peek());
- else
- assertFalse(new PDelay(i).equals(q.peek()));
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.element()));
- q.poll();
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(new PDelay(i), ((PDelay)q.remove()));
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new PDelay(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new PDelay(i)));
- assertFalse(q.remove(new PDelay(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- DelayQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new PDelay(i)));
- q.poll();
- assertFalse(q.contains(new PDelay(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- DelayQueue q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertEquals(NOCAP, q.remainingCapacity());
- PDelay x = new PDelay(1);
- q.add(x);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(x));
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- DelayQueue q = populatedQueue(SIZE);
- DelayQueue p = new DelayQueue();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new PDelay(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- DelayQueue q = populatedQueue(SIZE);
- DelayQueue p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- DelayQueue q = populatedQueue(SIZE);
- DelayQueue p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- PDelay I = (PDelay)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() throws InterruptedException {
- DelayQueue q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.take());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() throws InterruptedException {
- DelayQueue q = populatedQueue(SIZE);
- PDelay[] ints = new PDelay[SIZE];
- ints = (PDelay[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.take());
- }
-
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- DelayQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws CCE
- */
- public void testToArray1_BadArg() {
- DelayQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- DelayQueue q = populatedQueue(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final DelayQueue q = new DelayQueue();
- q.add(new PDelay(2));
- q.add(new PDelay(1));
- q.add(new PDelay(3));
- Iterator it = q.iterator();
- it.next();
- it.remove();
- it = q.iterator();
- assertEquals(it.next(), new PDelay(2));
- assertEquals(it.next(), new PDelay(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- DelayQueue q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
- }
- }
-
- /**
- * offer transfers elements across Executor tasks
- */
- public void testPollInExecutor() {
- final DelayQueue q = new DelayQueue();
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll());
- assertTrue(null != q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- assertTrue(q.isEmpty());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SHORT_DELAY_MS);
- q.put(new PDelay(1));
- }});
-
- joinPool(executor);
- }
-
-
- /**
- * Delayed actions do not occur until their delay elapses
- */
- public void testDelay() throws InterruptedException {
- DelayQueue q = new DelayQueue();
- NanoDelay[] elements = new NanoDelay[SIZE];
- for (int i = 0; i < SIZE; ++i) {
- elements[i] = new NanoDelay(1000000000L + 1000000L * (SIZE - i));
- }
- for (int i = 0; i < SIZE; ++i) {
- q.add(elements[i]);
- }
-
- long last = 0;
- for (int i = 0; i < SIZE; ++i) {
- NanoDelay e = (NanoDelay)(q.take());
- long tt = e.getTriggerTime();
- assertTrue(tt <= System.nanoTime());
- if (i != 0)
- assertTrue(tt >= last);
- last = tt;
- }
- }
-
- /**
- * peek of a non-empty queue returns non-null even if not expired
- */
- public void testPeekDelayed() {
- DelayQueue q = new DelayQueue();
- q.add(new NanoDelay(Long.MAX_VALUE));
- assert(q.peek() != null);
- }
-
-
- /**
- * poll of a non-empty queue returns null if no expired elements.
- */
- public void testPollDelayed() {
- DelayQueue q = new DelayQueue();
- q.add(new NanoDelay(Long.MAX_VALUE));
- assertNull(q.poll());
- }
-
- /**
- * timed poll of a non-empty queue returns null if no expired elements.
- */
- public void testTimedPollDelayed() throws InterruptedException {
- DelayQueue q = new DelayQueue();
- q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * drainTo(null) throws NPE
- */
- public void testDrainToNull() {
- DelayQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this) throws IAE
- */
- public void testDrainToSelf() {
- DelayQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c) empties queue into another collection c
- */
- public void testDrainTo() {
- DelayQueue q = new DelayQueue();
- PDelay[] elems = new PDelay[SIZE];
- for (int i = 0; i < SIZE; ++i) {
- elems[i] = new PDelay(i);
- q.add(elems[i]);
- }
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), elems[i]);
- q.add(elems[0]);
- q.add(elems[1]);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(elems[0]));
- assertTrue(q.contains(elems[1]));
- l.clear();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), 2);
- for (int i = 0; i < 2; ++i)
- assertEquals(l.get(i), elems[i]);
- }
-
- /**
- * drainTo empties queue
- */
- public void testDrainToWithActivePut() throws InterruptedException {
- final DelayQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- q.put(new PDelay(SIZE+1));
- }});
-
- t.start();
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertTrue(l.size() >= SIZE);
- t.join();
- assertTrue(q.size() + l.size() >= SIZE);
- }
-
- /**
- * drainTo(null, n) throws NPE
- */
- public void testDrainToNullN() {
- DelayQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null, 0);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this, n) throws IAE
- */
- public void testDrainToSelfN() {
- DelayQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c, n) empties first max {n, size} elements of queue into c
- */
- public void testDrainToN() {
- for (int i = 0; i < SIZE + 2; ++i) {
- DelayQueue q = populatedQueue(SIZE);
- ArrayList l = new ArrayList();
- q.drainTo(l, i);
- int k = (i < SIZE)? i : SIZE;
- assertEquals(q.size(), SIZE-k);
- assertEquals(l.size(), k);
- }
- }
-
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/EntryTest.java b/luni/src/test/java/tests/api/java/util/concurrent/EntryTest.java
deleted file mode 100644
index 893fd48..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/EntryTest.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class EntryTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(EntryTest.class);
- }
-
- static final String k1 = "1";
- static final String v1 = "a";
- static final String k2 = "2";
- static final String v2 = "b";
-
-
- /**
- * A new SimpleEntry(k, v) holds k, v.
- */
- public void testConstructor1() {
- Map.Entry e = new AbstractMap.SimpleEntry(k1, v1);
- assertEquals(k1, e.getKey());
- assertEquals(v1, e.getValue());
- }
-
- /**
- * A new SimpleImmutableEntry(k, v) holds k, v.
- */
- public void testConstructor2() {
- Map.Entry s = new AbstractMap.SimpleImmutableEntry(k1, v1);
- assertEquals(k1, s.getKey());
- assertEquals(v1, s.getValue());
- }
-
-
- /**
- * A new SimpleEntry(entry(k, v)) holds k, v.
- */
- public void testConstructor3() {
- Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
- Map.Entry e = new AbstractMap.SimpleEntry(e2);
- assertEquals(k1, e.getKey());
- assertEquals(v1, e.getValue());
- }
-
- /**
- * A new SimpleImmutableEntry(entry(k, v)) holds k, v.
- */
- public void testConstructor4() {
- Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
- Map.Entry s = new AbstractMap.SimpleImmutableEntry(s2);
- assertEquals(k1, s.getKey());
- assertEquals(v1, s.getValue());
- }
-
- /**
- * Entries with same key-value pairs are equal and have same
- * hashcodes
- */
- public void testEquals() {
- Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
- Map.Entry e = new AbstractMap.SimpleEntry(e2);
- Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
- Map.Entry s = new AbstractMap.SimpleImmutableEntry(s2);
- assertEquals(e2, e);
- assertEquals(e2.hashCode(), e.hashCode());
- assertEquals(s2, s);
- assertEquals(s2.hashCode(), s.hashCode());
- assertEquals(e2, s2);
- assertEquals(e2.hashCode(), s2.hashCode());
- assertEquals(e, s);
- assertEquals(e.hashCode(), s.hashCode());
- }
-
- /**
- * Entries with different key-value pairs are not equal
- */
- public void testNotEquals() {
- Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
- Map.Entry e = new AbstractMap.SimpleEntry(k2, v1);
- assertFalse(e2.equals( e));
- e = new AbstractMap.SimpleEntry(k1, v2);
- assertFalse(e2.equals( e));
- e = new AbstractMap.SimpleEntry(k2, v2);
- assertFalse(e2.equals( e));
-
- Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
- Map.Entry s = new AbstractMap.SimpleImmutableEntry(k2, v1);
- assertFalse(s2.equals( s));
- s = new AbstractMap.SimpleImmutableEntry(k1, v2);
- assertFalse(s2.equals( s));
- s = new AbstractMap.SimpleImmutableEntry(k2, v2);
- assertFalse(s2.equals( s));
- }
-
-
- /**
- * getValue returns last setValue for SimpleEntry
- */
- public void testSetValue1() {
- Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
- Map.Entry e = new AbstractMap.SimpleEntry(e2);
- assertEquals(k1, e.getKey());
- assertEquals(v1, e.getValue());
- e.setValue(k2);
- assertEquals(k2, e.getValue());
- assertFalse(e2.equals( e));
- }
-
- /**
- * setValue for SimpleImmutableEntry throws UnsupportedOperationException
- */
- public void testsetValue2() {
- Map.Entry s2 = new AbstractMap.SimpleImmutableEntry(k1, v1);
- Map.Entry s = new AbstractMap.SimpleImmutableEntry(s2);
- assertEquals(k1, s.getKey());
- assertEquals(v1, s.getValue());
- try {
- s.setValue(k2);
- shouldThrow();
- } catch (UnsupportedOperationException success) {}
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java
deleted file mode 100755
index be1eaa3..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-
-public class ExchangerTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ExchangerTest.class);
- }
-
- /**
- * exchange exchanges objects across two threads
- */
- public void testExchange() throws InterruptedException {
- final Exchanger e = new Exchanger();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertSame(one, e.exchange(two));
- assertSame(two, e.exchange(one));
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertSame(two, e.exchange(one));
- assertSame(one, e.exchange(two));
- }});
-
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- }
-
- /**
- * timed exchange exchanges objects across two threads
- */
- public void testTimedExchange() throws InterruptedException {
- final Exchanger e = new Exchanger();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- assertSame(one, e.exchange(two, SHORT_DELAY_MS, MILLISECONDS));
- assertSame(two, e.exchange(one, SHORT_DELAY_MS, MILLISECONDS));
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- assertSame(two, e.exchange(one, SHORT_DELAY_MS, MILLISECONDS));
- assertSame(one, e.exchange(two, SHORT_DELAY_MS, MILLISECONDS));
- }});
-
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- }
-
- /**
- * interrupt during wait for exchange throws IE
- */
- public void testExchange_InterruptedException() throws InterruptedException {
- final Exchanger e = new Exchanger();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- e.exchange(one);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * interrupt during wait for timed exchange throws IE
- */
- public void testTimedExchange_InterruptedException() throws InterruptedException {
- final Exchanger e = new Exchanger();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws Exception {
- e.exchange(null, SMALL_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timeout during wait for timed exchange throws TOE
- */
- public void testExchange_TimeOutException() throws InterruptedException {
- final Exchanger e = new Exchanger();
- Thread t = new ThreadShouldThrow(TimeoutException.class) {
- public void realRun() throws Exception {
- e.exchange(null, SHORT_DELAY_MS, MILLISECONDS);
- }};
-
- t.start();
- t.join();
- }
-
- /**
- * If one exchanging thread is interrupted, another succeeds.
- */
- public void testReplacementAfterExchange() throws InterruptedException {
- final Exchanger e = new Exchanger();
- Thread t1 = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- assertSame(two, e.exchange(one));
- e.exchange(two);
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertSame(one, e.exchange(two));
- Thread.sleep(SMALL_DELAY_MS);
- assertSame(three, e.exchange(one));
- }});
- Thread t3 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- assertSame(one, e.exchange(three));
- }});
-
- t1.start();
- t2.start();
- t3.start();
- Thread.sleep(SHORT_DELAY_MS);
- t1.interrupt();
- t1.join();
- t2.join();
- t3.join();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java
deleted file mode 100644
index dfa8f7d..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.atomic.*;
-import java.math.BigInteger;
-import java.security.*;
-
-public class ExecutorCompletionServiceTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ExecutorCompletionServiceTest.class);
- }
-
-
- /**
- * Creating a new ECS with null Executor throw NPE
- */
- public void testConstructorNPE() {
- try {
- ExecutorCompletionService ecs = new ExecutorCompletionService(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Creating a new ECS with null queue throw NPE
- */
- public void testConstructorNPE2() {
- try {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e, null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Submitting a null callable throws NPE
- */
- public void testSubmitNPE() {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e);
- try {
- Callable c = null;
- ecs.submit(c);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * Submitting a null runnable throws NPE
- */
- public void testSubmitNPE2() {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e);
- try {
- Runnable r = null;
- ecs.submit(r, Boolean.TRUE);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * A taken submitted task is completed
- */
- public void testTake() throws InterruptedException {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e);
- try {
- Callable c = new StringTask();
- ecs.submit(c);
- Future f = ecs.take();
- assertTrue(f.isDone());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * Take returns the same future object returned by submit
- */
- public void testTake2() throws InterruptedException {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e);
- try {
- Callable c = new StringTask();
- Future f1 = ecs.submit(c);
- Future f2 = ecs.take();
- assertSame(f1, f2);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * If poll returns non-null, the returned task is completed
- */
- public void testPoll1() throws InterruptedException {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e);
- try {
- assertNull(ecs.poll());
- Callable c = new StringTask();
- ecs.submit(c);
- Thread.sleep(SHORT_DELAY_MS);
- for (;;) {
- Future f = ecs.poll();
- if (f != null) {
- assertTrue(f.isDone());
- break;
- }
- }
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * If timed poll returns non-null, the returned task is completed
- */
- public void testPoll2() throws InterruptedException {
- ExecutorService e = Executors.newCachedThreadPool();
- ExecutorCompletionService ecs = new ExecutorCompletionService(e);
- try {
- assertNull(ecs.poll());
- Callable c = new StringTask();
- ecs.submit(c);
- Future f = ecs.poll(SHORT_DELAY_MS, MILLISECONDS);
- if (f != null)
- assertTrue(f.isDone());
- } finally {
- joinPool(e);
- }
- }
- /**
- * Submitting to underlying AES that overrides newTaskFor(Callable)
- * returns and eventually runs Future returned by newTaskFor.
- */
- public void testNewTaskForCallable() throws InterruptedException {
- final AtomicBoolean done = new AtomicBoolean(false);
- class MyCallableFuture<V> extends FutureTask<V> {
- MyCallableFuture(Callable<V> c) { super(c); }
- protected void done() { done.set(true); }
- }
- ExecutorService e = new ThreadPoolExecutor(
- 1, 1, 30L, TimeUnit.SECONDS,
- new ArrayBlockingQueue<Runnable>(1)) {
- protected <T> RunnableFuture<T> newTaskFor(Callable<T> c) {
- return new MyCallableFuture<T>(c);
- }
- };
- ExecutorCompletionService<String> ecs =
- new ExecutorCompletionService<String>(e);
- try {
- assertNull(ecs.poll());
- Callable<String> c = new StringTask();
- Future f1 = ecs.submit(c);
- assertTrue("submit must return MyCallableFuture",
- f1 instanceof MyCallableFuture);
- Future f2 = ecs.take();
- assertSame("submit and take must return same objects", f1, f2);
- assertTrue("completed task must have set done", done.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * Submitting to underlying AES that overrides newTaskFor(Runnable,T)
- * returns and eventually runs Future returned by newTaskFor.
- */
- public void testNewTaskForRunnable() throws InterruptedException {
- final AtomicBoolean done = new AtomicBoolean(false);
- class MyRunnableFuture<V> extends FutureTask<V> {
- MyRunnableFuture(Runnable t, V r) { super(t, r); }
- protected void done() { done.set(true); }
- }
- ExecutorService e = new ThreadPoolExecutor(
- 1, 1, 30L, TimeUnit.SECONDS,
- new ArrayBlockingQueue<Runnable>(1)) {
- protected <T> RunnableFuture<T> newTaskFor(Runnable t, T r) {
- return new MyRunnableFuture<T>(t, r);
- }
- };
- ExecutorCompletionService<String> ecs =
- new ExecutorCompletionService<String>(e);
- try {
- assertNull(ecs.poll());
- Runnable r = new NoOpRunnable();
- Future f1 = ecs.submit(r, null);
- assertTrue("submit must return MyRunnableFuture",
- f1 instanceof MyRunnableFuture);
- Future f2 = ecs.take();
- assertSame("submit and take must return same objects", f1, f2);
- assertTrue("completed task must have set done", done.get());
- } finally {
- joinPool(e);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java
deleted file mode 100755
index f29a712..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java
+++ /dev/null
@@ -1,556 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.math.BigInteger;
-import java.security.*;
-
-public class ExecutorsTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ExecutorsTest.class);
- }
-
- /**
- * A newCachedThreadPool can execute runnables
- */
- public void testNewCachedThreadPool1() {
- ExecutorService e = Executors.newCachedThreadPool();
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * A newCachedThreadPool with given ThreadFactory can execute runnables
- */
- public void testNewCachedThreadPool2() {
- ExecutorService e = Executors.newCachedThreadPool(new SimpleThreadFactory());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * A newCachedThreadPool with null ThreadFactory throws NPE
- */
- public void testNewCachedThreadPool3() {
- try {
- ExecutorService e = Executors.newCachedThreadPool(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * A new SingleThreadExecutor can execute runnables
- */
- public void testNewSingleThreadExecutor1() {
- ExecutorService e = Executors.newSingleThreadExecutor();
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * A new SingleThreadExecutor with given ThreadFactory can execute runnables
- */
- public void testNewSingleThreadExecutor2() {
- ExecutorService e = Executors.newSingleThreadExecutor(new SimpleThreadFactory());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * A new SingleThreadExecutor with null ThreadFactory throws NPE
- */
- public void testNewSingleThreadExecutor3() {
- try {
- ExecutorService e = Executors.newSingleThreadExecutor(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * A new SingleThreadExecutor cannot be casted to concrete implementation
- */
- public void testCastNewSingleThreadExecutor() {
- ExecutorService e = Executors.newSingleThreadExecutor();
- try {
- ThreadPoolExecutor tpe = (ThreadPoolExecutor)e;
- shouldThrow();
- } catch (ClassCastException success) {
- } finally {
- joinPool(e);
- }
- }
-
-
- /**
- * A new newFixedThreadPool can execute runnables
- */
- public void testNewFixedThreadPool1() {
- ExecutorService e = Executors.newFixedThreadPool(2);
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * A new newFixedThreadPool with given ThreadFactory can execute runnables
- */
- public void testNewFixedThreadPool2() {
- ExecutorService e = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * A new newFixedThreadPool with null ThreadFactory throws NPE
- */
- public void testNewFixedThreadPool3() {
- try {
- ExecutorService e = Executors.newFixedThreadPool(2, null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * A new newFixedThreadPool with 0 threads throws IAE
- */
- public void testNewFixedThreadPool4() {
- try {
- ExecutorService e = Executors.newFixedThreadPool(0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
-
- /**
- * An unconfigurable newFixedThreadPool can execute runnables
- */
- public void testunconfigurableExecutorService() {
- ExecutorService e = Executors.unconfigurableExecutorService(Executors.newFixedThreadPool(2));
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- e.execute(new NoOpRunnable());
- joinPool(e);
- }
-
- /**
- * unconfigurableExecutorService(null) throws NPE
- */
- public void testunconfigurableExecutorServiceNPE() {
- try {
- ExecutorService e = Executors.unconfigurableExecutorService(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * unconfigurableScheduledExecutorService(null) throws NPE
- */
- public void testunconfigurableScheduledExecutorServiceNPE() {
- try {
- ExecutorService e = Executors.unconfigurableScheduledExecutorService(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * a newSingleThreadScheduledExecutor successfully runs delayed task
- */
- public void testNewSingleThreadScheduledExecutor() throws Exception {
- TrackedCallable callable = new TrackedCallable();
- ScheduledExecutorService p1 = Executors.newSingleThreadScheduledExecutor();
- Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(callable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(callable.done);
- assertEquals(Boolean.TRUE, f.get());
- joinPool(p1);
- }
-
- /**
- * a newScheduledThreadPool successfully runs delayed task
- */
- public void testnewScheduledThreadPool() throws Exception {
- TrackedCallable callable = new TrackedCallable();
- ScheduledExecutorService p1 = Executors.newScheduledThreadPool(2);
- Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(callable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(callable.done);
- assertEquals(Boolean.TRUE, f.get());
- joinPool(p1);
- }
-
- /**
- * an unconfigurable newScheduledThreadPool successfully runs delayed task
- */
- public void testunconfigurableScheduledExecutorService() throws Exception {
- TrackedCallable callable = new TrackedCallable();
- ScheduledExecutorService p1 = Executors.unconfigurableScheduledExecutorService(Executors.newScheduledThreadPool(2));
- Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(callable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(callable.done);
- assertEquals(Boolean.TRUE, f.get());
- joinPool(p1);
- }
-
- /**
- * Future.get on submitted tasks will time out if they compute too long.
- */
- public void testTimedCallable() throws Exception {
- final Runnable sleeper =
- new RunnableShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- Thread.sleep(LONG_DELAY_MS);
- }};
- for (ExecutorService executor :
- new ExecutorService[] {
- Executors.newSingleThreadExecutor(),
- Executors.newCachedThreadPool(),
- Executors.newFixedThreadPool(2),
- Executors.newScheduledThreadPool(2),
- }) {
- try {
- Future future = executor.submit(sleeper);
- try {
- future.get(SHORT_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (TimeoutException success) {
- } finally {
- future.cancel(true);
- }
- }
- finally {
- joinPool(executor);
- }
- }
- }
-
-
- /**
- * ThreadPoolExecutor using defaultThreadFactory has
- * specified group, priority, daemon status, and name
- */
- public void testDefaultThreadFactory() throws Exception {
- final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
- Runnable r = new Runnable() {
- public void run() {
- try {
- Thread current = Thread.currentThread();
- threadAssertTrue(!current.isDaemon());
- threadAssertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
- ThreadGroup g = current.getThreadGroup();
- SecurityManager s = System.getSecurityManager();
- if (s != null)
- threadAssertTrue(g == s.getThreadGroup());
- else
- threadAssertTrue(g == egroup);
- String name = current.getName();
- threadAssertTrue(name.endsWith("thread-1"));
- } catch (SecurityException ok) {
- // Also pass if not allowed to change setting
- }
- }
- };
- ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
-
- e.execute(r);
- try {
- e.shutdown();
- } catch (SecurityException ok) {
- }
-
- try {
- Thread.sleep(SHORT_DELAY_MS);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * ThreadPoolExecutor using privilegedThreadFactory has
- * specified group, priority, daemon status, name,
- * access control context and context class loader
- */
- public void testPrivilegedThreadFactory() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
- final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
- final AccessControlContext thisacc = AccessController.getContext();
- Runnable r = new CheckedRunnable() {
- public void realRun() {
- Thread current = Thread.currentThread();
- assertTrue(!current.isDaemon());
- assertTrue(current.getPriority() <= Thread.NORM_PRIORITY);
- ThreadGroup g = current.getThreadGroup();
- SecurityManager s = System.getSecurityManager();
- if (s != null)
- assertTrue(g == s.getThreadGroup());
- else
- assertTrue(g == egroup);
- String name = current.getName();
- assertTrue(name.endsWith("thread-1"));
- assertTrue(thisccl == current.getContextClassLoader());
- assertTrue(thisacc.equals(AccessController.getContext()));
- }};
- ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
- e.execute(r);
- e.shutdown();
- Thread.sleep(SHORT_DELAY_MS);
- joinPool(e);
- }};
-
- runWithPermissions(r,
- new RuntimePermission("getClassLoader"),
- new RuntimePermission("setContextClassLoader"),
- new RuntimePermission("modifyThread"));
- }
-
- boolean haveCCLPermissions() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- try {
- sm.checkPermission(new RuntimePermission("setContextClassLoader"));
- sm.checkPermission(new RuntimePermission("getClassLoader"));
- } catch (AccessControlException e) {
- return false;
- }
- }
- return true;
- }
-
- void checkCCL() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("setContextClassLoader"));
- sm.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
- class CheckCCL implements Callable<Object> {
- public Object call() {
- checkCCL();
- return null;
- }
- }
-
-
- /**
- * Without class loader permissions, creating
- * privilegedCallableUsingCurrentClassLoader throws ACE
- */
- public void testCreatePrivilegedCallableUsingCCLWithNoPrivs() {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- if (System.getSecurityManager() == null)
- return;
- try {
- Executors.privilegedCallableUsingCurrentClassLoader(new NoOpCallable());
- shouldThrow();
- } catch (AccessControlException success) {}
- }};
-
- runWithoutPermissions(r);
- }
-
- /**
- * With class loader permissions, calling
- * privilegedCallableUsingCurrentClassLoader does not throw ACE
- */
- public void testprivilegedCallableUsingCCLWithPrivs() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- Executors.privilegedCallableUsingCurrentClassLoader
- (new NoOpCallable())
- .call();
- }};
-
- runWithPermissions(r,
- new RuntimePermission("getClassLoader"),
- new RuntimePermission("setContextClassLoader"));
- }
-
- /**
- * Without permissions, calling privilegedCallable throws ACE
- */
- public void testprivilegedCallableWithNoPrivs() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- if (System.getSecurityManager() == null)
- return;
- Callable task = Executors.privilegedCallable(new CheckCCL());
- try {
- task.call();
- shouldThrow();
- } catch (AccessControlException success) {}
- }};
-
- runWithoutPermissions(r);
-
- // It seems rather difficult to test that the
- // AccessControlContext of the privilegedCallable is used
- // instead of its caller. Below is a failed attempt to do
- // that, which does not work because the AccessController
- // cannot capture the internal state of the current Policy.
- // It would be much more work to differentiate based on,
- // e.g. CodeSource.
-
-// final AccessControlContext[] noprivAcc = new AccessControlContext[1];
-// final Callable[] task = new Callable[1];
-
-// runWithPermissions
-// (new CheckedRunnable() {
-// public void realRun() {
-// if (System.getSecurityManager() == null)
-// return;
-// noprivAcc[0] = AccessController.getContext();
-// task[0] = Executors.privilegedCallable(new CheckCCL());
-// try {
-// AccessController.doPrivileged(new PrivilegedAction<Void>() {
-// public Void run() {
-// checkCCL();
-// return null;
-// }}, noprivAcc[0]);
-// shouldThrow();
-// } catch (AccessControlException success) {}
-// }});
-
-// runWithPermissions
-// (new CheckedRunnable() {
-// public void realRun() throws Exception {
-// if (System.getSecurityManager() == null)
-// return;
-// // Verify that we have an underprivileged ACC
-// try {
-// AccessController.doPrivileged(new PrivilegedAction<Void>() {
-// public Void run() {
-// checkCCL();
-// return null;
-// }}, noprivAcc[0]);
-// shouldThrow();
-// } catch (AccessControlException success) {}
-
-// try {
-// task[0].call();
-// shouldThrow();
-// } catch (AccessControlException success) {}
-// }},
-// new RuntimePermission("getClassLoader"),
-// new RuntimePermission("setContextClassLoader"));
- }
-
- /**
- * With permissions, calling privilegedCallable succeeds
- */
- public void testprivilegedCallableWithPrivs() throws Exception {
- Runnable r = new CheckedRunnable() {
- public void realRun() throws Exception {
- Executors.privilegedCallable(new CheckCCL()).call();
- }};
-
- runWithPermissions(r,
- new RuntimePermission("getClassLoader"),
- new RuntimePermission("setContextClassLoader"));
- }
-
- /**
- * callable(Runnable) returns null when called
- */
- public void testCallable1() throws Exception {
- Callable c = Executors.callable(new NoOpRunnable());
- assertNull(c.call());
- }
-
- /**
- * callable(Runnable, result) returns result when called
- */
- public void testCallable2() throws Exception {
- Callable c = Executors.callable(new NoOpRunnable(), one);
- assertSame(one, c.call());
- }
-
- /**
- * callable(PrivilegedAction) returns its result when called
- */
- public void testCallable3() throws Exception {
- Callable c = Executors.callable(new PrivilegedAction() {
- public Object run() { return one; }});
- assertSame(one, c.call());
- }
-
- /**
- * callable(PrivilegedExceptionAction) returns its result when called
- */
- public void testCallable4() throws Exception {
- Callable c = Executors.callable(new PrivilegedExceptionAction() {
- public Object run() { return one; }});
- assertSame(one, c.call());
- }
-
-
- /**
- * callable(null Runnable) throws NPE
- */
- public void testCallableNPE1() {
- try {
- Callable c = Executors.callable((Runnable) null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * callable(null, result) throws NPE
- */
- public void testCallableNPE2() {
- try {
- Callable c = Executors.callable((Runnable) null, one);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * callable(null PrivilegedAction) throws NPE
- */
- public void testCallableNPE3() {
- try {
- Callable c = Executors.callable((PrivilegedAction) null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * callable(null PrivilegedExceptionAction) throws NPE
- */
- public void testCallableNPE4() {
- try {
- Callable c = Executors.callable((PrivilegedExceptionAction) null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java b/luni/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java
deleted file mode 100755
index b1f9f40..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.*;
-
-public class FutureTaskTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(FutureTaskTest.class);
- }
-
- /**
- * Subclass to expose protected methods
- */
- static class PublicFutureTask extends FutureTask {
- public PublicFutureTask(Callable r) { super(r); }
- public boolean runAndReset() { return super.runAndReset(); }
- public void set(Object x) { super.set(x); }
- public void setException(Throwable t) { super.setException(t); }
- }
-
- /**
- * Creating a future with a null callable throws NPE
- */
- public void testConstructor() {
- try {
- FutureTask task = new FutureTask(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * creating a future with null runnable fails
- */
- public void testConstructor2() {
- try {
- FutureTask task = new FutureTask(null, Boolean.TRUE);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * isDone is true when a task completes
- */
- public void testIsDone() {
- FutureTask task = new FutureTask(new NoOpCallable());
- task.run();
- assertTrue(task.isDone());
- assertFalse(task.isCancelled());
- }
-
- /**
- * runAndReset of a non-cancelled task succeeds
- */
- public void testRunAndReset() {
- PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
- assertTrue(task.runAndReset());
- assertFalse(task.isDone());
- }
-
- /**
- * runAndReset after cancellation fails
- */
- public void testResetAfterCancel() {
- PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
- assertTrue(task.cancel(false));
- assertFalse(task.runAndReset());
- assertTrue(task.isDone());
- assertTrue(task.isCancelled());
- }
-
-
-
- /**
- * setting value causes get to return it
- */
- public void testSet() throws Exception {
- PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
- task.set(one);
- assertSame(task.get(), one);
- }
-
- /**
- * setException causes get to throw ExecutionException
- */
- public void testSetException() throws Exception {
- Exception nse = new NoSuchElementException();
- PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
- task.setException(nse);
- try {
- Object x = task.get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertSame(success.getCause(), nse);
- }
- }
-
- /**
- * Cancelling before running succeeds
- */
- public void testCancelBeforeRun() {
- FutureTask task = new FutureTask(new NoOpCallable());
- assertTrue(task.cancel(false));
- task.run();
- assertTrue(task.isDone());
- assertTrue(task.isCancelled());
- }
-
- /**
- * Cancel(true) before run succeeds
- */
- public void testCancelBeforeRun2() {
- FutureTask task = new FutureTask(new NoOpCallable());
- assertTrue(task.cancel(true));
- task.run();
- assertTrue(task.isDone());
- assertTrue(task.isCancelled());
- }
-
- /**
- * cancel of a completed task fails
- */
- public void testCancelAfterRun() {
- FutureTask task = new FutureTask(new NoOpCallable());
- task.run();
- assertFalse(task.cancel(false));
- assertTrue(task.isDone());
- assertFalse(task.isCancelled());
- }
-
- /**
- * cancel(true) interrupts a running task
- */
- public void testCancelInterrupt() throws InterruptedException {
- final FutureTask task =
- new FutureTask(new CheckedInterruptedCallable<Object>() {
- public Object realCall() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- return Boolean.TRUE;
- }});
-
- Thread t = new Thread(task);
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(task.cancel(true));
- t.join();
- assertTrue(task.isDone());
- assertTrue(task.isCancelled());
- }
-
-
- /**
- * cancel(false) does not interrupt a running task
- */
- public void testCancelNoInterrupt() throws InterruptedException {
- final FutureTask task =
- new FutureTask(new CheckedCallable<Object>() {
- public Object realCall() throws InterruptedException {
- Thread.sleep(MEDIUM_DELAY_MS);
- return Boolean.TRUE;
- }});
-
- Thread t = new Thread(task);
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(task.cancel(false));
- t.join();
- assertTrue(task.isDone());
- assertTrue(task.isCancelled());
- }
-
- /**
- * set in one thread causes get in another thread to retrieve value
- */
- public void testGet1() throws InterruptedException {
- final FutureTask ft =
- new FutureTask(new CheckedCallable<Object>() {
- public Object realCall() throws InterruptedException {
- return Boolean.TRUE;
- }});
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- assertSame(Boolean.TRUE, ft.get());
- }});
-
- assertFalse(ft.isDone());
- assertFalse(ft.isCancelled());
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- ft.run();
- t.join();
- assertTrue(ft.isDone());
- assertFalse(ft.isCancelled());
- }
-
- /**
- * set in one thread causes timed get in another thread to retrieve value
- */
- public void testTimedGet1() throws InterruptedException {
- final FutureTask ft =
- new FutureTask(new CheckedCallable<Object>() {
- public Object realCall() throws InterruptedException {
- return Boolean.TRUE;
- }});
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws Exception {
- assertSame(Boolean.TRUE, ft.get(SMALL_DELAY_MS, MILLISECONDS));
- }});
-
- assertFalse(ft.isDone());
- assertFalse(ft.isCancelled());
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- ft.run();
- t.join();
- assertTrue(ft.isDone());
- assertFalse(ft.isCancelled());
- }
-
- /**
- * Cancelling a task causes timed get in another thread to throw CancellationException
- */
- public void testTimedGet_Cancellation() throws InterruptedException {
- final FutureTask ft =
- new FutureTask(new CheckedInterruptedCallable<Object>() {
- public Object realCall() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- return Boolean.TRUE;
- }});
-
- Thread t1 = new ThreadShouldThrow(CancellationException.class) {
- public void realRun() throws Exception {
- ft.get(MEDIUM_DELAY_MS, MILLISECONDS);
- }};
- Thread t2 = new Thread(ft);
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- ft.cancel(true);
- t1.join();
- t2.join();
- }
-
- /**
- * Cancelling a task causes get in another thread to throw CancellationException
- */
- public void testGet_Cancellation() throws InterruptedException {
- final FutureTask ft =
- new FutureTask(new CheckedInterruptedCallable<Object>() {
- public Object realCall() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- return Boolean.TRUE;
- }});
- Thread t1 = new ThreadShouldThrow(CancellationException.class) {
- public void realRun() throws Exception {
- ft.get();
- }};
-
- Thread t2 = new Thread(ft);
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- ft.cancel(true);
- t1.join();
- t2.join();
- }
-
-
- /**
- * A runtime exception in task causes get to throw ExecutionException
- */
- public void testGet_ExecutionException() throws InterruptedException {
- final FutureTask ft = new FutureTask(new Callable() {
- public Object call() {
- return 5/0;
- }});
-
- ft.run();
- try {
- ft.get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof ArithmeticException);
- }
- }
-
- /**
- * A runtime exception in task causes timed get to throw ExecutionException
- */
- public void testTimedGet_ExecutionException2() throws Exception {
- final FutureTask ft = new FutureTask(new Callable() {
- public Object call() {
- return 5/0;
- }});
-
- ft.run();
- try {
- ft.get(SHORT_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof ArithmeticException);
- }
- }
-
-
- /**
- * Interrupting a waiting get causes it to throw InterruptedException
- */
- public void testGet_InterruptedException() throws InterruptedException {
- final FutureTask ft = new FutureTask(new NoOpCallable());
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws Exception {
- ft.get();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * Interrupting a waiting timed get causes it to throw InterruptedException
- */
- public void testTimedGet_InterruptedException2() throws InterruptedException {
- final FutureTask ft = new FutureTask(new NoOpCallable());
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws Exception {
- ft.get(LONG_DELAY_MS,MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * A timed out timed get throws TimeoutException
- */
- public void testGet_TimeoutException() throws Exception {
- try {
- FutureTask ft = new FutureTask(new NoOpCallable());
- ft.get(1,MILLISECONDS);
- shouldThrow();
- } catch (TimeoutException success) {}
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java b/luni/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java
deleted file mode 100644
index b764855..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java
+++ /dev/null
@@ -1,761 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-import java.security.*;
-
-/**
- * Base class for JSR166 Junit TCK tests. Defines some constants,
- * utility methods and classes, as well as a simple framework for
- * helping to make sure that assertions failing in generated threads
- * cause the associated test that generated them to itself fail (which
- * JUnit does not otherwise arrange). The rules for creating such
- * tests are:
- *
- * <ol>
- *
- * <li> All assertions in code running in generated threads must use
- * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
- * #threadAssertEquals}, or {@link #threadAssertNull}, (not
- * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
- * particularly recommended) for other code to use these forms too.
- * Only the most typically used JUnit assertion methods are defined
- * this way, but enough to live with.</li>
- *
- * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
- * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
- * them. These methods are used to clear and check for thread
- * assertion failures.</li>
- *
- * <li>All delays and timeouts must use one of the constants <tt>
- * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
- * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
- * discriminable from zero time, and always allows enough time for the
- * small amounts of computation (creating a thread, calling a few
- * methods, etc) needed to reach a timeout point. Similarly, a SMALL
- * is always discriminable as larger than SHORT and smaller than
- * MEDIUM. And so on. These constants are set to conservative values,
- * but even so, if there is ever any doubt, they can all be increased
- * in one spot to rerun tests on slower platforms.</li>
- *
- * <li> All threads generated must be joined inside each test case
- * method (or <tt>fail</tt> to do so) before returning from the
- * method. The <tt> joinPool</tt> method can be used to do this when
- * using Executors.</li>
- *
- * </ol>
- *
- * <p> <b>Other notes</b>
- * <ul>
- *
- * <li> Usually, there is one testcase method per JSR166 method
- * covering "normal" operation, and then as many exception-testing
- * methods as there are exceptions the method can throw. Sometimes
- * there are multiple tests per JSR166 method when the different
- * "normal" behaviors differ significantly. And sometimes testcases
- * cover multiple methods when they cannot be tested in
- * isolation.</li>
- *
- * <li> The documentation style for testcases is to provide as javadoc
- * a simple sentence or two describing the property that the testcase
- * method purports to test. The javadocs do not say anything about how
- * the property is tested. To find out, read the code.</li>
- *
- * <li> These tests are "conformance tests", and do not attempt to
- * test throughput, latency, scalability or other performance factors
- * (see the separate "jtreg" tests for a set intended to check these
- * for the most central aspects of functionality.) So, most tests use
- * the smallest sensible numbers of threads, collection sizes, etc
- * needed to check basic conformance.</li>
- *
- * <li>The test classes currently do not declare inclusion in
- * any particular package to simplify things for people integrating
- * them in TCK test suites.</li>
- *
- * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
- * runs all JSR166 unit tests.</li>
- *
- * </ul>
- */
-public class JSR166TestCase extends TestCase {
- private static final boolean useSecurityManager =
- Boolean.getBoolean("jsr166.useSecurityManager");
-
- // BEGIN android-removed
- // /**
- // * Runs all JSR166 unit tests using junit.textui.TestRunner
- // */
- // public static void main(String[] args) {
- // if (useSecurityManager) {
- // System.err.println("Setting a permissive security manager");
- // Policy.setPolicy(permissivePolicy());
- // System.setSecurityManager(new SecurityManager());
- // }
- // int iters = 1;
- // if (args.length > 0)
- // iters = Integer.parseInt(args[0]);
- // Test s = suite();
- // for (int i = 0; i < iters; ++i) {
- // junit.textui.TestRunner.run(s);
- // System.gc();
- // System.runFinalization();
- // }
- // System.exit(0);
- // }
- // END android-removed
-
- /**
- * Collects all JSR166 unit tests as one suite
- */
- public static Test suite() {
- TestSuite suite = new TestSuite("JSR166 Unit Tests");
-
- suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
- suite.addTest(new TestSuite(AbstractQueueTest.class));
- suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
- suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
- suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
- suite.addTest(new TestSuite(ArrayDequeTest.class));
- suite.addTest(new TestSuite(AtomicBooleanTest.class));
- suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
- suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
- suite.addTest(new TestSuite(AtomicIntegerTest.class));
- suite.addTest(new TestSuite(AtomicLongArrayTest.class));
- suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
- suite.addTest(new TestSuite(AtomicLongTest.class));
- suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
- suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
- suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
- suite.addTest(new TestSuite(AtomicReferenceTest.class));
- suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
- suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
- suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
- suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
- suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
- suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
- suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
- suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
- suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
- suite.addTest(new TestSuite(CountDownLatchTest.class));
- suite.addTest(new TestSuite(CyclicBarrierTest.class));
- suite.addTest(new TestSuite(DelayQueueTest.class));
- suite.addTest(new TestSuite(EntryTest.class));
- suite.addTest(new TestSuite(ExchangerTest.class));
- suite.addTest(new TestSuite(ExecutorsTest.class));
- suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
- suite.addTest(new TestSuite(FutureTaskTest.class));
- suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
- suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
- suite.addTest(new TestSuite(LinkedListTest.class));
- suite.addTest(new TestSuite(LockSupportTest.class));
- suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
- suite.addTest(new TestSuite(PriorityQueueTest.class));
- suite.addTest(new TestSuite(ReentrantLockTest.class));
- suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
- suite.addTest(new TestSuite(ScheduledExecutorTest.class));
- suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
- suite.addTest(new TestSuite(SemaphoreTest.class));
- suite.addTest(new TestSuite(SynchronousQueueTest.class));
- suite.addTest(new TestSuite(SystemTest.class));
- suite.addTest(new TestSuite(ThreadLocalTest.class));
- suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
- suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
- suite.addTest(new TestSuite(ThreadTest.class));
- suite.addTest(new TestSuite(TimeUnitTest.class));
-
- return suite;
- }
-
-
- public static long SHORT_DELAY_MS;
- public static long SMALL_DELAY_MS;
- public static long MEDIUM_DELAY_MS;
- public static long LONG_DELAY_MS;
-
-
- /**
- * Returns the shortest timed delay. This could
- * be reimplemented to use for example a Property.
- */
- protected long getShortDelay() {
- // BEGIN android-changed
- // original value is 50
- return 250;
- // END android-changed
- }
-
-
- /**
- * Sets delays as multiples of SHORT_DELAY.
- */
- protected void setDelays() {
- SHORT_DELAY_MS = getShortDelay();
- SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
- MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
- LONG_DELAY_MS = SHORT_DELAY_MS * 50;
- }
-
- /**
- * Flag set true if any threadAssert methods fail
- */
- volatile boolean threadFailed;
-
- /**
- * Initializes test to indicate that no thread assertions have failed
- */
- public void setUp() {
- setDelays();
- threadFailed = false;
- }
-
- /**
- * Triggers test case failure if any thread assertions have failed
- */
- public void tearDown() {
- assertFalse(threadFailed);
- }
-
- /**
- * Fail, also setting status to indicate current testcase should fail
- */
- public void threadFail(String reason) {
- threadFailed = true;
- fail(reason);
- }
-
- /**
- * If expression not true, set status to indicate current testcase
- * should fail
- */
- public void threadAssertTrue(boolean b) {
- if (!b) {
- threadFailed = true;
- assertTrue(b);
- }
- }
-
- /**
- * If expression not false, set status to indicate current testcase
- * should fail
- */
- public void threadAssertFalse(boolean b) {
- if (b) {
- threadFailed = true;
- assertFalse(b);
- }
- }
-
- /**
- * If argument not null, set status to indicate current testcase
- * should fail
- */
- public void threadAssertNull(Object x) {
- if (x != null) {
- threadFailed = true;
- assertNull(x);
- }
- }
-
- /**
- * If arguments not equal, set status to indicate current testcase
- * should fail
- */
- public void threadAssertEquals(long x, long y) {
- if (x != y) {
- threadFailed = true;
- assertEquals(x, y);
- }
- }
-
- /**
- * If arguments not equal, set status to indicate current testcase
- * should fail
- */
- public void threadAssertEquals(Object x, Object y) {
- if (x != y && (x == null || !x.equals(y))) {
- threadFailed = true;
- assertEquals(x, y);
- }
- }
-
- /**
- * threadFail with message "should throw exception"
- */
- public void threadShouldThrow() {
- threadFailed = true;
- fail("should throw exception");
- }
-
- /**
- * threadFail with message "should throw" + exceptionName
- */
- public void threadShouldThrow(String exceptionName) {
- threadFailed = true;
- fail("should throw " + exceptionName);
- }
-
- /**
- * threadFail with message "Unexpected exception"
- */
- public void threadUnexpectedException() {
- threadFailed = true;
- fail("Unexpected exception");
- }
-
- /**
- * threadFail with message "Unexpected exception", with argument
- */
- public void threadUnexpectedException(Throwable ex) {
- threadFailed = true;
- ex.printStackTrace();
- fail("Unexpected exception: " + ex);
- }
-
- /**
- * Wait out termination of a thread pool or fail doing so
- */
- public void joinPool(ExecutorService exec) {
- try {
- exec.shutdown();
- assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- } catch (SecurityException ok) {
- // Allowed in case test doesn't have privs
- } catch (InterruptedException ie) {
- fail("Unexpected InterruptedException");
- }
- }
-
-
- /**
- * fail with message "should throw exception"
- */
- public void shouldThrow() {
- fail("Should throw exception");
- }
-
- /**
- * fail with message "should throw " + exceptionName
- */
- public void shouldThrow(String exceptionName) {
- fail("Should throw " + exceptionName);
- }
-
- /**
- * fail with message "Unexpected exception"
- */
- public void unexpectedException() {
- fail("Unexpected exception");
- }
-
- /**
- * fail with message "Unexpected exception", with argument
- */
- public void unexpectedException(Throwable ex) {
- ex.printStackTrace();
- fail("Unexpected exception: " + ex);
- }
-
-
- /**
- * The number of elements to place in collections, arrays, etc.
- */
- public static final int SIZE = 20;
-
- // Some convenient Integer constants
-
- public static final Integer zero = new Integer(0);
- public static final Integer one = new Integer(1);
- public static final Integer two = new Integer(2);
- public static final Integer three = new Integer(3);
- public static final Integer four = new Integer(4);
- public static final Integer five = new Integer(5);
- public static final Integer six = new Integer(6);
- public static final Integer seven = new Integer(7);
- public static final Integer eight = new Integer(8);
- public static final Integer nine = new Integer(9);
- public static final Integer m1 = new Integer(-1);
- public static final Integer m2 = new Integer(-2);
- public static final Integer m3 = new Integer(-3);
- public static final Integer m4 = new Integer(-4);
- public static final Integer m5 = new Integer(-5);
- public static final Integer m6 = new Integer(-6);
- public static final Integer m10 = new Integer(-10);
-
-
- /**
- * Runs Runnable r with a security policy that permits precisely
- * the specified permissions. If there is no current security
- * manager, the runnable is run twice, both with and without a
- * security manager. We require that any security manager permit
- * getPolicy/setPolicy.
- */
- public void runWithPermissions(Runnable r, Permission... permissions) {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null) {
- r.run();
- Policy savedPolicy = Policy.getPolicy();
- try {
- Policy.setPolicy(permissivePolicy());
- System.setSecurityManager(new SecurityManager());
- runWithPermissions(r, permissions);
- } finally {
- System.setSecurityManager(null);
- Policy.setPolicy(savedPolicy);
- }
- } else {
- Policy savedPolicy = Policy.getPolicy();
- AdjustablePolicy policy = new AdjustablePolicy(permissions);
- Policy.setPolicy(policy);
-
- try {
- r.run();
- } finally {
- policy.addPermission(new SecurityPermission("setPolicy"));
- Policy.setPolicy(savedPolicy);
- }
- }
- }
-
- /**
- * Runs a runnable without any permissions.
- */
- public void runWithoutPermissions(Runnable r) {
- runWithPermissions(r);
- }
-
- /**
- * A security policy where new permissions can be dynamically added
- * or all cleared.
- */
- public static class AdjustablePolicy extends java.security.Policy {
- Permissions perms = new Permissions();
- AdjustablePolicy(Permission... permissions) {
- for (Permission permission : permissions)
- perms.add(permission);
- }
- void addPermission(Permission perm) { perms.add(perm); }
- void clearPermissions() { perms = new Permissions(); }
- public PermissionCollection getPermissions(CodeSource cs) {
- return perms;
- }
- public PermissionCollection getPermissions(ProtectionDomain pd) {
- return perms;
- }
- public boolean implies(ProtectionDomain pd, Permission p) {
- return perms.implies(p);
- }
- public void refresh() {}
- }
-
- /**
- * Returns a policy containing all the permissions we ever need.
- */
- public static Policy permissivePolicy() {
- return new AdjustablePolicy
- // Permissions j.u.c. needs directly
- (new RuntimePermission("modifyThread"),
- new RuntimePermission("getClassLoader"),
- new RuntimePermission("setContextClassLoader"),
- // Permissions needed to change permissions!
- new SecurityPermission("getPolicy"),
- new SecurityPermission("setPolicy"),
- new RuntimePermission("setSecurityManager"),
- // Permissions needed by the junit test harness
- new RuntimePermission("accessDeclaredMembers"),
- new PropertyPermission("*", "read"),
- new java.io.FilePermission("<<ALL FILES>>", "read"));
- }
-
- /**
- * Sleep until the timeout has elapsed, or interrupted.
- * Does <em>NOT</em> throw InterruptedException.
- */
- void sleepTillInterrupted(long timeoutMillis) {
- try {
- Thread.sleep(timeoutMillis);
- } catch (InterruptedException wakeup) {}
- }
-
- /**
- * Returns a new started Thread running the given runnable.
- */
- Thread newStartedThread(Runnable runnable) {
- Thread t = new Thread(runnable);
- t.start();
- return t;
- }
-
- // Some convenient Runnable classes
-
- public abstract class CheckedRunnable implements Runnable {
- protected abstract void realRun() throws Throwable;
-
- public final void run() {
- try {
- realRun();
- } catch (Throwable t) {
- threadUnexpectedException(t);
- }
- }
- }
-
- public abstract class RunnableShouldThrow implements Runnable {
- protected abstract void realRun() throws Throwable;
-
- final Class<?> exceptionClass;
-
- <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
- this.exceptionClass = exceptionClass;
- }
-
- public final void run() {
- try {
- realRun();
- threadShouldThrow(exceptionClass.getSimpleName());
- } catch (Throwable t) {
- if (! exceptionClass.isInstance(t))
- threadUnexpectedException(t);
- }
- }
- }
-
- public abstract class ThreadShouldThrow extends Thread {
- protected abstract void realRun() throws Throwable;
-
- final Class<?> exceptionClass;
-
- <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
- this.exceptionClass = exceptionClass;
- }
-
- public final void run() {
- try {
- realRun();
- threadShouldThrow(exceptionClass.getSimpleName());
- } catch (Throwable t) {
- if (! exceptionClass.isInstance(t))
- threadUnexpectedException(t);
- }
- }
- }
-
- public abstract class CheckedInterruptedRunnable implements Runnable {
- protected abstract void realRun() throws Throwable;
-
- public final void run() {
- try {
- realRun();
- threadShouldThrow("InterruptedException");
- } catch (InterruptedException success) {
- } catch (Throwable t) {
- threadUnexpectedException(t);
- }
- }
- }
-
- public abstract class CheckedCallable<T> implements Callable<T> {
- protected abstract T realCall() throws Throwable;
-
- public final T call() {
- try {
- return realCall();
- } catch (Throwable t) {
- threadUnexpectedException(t);
- }
- return null;
- }
- }
-
- public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
- protected abstract T realCall() throws Throwable;
-
- public final T call() {
- try {
- T result = realCall();
- threadShouldThrow("InterruptedException");
- return result;
- } catch (InterruptedException success) {
- } catch (Throwable t) {
- threadUnexpectedException(t);
- }
- return null;
- }
- }
-
- public static class NoOpRunnable implements Runnable {
- public void run() {}
- }
-
- public static class NoOpCallable implements Callable {
- public Object call() { return Boolean.TRUE; }
- }
-
- public static final String TEST_STRING = "a test string";
-
- public static class StringTask implements Callable<String> {
- public String call() { return TEST_STRING; }
- }
-
- public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
- return new CheckedCallable<String>() {
- public String realCall() {
- try {
- latch.await();
- } catch (InterruptedException quittingTime) {}
- return TEST_STRING;
- }};
- }
-
- public static class NPETask implements Callable<String> {
- public String call() { throw new NullPointerException(); }
- }
-
- public static class CallableOne implements Callable<Integer> {
- public Integer call() { return one; }
- }
-
- public class ShortRunnable extends CheckedRunnable {
- protected void realRun() throws Throwable {
- Thread.sleep(SHORT_DELAY_MS);
- }
- }
-
- public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
- protected void realRun() throws InterruptedException {
- Thread.sleep(SHORT_DELAY_MS);
- }
- }
-
- public class SmallRunnable extends CheckedRunnable {
- protected void realRun() throws Throwable {
- Thread.sleep(SMALL_DELAY_MS);
- }
- }
-
- public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
- protected void realRun() {
- try {
- Thread.sleep(SMALL_DELAY_MS);
- } catch (InterruptedException ok) {}
- }
- }
-
- public class SmallCallable extends CheckedCallable {
- protected Object realCall() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- return Boolean.TRUE;
- }
- }
-
- public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
- protected void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- }
- }
-
- public class MediumRunnable extends CheckedRunnable {
- protected void realRun() throws Throwable {
- Thread.sleep(MEDIUM_DELAY_MS);
- }
- }
-
- public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
- protected void realRun() throws InterruptedException {
- Thread.sleep(MEDIUM_DELAY_MS);
- }
- }
-
- public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
- protected void realRun() {
- try {
- Thread.sleep(MEDIUM_DELAY_MS);
- } catch (InterruptedException ok) {}
- }
- }
-
- public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
- protected void realRun() {
- try {
- Thread.sleep(LONG_DELAY_MS);
- } catch (InterruptedException ok) {}
- }
- }
-
- /**
- * For use as ThreadFactory in constructors
- */
- public static class SimpleThreadFactory implements ThreadFactory {
- public Thread newThread(Runnable r) {
- return new Thread(r);
- }
- }
-
- public static class TrackedShortRunnable implements Runnable {
- public volatile boolean done = false;
- public void run() {
- try {
- Thread.sleep(SMALL_DELAY_MS);
- done = true;
- } catch (InterruptedException ok) {}
- }
- }
-
- public static class TrackedMediumRunnable implements Runnable {
- public volatile boolean done = false;
- public void run() {
- try {
- Thread.sleep(MEDIUM_DELAY_MS);
- done = true;
- } catch (InterruptedException ok) {}
- }
- }
-
- public static class TrackedLongRunnable implements Runnable {
- public volatile boolean done = false;
- public void run() {
- try {
- Thread.sleep(LONG_DELAY_MS);
- done = true;
- } catch (InterruptedException ok) {}
- }
- }
-
- public static class TrackedNoOpRunnable implements Runnable {
- public volatile boolean done = false;
- public void run() {
- done = true;
- }
- }
-
- public static class TrackedCallable implements Callable {
- public volatile boolean done = false;
- public Object call() {
- try {
- Thread.sleep(SMALL_DELAY_MS);
- done = true;
- } catch (InterruptedException ok) {}
- return Boolean.TRUE;
- }
- }
-
-
- /**
- * For use as RejectedExecutionHandler in constructors
- */
- public static class NoOpREHandler implements RejectedExecutionHandler {
- public void rejectedExecution(Runnable r,
- ThreadPoolExecutor executor) {}
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/LinkedBlockingDequeTest.java b/luni/src/test/java/tests/api/java/util/concurrent/LinkedBlockingDequeTest.java
deleted file mode 100644
index a858bb9..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/LinkedBlockingDequeTest.java
+++ /dev/null
@@ -1,1671 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-
-public class LinkedBlockingDequeTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(LinkedBlockingDequeTest.class);
- }
-
- /**
- * Create a deque of given size containing consecutive
- * Integers 0 ... n.
- */
- private LinkedBlockingDeque populatedDeque(int n) {
- LinkedBlockingDeque q = new LinkedBlockingDeque(n);
- assertTrue(q.isEmpty());
- for (int i = 0; i < n; i++)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(0, q.remainingCapacity());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- LinkedBlockingDeque q = new LinkedBlockingDeque();
- assertTrue(q.isEmpty());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.add(new Integer(2));
- q.removeFirst();
- q.removeFirst();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.removeFirst();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferFirstNull() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque();
- q.offerFirst(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * OfferFirst succeeds
- */
- public void testOfferFirst() {
- LinkedBlockingDeque q = new LinkedBlockingDeque();
- assertTrue(q.offerFirst(new Integer(0)));
- assertTrue(q.offerFirst(new Integer(1)));
- }
-
- /**
- * OfferLast succeeds
- */
- public void testOfferLast() {
- LinkedBlockingDeque q = new LinkedBlockingDeque();
- assertTrue(q.offerLast(new Integer(0)));
- assertTrue(q.offerLast(new Integer(1)));
- }
-
- /**
- * pollFirst succeeds unless empty
- */
- public void testPollFirst() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst());
- }
- assertNull(q.pollFirst());
- }
-
- /**
- * pollLast succeeds unless empty
- */
- public void testPollLast() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.pollLast());
- }
- assertNull(q.pollLast());
- }
-
- /**
- * peekFirst returns next element, or null if empty
- */
- public void testPeekFirst() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peekFirst());
- assertEquals(i, q.pollFirst());
- assertTrue(q.peekFirst() == null ||
- !q.peekFirst().equals(i));
- }
- assertNull(q.peekFirst());
- }
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.pollFirst());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * peekLast returns next element, or null if empty
- */
- public void testPeekLast() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.peekLast());
- assertEquals(i, q.pollLast());
- assertTrue(q.peekLast() == null ||
- !q.peekLast().equals(i));
- }
- assertNull(q.peekLast());
- }
-
- /**
- * getFirst returns next getFirst, or throws NSEE if empty
- */
- public void testFirstElement() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.getFirst());
- assertEquals(i, q.pollFirst());
- }
- try {
- q.getFirst();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- assertNull(q.peekFirst());
- }
-
- /**
- * getLast returns next element, or throws NSEE if empty
- */
- public void testLastElement() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = SIZE-1; i >= 0; --i) {
- assertEquals(i, q.getLast());
- assertEquals(i, q.pollLast());
- }
- try {
- q.getLast();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- assertNull(q.peekLast());
- }
-
- /**
- * removeFirst removes next element, or throws NSEE if empty
- */
- public void testRemoveFirst() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.removeFirst());
- }
- try {
- q.removeFirst();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- assertNull(q.peekFirst());
- }
-
- /**
- * removeLast removes last element, or throws NSEE if empty
- */
- public void testRemoveLast() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = SIZE - 1; i >= 0; --i) {
- assertEquals(i, q.removeLast());
- }
- try {
- q.removeLast();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- assertNull(q.peekLast());
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * removeFirstOccurrence(x) removes x and returns true if present
- */
- public void testRemoveFirstOccurrence() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.removeFirstOccurrence(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.removeFirstOccurrence(new Integer(i)));
- assertFalse(q.removeFirstOccurrence(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * removeLastOccurrence(x) removes x and returns true if present
- */
- public void testRemoveLastOccurrence() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.removeLastOccurrence(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.removeLastOccurrence(new Integer(i)));
- assertFalse(q.removeLastOccurrence(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * peekFirst returns element inserted with addFirst
- */
- public void testAddFirst() {
- LinkedBlockingDeque q = populatedDeque(3);
- q.pollLast();
- q.addFirst(four);
- assertSame(four, q.peekFirst());
- }
-
- /**
- * peekLast returns element inserted with addLast
- */
- public void testAddLast() {
- LinkedBlockingDeque q = populatedDeque(3);
- q.pollLast();
- q.addLast(four);
- assertSame(four, q.peekLast());
- }
-
-
- /**
- * A new deque has the indicated capacity, or Integer.MAX_VALUE if
- * none given
- */
- public void testConstructor1() {
- assertEquals(SIZE, new LinkedBlockingDeque(SIZE).remainingCapacity());
- assertEquals(Integer.MAX_VALUE, new LinkedBlockingDeque().remainingCapacity());
- }
-
- /**
- * Constructor throws IAE if capacity argument nonpositive
- */
- public void testConstructor2() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Deque contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- LinkedBlockingDeque q = new LinkedBlockingDeque(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * Deque transitions from empty to full when elements added
- */
- public void testEmptyFull() {
- LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- assertTrue(q.isEmpty());
- assertEquals("should have room for 2", 2, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- q.add(two);
- assertFalse(q.isEmpty());
- assertEquals(0, q.remainingCapacity());
- assertFalse(q.offer(three));
- }
-
- /**
- * remainingCapacity decreases on add, increases on remove
- */
- public void testRemainingCapacity() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remainingCapacity());
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.remainingCapacity());
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(1);
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(1);
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * push(null) throws NPE
- */
- public void testPushNull() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(1);
- q.push(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * push succeeds if not full; throws ISE if full
- */
- public void testPush() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.push(I);
- assertEquals(I, q.peek());
- }
- assertEquals(0, q.remainingCapacity());
- q.push(new Integer(SIZE));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * peekFirst returns element inserted with push
- */
- public void testPushWithPeek() {
- LinkedBlockingDeque q = populatedDeque(3);
- q.pollLast();
- q.push(four);
- assertSame(four, q.peekFirst());
- }
-
-
- /**
- * pop removes next element, or throws NSEE if empty
- */
- public void testPop() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pop());
- }
- try {
- q.pop();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
-
- /**
- * Offer succeeds if not full; fails if full
- */
- public void testOffer() {
- LinkedBlockingDeque q = new LinkedBlockingDeque(1);
- assertTrue(q.offer(zero));
- assertFalse(q.offer(one));
- }
-
- /**
- * add succeeds if not full; throws ISE if full
- */
- public void testAdd() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.add(new Integer(i)));
- }
- assertEquals(0, q.remainingCapacity());
- q.add(new Integer(SIZE));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(1);
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll throws ISE if not enough room
- */
- public void testAddAll4() {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(1);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * Deque contains all elements, in traversal order, of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
-
- /**
- * put(null) throws NPE
- */
- public void testPutNull() throws InterruptedException {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- q.put(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully put are contained
- */
- public void testPut() throws InterruptedException {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.put(I);
- assertTrue(q.contains(I));
- }
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * put blocks interruptibly if full
- */
- public void testBlockingPut() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- q.put(i);
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- try {
- q.put(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * put blocks waiting for take when full
- */
- public void testPutWithTake() throws InterruptedException {
- final int capacity = 2;
- final LinkedBlockingDeque q = new LinkedBlockingDeque(capacity);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < capacity + 1; i++)
- q.put(i);
- try {
- q.put(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(q.remainingCapacity(), 0);
- assertEquals(0, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(q.remainingCapacity(), 0);
- }
-
- /**
- * timed offer times out if full and elements not taken
- */
- public void testTimedOffer() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Object());
- q.put(new Object());
- assertFalse(q.offer(new Object(), SHORT_DELAY_MS, MILLISECONDS));
- try {
- q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * take retrieves elements in FIFO order
- */
- public void testTake() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- }
-
- /**
- * take blocks interruptibly when empty
- */
- public void testTakeFromEmpty() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- q.take();
- }};
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * Take removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTake() throws InterruptedException {
- final LinkedBlockingDeque q = populatedDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- try {
- q.take();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * timed poll with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll0() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(0, MILLISECONDS));
- }
- assertNull(q.poll(0, MILLISECONDS));
- }
-
- /**
- * timed poll with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPoll() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- try {
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOffer() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
-
- /**
- * putFirst(null) throws NPE
- */
- public void testPutFirstNull() throws InterruptedException {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- q.putFirst(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully putFirst are contained
- */
- public void testPutFirst() throws InterruptedException {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.putFirst(I);
- assertTrue(q.contains(I));
- }
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * putFirst blocks interruptibly if full
- */
- public void testBlockingPutFirst() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- q.putFirst(i);
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- try {
- q.putFirst(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * putFirst blocks waiting for take when full
- */
- public void testPutFirstWithTake() throws InterruptedException {
- final int capacity = 2;
- final LinkedBlockingDeque q = new LinkedBlockingDeque(capacity);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < capacity + 1; i++)
- q.putFirst(i);
- try {
- q.putFirst(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(q.remainingCapacity(), 0);
- assertEquals(capacity - 1, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(q.remainingCapacity(), 0);
- }
-
- /**
- * timed offerFirst times out if full and elements not taken
- */
- public void testTimedOfferFirst() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.putFirst(new Object());
- q.putFirst(new Object());
- assertFalse(q.offerFirst(new Object(), SHORT_DELAY_MS, MILLISECONDS));
- try {
- q.offerFirst(new Object(), LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * take retrieves elements in FIFO order
- */
- public void testTakeFirst() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.takeFirst());
- }
- }
-
- /**
- * takeFirst blocks interruptibly when empty
- */
- public void testTakeFirstFromEmpty() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- q.takeFirst();
- }};
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * TakeFirst removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTakeFirst() throws InterruptedException {
- final LinkedBlockingDeque q = populatedDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- assertEquals(i, q.takeFirst());
- try {
- q.takeFirst();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * timed pollFirst with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPollFirst0() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst(0, MILLISECONDS));
- }
- assertNull(q.pollFirst(0, MILLISECONDS));
- }
-
- /**
- * timed pollFirst with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPollFirst() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst(SHORT_DELAY_MS, MILLISECONDS));
- }
- assertNull(q.pollFirst(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed pollFirst throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPollFirst() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.pollFirst(SHORT_DELAY_MS, MILLISECONDS));
- }
- try {
- q.pollFirst(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed pollFirst before a delayed offerFirst fails; after offerFirst succeeds;
- * on interruption throws
- */
- public void testTimedPollFirstWithOfferFirst() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.pollFirst(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.pollFirst(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.pollFirst(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offerFirst(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
- /**
- * putLast(null) throws NPE
- */
- public void testPutLastNull() throws InterruptedException {
- try {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- q.putLast(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully putLast are contained
- */
- public void testPutLast() throws InterruptedException {
- LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.putLast(I);
- assertTrue(q.contains(I));
- }
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * putLast blocks interruptibly if full
- */
- public void testBlockingPutLast() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- q.putLast(i);
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- try {
- q.putLast(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * putLast blocks waiting for take when full
- */
- public void testPutLastWithTake() throws InterruptedException {
- final int capacity = 2;
- final LinkedBlockingDeque q = new LinkedBlockingDeque(capacity);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < capacity + 1; i++)
- q.putLast(i);
- try {
- q.putLast(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(q.remainingCapacity(), 0);
- assertEquals(0, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(q.remainingCapacity(), 0);
- }
-
- /**
- * timed offerLast times out if full and elements not taken
- */
- public void testTimedOfferLast() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.putLast(new Object());
- q.putLast(new Object());
- assertFalse(q.offerLast(new Object(), SHORT_DELAY_MS, MILLISECONDS));
- try {
- q.offerLast(new Object(), LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * takeLast retrieves elements in FIFO order
- */
- public void testTakeLast() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i-1, q.takeLast());
- }
- }
-
- /**
- * takeLast blocks interruptibly when empty
- */
- public void testTakeLastFromEmpty() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- q.takeLast();
- }};
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * TakeLast removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTakeLast() throws InterruptedException {
- final LinkedBlockingDeque q = populatedDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- assertEquals(SIZE - 1 - i, q.takeLast());
- try {
- q.takeLast();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed pollLast with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPollLast0() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i-1, q.pollLast(0, MILLISECONDS));
- }
- assertNull(q.pollLast(0, MILLISECONDS));
- }
-
- /**
- * timed pollLast with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPollLast() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i-1, q.pollLast(SHORT_DELAY_MS, MILLISECONDS));
- }
- assertNull(q.pollLast(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed pollLast throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPollLast() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i-1, q.pollLast(SHORT_DELAY_MS, MILLISECONDS));
- }
- try {
- q.pollLast(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offerLast fails; after offerLast succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOfferLast() throws InterruptedException {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offerLast(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.element());
- q.poll();
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.poll();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertEquals(SIZE, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(one));
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- LinkedBlockingDeque p = new LinkedBlockingDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- LinkedBlockingDeque p = populatedDeque(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- LinkedBlockingDeque p = populatedDeque(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() throws InterruptedException{
- LinkedBlockingDeque q = populatedDeque(SIZE);
- Object[] o = q.toArray();
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.take());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.take());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws CCE
- */
- public void testToArray1_BadArg() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- try {
- Object o[] = q.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() throws InterruptedException {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertEquals(it.next(), q.take());
- }
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(3);
- q.add(two);
- q.add(one);
- q.add(three);
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertSame(it.next(), one);
- assertSame(it.next(), three);
- assertFalse(it.hasNext());
- }
-
-
- /**
- * iterator ordering is FIFO
- */
- public void testIteratorOrdering() {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(3);
- q.add(one);
- q.add(two);
- q.add(three);
- assertEquals(0, q.remainingCapacity());
- int k = 0;
- for (Iterator it = q.iterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
- assertEquals(3, k);
- }
-
- /**
- * Modifications do not cause iterators to fail
- */
- public void testWeaklyConsistentIteration () {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(3);
- q.add(one);
- q.add(two);
- q.add(three);
- for (Iterator it = q.iterator(); it.hasNext();) {
- q.remove();
- it.next();
- }
- assertEquals(0, q.size());
- }
-
-
- /**
- * Descending iterator iterates through all elements
- */
- public void testDescendingIterator() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- int i = 0;
- Iterator it = q.descendingIterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- assertFalse(it.hasNext());
- try {
- it.next();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * Descending iterator ordering is reverse FIFO
- */
- public void testDescendingIteratorOrdering() {
- final LinkedBlockingDeque q = new LinkedBlockingDeque();
- for (int iters = 0; iters < 100; ++iters) {
- q.add(new Integer(3));
- q.add(new Integer(2));
- q.add(new Integer(1));
- int k = 0;
- for (Iterator it = q.descendingIterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
-
- assertEquals(3, k);
- q.remove();
- q.remove();
- q.remove();
- }
- }
-
- /**
- * descendingIterator.remove removes current element
- */
- public void testDescendingIteratorRemove () {
- final LinkedBlockingDeque q = new LinkedBlockingDeque();
- for (int iters = 0; iters < 100; ++iters) {
- q.add(new Integer(3));
- q.add(new Integer(2));
- q.add(new Integer(1));
- Iterator it = q.descendingIterator();
- assertEquals(it.next(), new Integer(1));
- it.remove();
- assertEquals(it.next(), new Integer(2));
- it = q.descendingIterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- it.remove();
- assertFalse(it.hasNext());
- q.remove();
- }
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
-
- /**
- * offer transfers elements across Executor tasks
- */
- public void testOfferInExecutor() {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- q.add(one);
- q.add(two);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(q.offer(three));
- assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
- assertEquals(0, q.remainingCapacity());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- assertSame(one, q.take());
- }});
-
- joinPool(executor);
- }
-
- /**
- * poll retrieves elements across Executor threads
- */
- public void testPollInExecutor() {
- final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll());
- assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- assertTrue(q.isEmpty());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- q.put(one);
- }});
-
- joinPool(executor);
- }
-
- /**
- * A deserialized serialized deque has same elements in same order
- */
- public void testSerialization() throws Exception {
- LinkedBlockingDeque q = populatedDeque(SIZE);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- LinkedBlockingDeque r = (LinkedBlockingDeque)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-
- /**
- * drainTo(null) throws NPE
- */
- public void testDrainToNull() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- try {
- q.drainTo(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this) throws IAE
- */
- public void testDrainToSelf() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- try {
- q.drainTo(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c) empties deque into another collection c
- */
- public void testDrainTo() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- q.add(zero);
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(zero));
- assertTrue(q.contains(one));
- l.clear();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), 2);
- for (int i = 0; i < 2; ++i)
- assertEquals(l.get(i), new Integer(i));
- }
-
- /**
- * drainTo empties full deque, unblocking a waiting put.
- */
- public void testDrainToWithActivePut() throws InterruptedException {
- final LinkedBlockingDeque q = populatedDeque(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Integer(SIZE+1));
- }});
-
- t.start();
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertTrue(l.size() >= SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- t.join();
- assertTrue(q.size() + l.size() >= SIZE);
- }
-
- /**
- * drainTo(null, n) throws NPE
- */
- public void testDrainToNullN() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- try {
- q.drainTo(null, 0);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this, n) throws IAE
- */
- public void testDrainToSelfN() {
- LinkedBlockingDeque q = populatedDeque(SIZE);
- try {
- q.drainTo(q, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c, n) empties first max {n, size} elements of deque into c
- */
- public void testDrainToN() {
- LinkedBlockingDeque q = new LinkedBlockingDeque();
- for (int i = 0; i < SIZE + 2; ++i) {
- for (int j = 0; j < SIZE; j++)
- assertTrue(q.offer(new Integer(j)));
- ArrayList l = new ArrayList();
- q.drainTo(l, i);
- int k = (i < SIZE)? i : SIZE;
- assertEquals(l.size(), k);
- assertEquals(q.size(), SIZE-k);
- for (int j = 0; j < k; ++j)
- assertEquals(l.get(j), new Integer(j));
- while (q.poll() != null) ;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java
deleted file mode 100755
index a98dc21..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java
+++ /dev/null
@@ -1,919 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-
-public class LinkedBlockingQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(LinkedBlockingQueueTest.class);
- }
-
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private LinkedBlockingQueue populatedQueue(int n) {
- LinkedBlockingQueue q = new LinkedBlockingQueue(n);
- assertTrue(q.isEmpty());
- for (int i = 0; i < n; i++)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(0, q.remainingCapacity());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * A new queue has the indicated capacity, or Integer.MAX_VALUE if
- * none given
- */
- public void testConstructor1() {
- assertEquals(SIZE, new LinkedBlockingQueue(SIZE).remainingCapacity());
- assertEquals(Integer.MAX_VALUE, new LinkedBlockingQueue().remainingCapacity());
- }
-
- /**
- * Constructor throws IAE if capacity argument nonpositive
- */
- public void testConstructor2() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * Queue transitions from empty to full when elements added
- */
- public void testEmptyFull() {
- LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- assertTrue(q.isEmpty());
- assertEquals("should have room for 2", 2, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- q.add(two);
- assertFalse(q.isEmpty());
- assertEquals(0, q.remainingCapacity());
- assertFalse(q.offer(three));
- }
-
- /**
- * remainingCapacity decreases on add, increases on remove
- */
- public void testRemainingCapacity() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remainingCapacity());
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.remainingCapacity());
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(1);
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(1);
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Offer succeeds if not full; fails if full
- */
- public void testOffer() {
- LinkedBlockingQueue q = new LinkedBlockingQueue(1);
- assertTrue(q.offer(zero));
- assertFalse(q.offer(one));
- }
-
- /**
- * add succeeds if not full; throws ISE if full
- */
- public void testAdd() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.add(new Integer(i)));
- }
- assertEquals(0, q.remainingCapacity());
- q.add(new Integer(SIZE));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(1);
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll throws ISE if not enough room
- */
- public void testAddAll4() {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(1);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
- /**
- * Queue contains all elements, in traversal order, of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * put(null) throws NPE
- */
- public void testPutNull() throws InterruptedException {
- try {
- LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- q.put(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully put are contained
- */
- public void testPut() throws InterruptedException {
- LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.put(I);
- assertTrue(q.contains(I));
- }
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * put blocks interruptibly if full
- */
- public void testBlockingPut() throws InterruptedException {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i)
- q.put(i);
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- try {
- q.put(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(SIZE, q.size());
- assertEquals(0, q.remainingCapacity());
- }
-
- /**
- * put blocks waiting for take when full
- */
- public void testPutWithTake() throws InterruptedException {
- final int capacity = 2;
- final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < capacity + 1; i++)
- q.put(i);
- try {
- q.put(99);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(q.remainingCapacity(), 0);
- assertEquals(0, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- assertEquals(q.remainingCapacity(), 0);
- }
-
- /**
- * timed offer times out if full and elements not taken
- */
- public void testTimedOffer() throws InterruptedException {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Object());
- q.put(new Object());
- assertFalse(q.offer(new Object(), SHORT_DELAY_MS, MILLISECONDS));
- try {
- q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * take retrieves elements in FIFO order
- */
- public void testTake() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- }
-
- /**
- * take blocks interruptibly when empty
- */
- public void testTakeFromEmpty() throws InterruptedException {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- Thread t = new ThreadShouldThrow(InterruptedException.class) {
- public void realRun() throws InterruptedException {
- q.take();
- }};
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * Take removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTake() throws InterruptedException {
- final LinkedBlockingQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- try {
- q.take();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * timed pool with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll0() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(0, MILLISECONDS));
- }
- assertNull(q.poll(0, MILLISECONDS));
- }
-
- /**
- * timed pool with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPoll() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- try {
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOffer() throws InterruptedException {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.poll());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.element());
- assertEquals(i, q.poll());
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * An add following remove(x) succeeds
- */
- public void testRemoveElementAndAdd() throws InterruptedException {
- LinkedBlockingQueue q = new LinkedBlockingQueue();
- assertTrue(q.add(new Integer(1)));
- assertTrue(q.add(new Integer(2)));
- assertTrue(q.remove(new Integer(1)));
- assertTrue(q.remove(new Integer(2)));
- assertTrue(q.add(new Integer(3)));
- assertTrue(q.take() != null);
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.poll();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertEquals(SIZE, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(one));
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- LinkedBlockingQueue p = new LinkedBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- LinkedBlockingQueue p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- LinkedBlockingQueue p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.take());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.take());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws CCE
- */
- public void testToArray1_BadArg() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() throws InterruptedException {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertEquals(it.next(), q.take());
- }
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
- q.add(two);
- q.add(one);
- q.add(three);
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertSame(it.next(), one);
- assertSame(it.next(), three);
- assertFalse(it.hasNext());
- }
-
-
- /**
- * iterator ordering is FIFO
- */
- public void testIteratorOrdering() {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
- q.add(one);
- q.add(two);
- q.add(three);
- assertEquals(0, q.remainingCapacity());
- int k = 0;
- for (Iterator it = q.iterator(); it.hasNext();) {
- assertEquals(++k, it.next());
- }
- assertEquals(3, k);
- }
-
- /**
- * Modifications do not cause iterators to fail
- */
- public void testWeaklyConsistentIteration () {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
- q.add(one);
- q.add(two);
- q.add(three);
- for (Iterator it = q.iterator(); it.hasNext();) {
- q.remove();
- it.next();
- }
- assertEquals(0, q.size());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
-
- /**
- * offer transfers elements across Executor tasks
- */
- public void testOfferInExecutor() {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- q.add(one);
- q.add(two);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(q.offer(three));
- assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
- assertEquals(0, q.remainingCapacity());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- assertSame(one, q.take());
- }});
-
- joinPool(executor);
- }
-
- /**
- * poll retrieves elements across Executor threads
- */
- public void testPollInExecutor() {
- final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll());
- assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- assertTrue(q.isEmpty());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- q.put(one);
- }});
-
- joinPool(executor);
- }
-
- /**
- * A deserialized serialized queue has same elements in same order
- */
- public void testSerialization() throws Exception {
- LinkedBlockingQueue q = populatedQueue(SIZE);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-
- /**
- * drainTo(null) throws NPE
- */
- public void testDrainToNull() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this) throws IAE
- */
- public void testDrainToSelf() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c) empties queue into another collection c
- */
- public void testDrainTo() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- q.add(zero);
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(zero));
- assertTrue(q.contains(one));
- l.clear();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), 2);
- for (int i = 0; i < 2; ++i)
- assertEquals(l.get(i), new Integer(i));
- }
-
- /**
- * drainTo empties full queue, unblocking a waiting put.
- */
- public void testDrainToWithActivePut() throws InterruptedException {
- final LinkedBlockingQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Integer(SIZE+1));
- }});
-
- t.start();
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertTrue(l.size() >= SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- t.join();
- assertTrue(q.size() + l.size() >= SIZE);
- }
-
- /**
- * drainTo(null, n) throws NPE
- */
- public void testDrainToNullN() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null, 0);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this, n) throws IAE
- */
- public void testDrainToSelfN() {
- LinkedBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c, n) empties first max {n, size} elements of queue into c
- */
- public void testDrainToN() {
- LinkedBlockingQueue q = new LinkedBlockingQueue();
- for (int i = 0; i < SIZE + 2; ++i) {
- for (int j = 0; j < SIZE; j++)
- assertTrue(q.offer(new Integer(j)));
- ArrayList l = new ArrayList();
- q.drainTo(l, i);
- int k = (i < SIZE)? i : SIZE;
- assertEquals(l.size(), k);
- assertEquals(q.size(), SIZE-k);
- for (int j = 0; j < k; ++j)
- assertEquals(l.get(j), new Integer(j));
- while (q.poll() != null) ;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java b/luni/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java
deleted file mode 100755
index 802bfbf..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java
+++ /dev/null
@@ -1,449 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent;
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-
-public class LinkedListTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(LinkedListTest.class);
- }
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private LinkedList populatedQueue(int n) {
- LinkedList q = new LinkedList();
- assertTrue(q.isEmpty());
- for(int i = 0; i < n; ++i)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * new queue is empty
- */
- public void testConstructor1() {
- assertEquals(0, new LinkedList().size());
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- LinkedList q = new LinkedList((Collection)null);
- shouldThrow();
- }
- catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
-
- */
- public void testConstructor6() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- LinkedList q = new LinkedList(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
- finally {}
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- LinkedList q = new LinkedList();
- assertTrue(q.isEmpty());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.add(new Integer(2));
- q.remove();
- q.remove();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) succeeds
- */
- public void testOfferNull() {
- try {
- LinkedList q = new LinkedList();
- q.offer(null);
- } catch (NullPointerException ie) {
- unexpectedException();
- }
- }
-
- /**
- * Offer succeeds
- */
- public void testOffer() {
- LinkedList q = new LinkedList();
- assertTrue(q.offer(new Integer(0)));
- assertTrue(q.offer(new Integer(1)));
- }
-
- /**
- * add succeeds
- */
- public void testAdd() {
- LinkedList q = new LinkedList();
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- assertTrue(q.add(new Integer(i)));
- }
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- LinkedList q = new LinkedList();
- q.addAll(null);
- shouldThrow();
- }
- catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements, in traversal order, of successful addAll
- */
- public void testAddAll5() {
- try {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- LinkedList q = new LinkedList();
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
- finally {}
- }
-
- /**
- * addAll with too large an index throws IOOBE
- */
- public void testAddAll2_IndexOutOfBoundsException() {
- try {
- LinkedList l = new LinkedList();
- l.add(new Object());
- LinkedList m = new LinkedList();
- m.add(new Object());
- l.addAll(4,m);
- shouldThrow();
- } catch(IndexOutOfBoundsException success) {}
- }
-
- /**
- * addAll with negative index throws IOOBE
- */
- public void testAddAll4_BadIndex() {
- try {
- LinkedList l = new LinkedList();
- l.add(new Object());
- LinkedList m = new LinkedList();
- m.add(new Object());
- l.addAll(-1,m);
- shouldThrow();
- } catch(IndexOutOfBoundsException success){}
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, ((Integer)q.poll()).intValue());
- }
- assertNull(q.poll());
- }
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, ((Integer)q.peek()).intValue());
- q.poll();
- assertTrue(q.peek() == null ||
- i != ((Integer)q.peek()).intValue());
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, ((Integer)q.element()).intValue());
- q.poll();
- }
- try {
- q.element();
- shouldThrow();
- }
- catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, ((Integer)q.remove()).intValue());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success){
- }
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- LinkedList q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.poll();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- LinkedList q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- LinkedList q = populatedQueue(SIZE);
- LinkedList p = new LinkedList();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- LinkedList q = populatedQueue(SIZE);
- LinkedList p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- LinkedList q = populatedQueue(SIZE);
- LinkedList p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() {
- LinkedList q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for(int i = 0; i < o.length; i++)
- assertEquals(o[i], q.poll());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() {
- LinkedList q = populatedQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for(int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- try {
- LinkedList l = new LinkedList();
- l.add(new Object());
- Object o[] = l.toArray(null);
- shouldThrow();
- } catch(NullPointerException success){}
- }
-
- /**
- * toArray with incompatable aray type throws CCE
- */
- public void testToArray1_BadArg() {
- try {
- LinkedList l = new LinkedList();
- l.add(new Integer(5));
- Object o[] = l.toArray(new String[10] );
- shouldThrow();
- } catch(ArrayStoreException success){}
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- LinkedList q = populatedQueue(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while(it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator ordering is FIFO
- */
- public void testIteratorOrdering() {
- final LinkedList q = new LinkedList();
- q.add(new Integer(1));
- q.add(new Integer(2));
- q.add(new Integer(3));
- int k = 0;
- for (Iterator it = q.iterator(); it.hasNext();) {
- int i = ((Integer)(it.next())).intValue();
- assertEquals(++k, i);
- }
-
- assertEquals(3, k);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final LinkedList q = new LinkedList();
- q.add(new Integer(1));
- q.add(new Integer(2));
- q.add(new Integer(3));
- Iterator it = q.iterator();
- it.next();
- it.remove();
- it = q.iterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- LinkedList q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * peek returns element inserted with addFirst
- */
- public void testAddFirst() {
- LinkedList q = populatedQueue(3);
- q.addFirst(four);
- assertEquals(four,q.peek());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java b/luni/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java
deleted file mode 100755
index 1052a24..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.concurrent.locks.*;
-
-public class LockSupportTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(LockSupportTest.class);
- }
-
- /**
- * park is released by unpark occurring after park
- */
- public void testPark() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- LockSupport.park();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- LockSupport.unpark(t);
- t.join();
- }
-
- /**
- * park is released by unpark occurring before park
- */
- public void testPark2() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SHORT_DELAY_MS);
- LockSupport.park();
- }});
-
- t.start();
- LockSupport.unpark(t);
- t.join();
- }
-
- /**
- * park is released by interrupt
- */
- public void testPark3() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- LockSupport.park();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * park returns if interrupted before park
- */
- public void testPark4() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.lock();
- LockSupport.park();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- lock.unlock();
- t.join();
- }
-
- /**
- * parkNanos times out if not unparked
- */
- public void testParkNanos() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- LockSupport.parkNanos(1000);
- }});
-
- t.start();
- t.join();
- }
-
-
- /**
- * parkUntil times out if not unparked
- */
- public void testParkUntil() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- long d = new Date().getTime() + 100;
- LockSupport.parkUntil(d);
- }});
-
- t.start();
- t.join();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java
deleted file mode 100755
index f1dd88d..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java
+++ /dev/null
@@ -1,840 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-
-public class PriorityBlockingQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(PriorityBlockingQueueTest.class);
- }
-
- private static final int NOCAP = Integer.MAX_VALUE;
-
- /** Sample Comparator */
- static class MyReverseComparator implements Comparator {
- public int compare(Object x, Object y) {
- return ((Comparable)y).compareTo(x);
- }
- }
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private PriorityBlockingQueue populatedQueue(int n) {
- PriorityBlockingQueue q = new PriorityBlockingQueue(n);
- assertTrue(q.isEmpty());
- for (int i = n-1; i >= 0; i-=2)
- assertTrue(q.offer(new Integer(i)));
- for (int i = (n & 1); i < n; i+=2)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(NOCAP, q.remainingCapacity());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * A new queue has unbounded capacity
- */
- public void testConstructor1() {
- assertEquals(NOCAP, new PriorityBlockingQueue(SIZE).remainingCapacity());
- }
-
- /**
- * Constructor throws IAE if capacity argument nonpositive
- */
- public void testConstructor2() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- PriorityBlockingQueue q = new PriorityBlockingQueue(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * The comparator used in constructor is used
- */
- public void testConstructor7() {
- MyReverseComparator cmp = new MyReverseComparator();
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE, cmp);
- assertEquals(cmp, q.comparator());
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- for (int i = SIZE-1; i >= 0; --i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- PriorityBlockingQueue q = new PriorityBlockingQueue(2);
- assertTrue(q.isEmpty());
- assertEquals(NOCAP, q.remainingCapacity());
- q.add(one);
- assertFalse(q.isEmpty());
- q.add(two);
- q.remove();
- q.remove();
- assertTrue(q.isEmpty());
- }
-
- /**
- * remainingCapacity does not change when elements added or removed,
- * but size does
- */
- public void testRemainingCapacity() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(NOCAP, q.remainingCapacity());
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(NOCAP, q.remainingCapacity());
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(1);
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(1);
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Offer of comparable element succeeds
- */
- public void testOffer() {
- PriorityBlockingQueue q = new PriorityBlockingQueue(1);
- assertTrue(q.offer(zero));
- assertTrue(q.offer(one));
- }
-
- /**
- * Offer of non-Comparable throws CCE
- */
- public void testOfferNonComparable() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(1);
- q.offer(new Object());
- q.offer(new Object());
- q.offer(new Object());
- shouldThrow();
- } catch (ClassCastException success) {}
- }
-
- /**
- * add of comparable succeeds
- */
- public void testAdd() {
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- assertTrue(q.add(new Integer(i)));
- }
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(1);
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = SIZE-1; i >= 0; --i)
- ints[i] = new Integer(i);
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * put(null) throws NPE
- */
- public void testPutNull() {
- try {
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
- q.put(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * all elements successfully put are contained
- */
- public void testPut() {
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- Integer I = new Integer(i);
- q.put(I);
- assertTrue(q.contains(I));
- }
- assertEquals(SIZE, q.size());
- }
-
- /**
- * put doesn't block waiting for take
- */
- public void testPutWithTake() throws InterruptedException {
- final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
- final int size = 4;
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- for (int i = 0; i < size; i++)
- q.put(new Integer(0));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(q.size(), size);
- q.take();
- t.interrupt();
- t.join();
- }
-
- /**
- * timed offer does not time out
- */
- public void testTimedOffer() throws InterruptedException {
- final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- q.put(new Integer(0));
- q.put(new Integer(0));
- assertTrue(q.offer(new Integer(0), SHORT_DELAY_MS, MILLISECONDS));
- assertTrue(q.offer(new Integer(0), LONG_DELAY_MS, MILLISECONDS));
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * take retrieves elements in priority order
- */
- public void testTake() throws InterruptedException {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- }
-
- /**
- * take blocks interruptibly when empty
- */
- public void testTakeFromEmpty() throws InterruptedException {
- final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- q.take();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * Take removes existing elements until empty, then blocks interruptibly
- */
- public void testBlockingTake() throws InterruptedException {
- final PriorityBlockingQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.take());
- }
- try {
- q.take();
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * timed pool with zero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll0() throws InterruptedException {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(0, MILLISECONDS));
- }
- assertNull(q.poll(0, MILLISECONDS));
- }
-
- /**
- * timed pool with nonzero timeout succeeds when non-empty, else times out
- */
- public void testTimedPoll() throws InterruptedException {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPoll() throws InterruptedException {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
- try {
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOffer() throws InterruptedException {
- final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.poll());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.element());
- assertEquals(i, q.poll());
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.poll();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(one));
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- PriorityBlockingQueue p = new PriorityBlockingQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- PriorityBlockingQueue p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- PriorityBlockingQueue p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() throws InterruptedException {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.take());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() throws InterruptedException {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.take());
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * toArray with incompatible array type throws CCE
- */
- public void testToArray1_BadArg() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- try {
- Object o[] = q.toArray(new String[10]);
- shouldThrow();
- } catch (ArrayStoreException success) {}
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final PriorityBlockingQueue q = new PriorityBlockingQueue(3);
- q.add(new Integer(2));
- q.add(new Integer(1));
- q.add(new Integer(3));
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * offer transfers elements across Executor tasks
- */
- public void testPollInExecutor() {
- final PriorityBlockingQueue q = new PriorityBlockingQueue(2);
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll());
- assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- assertTrue(q.isEmpty());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- q.put(one);
- }});
-
- joinPool(executor);
- }
-
- /**
- * A deserialized serialized queue has same elements
- */
- public void testSerialization() throws Exception {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- PriorityBlockingQueue r = (PriorityBlockingQueue)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-
- /**
- * drainTo(null) throws NPE
- */
- public void testDrainToNull() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this) throws IAE
- */
- public void testDrainToSelf() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c) empties queue into another collection c
- */
- public void testDrainTo() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- q.add(zero);
- q.add(one);
- assertFalse(q.isEmpty());
- assertTrue(q.contains(zero));
- assertTrue(q.contains(one));
- l.clear();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), 2);
- for (int i = 0; i < 2; ++i)
- assertEquals(l.get(i), new Integer(i));
- }
-
- /**
- * drainTo empties queue
- */
- public void testDrainToWithActivePut() throws InterruptedException {
- final PriorityBlockingQueue q = populatedQueue(SIZE);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- q.put(new Integer(SIZE+1));
- }});
-
- t.start();
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertTrue(l.size() >= SIZE);
- for (int i = 0; i < SIZE; ++i)
- assertEquals(l.get(i), new Integer(i));
- t.join();
- assertTrue(q.size() + l.size() >= SIZE);
- }
-
- /**
- * drainTo(null, n) throws NPE
- */
- public void testDrainToNullN() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(null, 0);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this, n) throws IAE
- */
- public void testDrainToSelfN() {
- PriorityBlockingQueue q = populatedQueue(SIZE);
- try {
- q.drainTo(q, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c, n) empties first max {n, size} elements of queue into c
- */
- public void testDrainToN() {
- PriorityBlockingQueue q = new PriorityBlockingQueue(SIZE*2);
- for (int i = 0; i < SIZE + 2; ++i) {
- for (int j = 0; j < SIZE; j++)
- assertTrue(q.offer(new Integer(j)));
- ArrayList l = new ArrayList();
- q.drainTo(l, i);
- int k = (i < SIZE)? i : SIZE;
- assertEquals(l.size(), k);
- assertEquals(q.size(), SIZE-k);
- for (int j = 0; j < k; ++j)
- assertEquals(l.get(j), new Integer(j));
- while (q.poll() != null) ;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java
deleted file mode 100755
index 12ddef4..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class PriorityQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(PriorityQueueTest.class);
- }
-
- static class MyReverseComparator implements Comparator {
- public int compare(Object x, Object y) {
- return ((Comparable)y).compareTo(x);
- }
- }
-
- /**
- * Create a queue of given size containing consecutive
- * Integers 0 ... n.
- */
- private PriorityQueue populatedQueue(int n) {
- PriorityQueue q = new PriorityQueue(n);
- assertTrue(q.isEmpty());
- for (int i = n-1; i >= 0; i-=2)
- assertTrue(q.offer(new Integer(i)));
- for (int i = (n & 1); i < n; i+=2)
- assertTrue(q.offer(new Integer(i)));
- assertFalse(q.isEmpty());
- assertEquals(n, q.size());
- return q;
- }
-
- /**
- * A new queue has unbounded capacity
- */
- public void testConstructor1() {
- assertEquals(0, new PriorityQueue(SIZE).size());
- }
-
- /**
- * Constructor throws IAE if capacity argument nonpositive
- */
- public void testConstructor2() {
- try {
- PriorityQueue q = new PriorityQueue(0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Initializing from null Collection throws NPE
- */
- public void testConstructor3() {
- try {
- PriorityQueue q = new PriorityQueue((Collection)null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection of null elements throws NPE
- */
- public void testConstructor4() {
- try {
- Integer[] ints = new Integer[SIZE];
- PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Initializing from Collection with some null elements throws NPE
- */
- public void testConstructor5() {
- try {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of collection used to initialize
- */
- public void testConstructor6() {
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * The comparator used in constructor is used
- */
- public void testConstructor7() {
- MyReverseComparator cmp = new MyReverseComparator();
- PriorityQueue q = new PriorityQueue(SIZE, cmp);
- assertEquals(cmp, q.comparator());
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- for (int i = SIZE-1; i >= 0; --i)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * isEmpty is true before add, false after
- */
- public void testEmpty() {
- PriorityQueue q = new PriorityQueue(2);
- assertTrue(q.isEmpty());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.add(new Integer(2));
- q.remove();
- q.remove();
- assertTrue(q.isEmpty());
- }
-
- /**
- * size changes when elements added and removed
- */
- public void testSize() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(SIZE-i, q.size());
- q.remove();
- }
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- q.add(new Integer(i));
- }
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- PriorityQueue q = new PriorityQueue(1);
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- PriorityQueue q = new PriorityQueue(1);
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Offer of comparable element succeeds
- */
- public void testOffer() {
- PriorityQueue q = new PriorityQueue(1);
- assertTrue(q.offer(zero));
- assertTrue(q.offer(one));
- }
-
- /**
- * Offer of non-Comparable throws CCE
- */
- public void testOfferNonComparable() {
- try {
- PriorityQueue q = new PriorityQueue(1);
- q.offer(new Object());
- q.offer(new Object());
- q.offer(new Object());
- shouldThrow();
- } catch (ClassCastException success) {}
- }
-
- /**
- * add of comparable succeeds
- */
- public void testAdd() {
- PriorityQueue q = new PriorityQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.size());
- assertTrue(q.add(new Integer(i)));
- }
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- PriorityQueue q = new PriorityQueue(1);
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- PriorityQueue q = new PriorityQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll of a collection with any null elements throws NPE after
- * possibly adding some elements
- */
- public void testAddAll3() {
- try {
- PriorityQueue q = new PriorityQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE-1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Queue contains all elements of successful addAll
- */
- public void testAddAll5() {
- Integer[] empty = new Integer[0];
- Integer[] ints = new Integer[SIZE];
- for (int i = 0; i < SIZE; ++i)
- ints[i] = new Integer(SIZE-1-i);
- PriorityQueue q = new PriorityQueue(SIZE);
- assertFalse(q.addAll(Arrays.asList(empty)));
- assertTrue(q.addAll(Arrays.asList(ints)));
- for (int i = 0; i < SIZE; ++i)
- assertEquals(new Integer(i), q.poll());
- }
-
- /**
- * poll succeeds unless empty
- */
- public void testPoll() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.poll());
- }
- assertNull(q.poll());
- }
-
- /**
- * peek returns next element, or null if empty
- */
- public void testPeek() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.peek());
- assertEquals(i, q.poll());
- assertTrue(q.peek() == null ||
- !q.peek().equals(i));
- }
- assertNull(q.peek());
- }
-
- /**
- * element returns next element, or throws NSEE if empty
- */
- public void testElement() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.element());
- assertEquals(i, q.poll());
- }
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove removes next element, or throws NSEE if empty
- */
- public void testRemove() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertEquals(i, q.remove());
- }
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) removes x and returns true if present
- */
- public void testRemoveElement() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 1; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- }
- for (int i = 0; i < SIZE; i+=2) {
- assertTrue(q.remove(new Integer(i)));
- assertFalse(q.remove(new Integer(i+1)));
- }
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains(x) reports true when elements added but not yet removed
- */
- public void testContains() {
- PriorityQueue q = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.contains(new Integer(i)));
- q.poll();
- assertFalse(q.contains(new Integer(i)));
- }
- }
-
- /**
- * clear removes all elements
- */
- public void testClear() {
- PriorityQueue q = populatedQueue(SIZE);
- q.clear();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- q.add(new Integer(1));
- assertFalse(q.isEmpty());
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll(c) is true when c contains a subset of elements
- */
- public void testContainsAll() {
- PriorityQueue q = populatedQueue(SIZE);
- PriorityQueue p = new PriorityQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(q.containsAll(p));
- assertFalse(p.containsAll(q));
- p.add(new Integer(i));
- }
- assertTrue(p.containsAll(q));
- }
-
- /**
- * retainAll(c) retains only those elements of c and reports true if changed
- */
- public void testRetainAll() {
- PriorityQueue q = populatedQueue(SIZE);
- PriorityQueue p = populatedQueue(SIZE);
- for (int i = 0; i < SIZE; ++i) {
- boolean changed = q.retainAll(p);
- if (i == 0)
- assertFalse(changed);
- else
- assertTrue(changed);
-
- assertTrue(q.containsAll(p));
- assertEquals(SIZE-i, q.size());
- p.remove();
- }
- }
-
- /**
- * removeAll(c) removes only those elements of c and reports true if changed
- */
- public void testRemoveAll() {
- for (int i = 1; i < SIZE; ++i) {
- PriorityQueue q = populatedQueue(SIZE);
- PriorityQueue p = populatedQueue(i);
- assertTrue(q.removeAll(p));
- assertEquals(SIZE-i, q.size());
- for (int j = 0; j < i; ++j) {
- Integer I = (Integer)(p.remove());
- assertFalse(q.contains(I));
- }
- }
- }
-
- /**
- * toArray contains all elements
- */
- public void testToArray() {
- PriorityQueue q = populatedQueue(SIZE);
- Object[] o = q.toArray();
- Arrays.sort(o);
- for (int i = 0; i < o.length; i++)
- assertEquals(o[i], q.poll());
- }
-
- /**
- * toArray(a) contains all elements
- */
- public void testToArray2() {
- PriorityQueue q = populatedQueue(SIZE);
- Integer[] ints = new Integer[SIZE];
- ints = (Integer[])q.toArray(ints);
- Arrays.sort(ints);
- for (int i = 0; i < ints.length; i++)
- assertEquals(ints[i], q.poll());
- }
-
- /**
- * iterator iterates through all elements
- */
- public void testIterator() {
- PriorityQueue q = populatedQueue(SIZE);
- int i = 0;
- Iterator it = q.iterator();
- while (it.hasNext()) {
- assertTrue(q.contains(it.next()));
- ++i;
- }
- assertEquals(i, SIZE);
- }
-
- /**
- * iterator.remove removes current element
- */
- public void testIteratorRemove () {
- final PriorityQueue q = new PriorityQueue(3);
- q.add(new Integer(2));
- q.add(new Integer(1));
- q.add(new Integer(3));
-
- Iterator it = q.iterator();
- it.next();
- it.remove();
-
- it = q.iterator();
- assertEquals(it.next(), new Integer(2));
- assertEquals(it.next(), new Integer(3));
- assertFalse(it.hasNext());
- }
-
-
- /**
- * toString contains toStrings of elements
- */
- public void testToString() {
- PriorityQueue q = populatedQueue(SIZE);
- String s = q.toString();
- for (int i = 0; i < SIZE; ++i) {
- assertTrue(s.indexOf(String.valueOf(i)) >= 0);
- }
- }
-
- /**
- * A deserialized serialized queue has same elements
- */
- public void testSerialization() throws Exception {
- PriorityQueue q = populatedQueue(SIZE);
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- PriorityQueue r = (PriorityQueue)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java
deleted file mode 100755
index d6b434e..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java
+++ /dev/null
@@ -1,911 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.locks.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.*;
-import java.io.*;
-
-public class ReentrantLockTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ReentrantLockTest.class);
- }
-
- /**
- * A runnable calling lockInterruptibly
- */
- class InterruptibleLockRunnable extends CheckedRunnable {
- final ReentrantLock lock;
- InterruptibleLockRunnable(ReentrantLock l) { lock = l; }
- public void realRun() throws InterruptedException {
- lock.lockInterruptibly();
- }
- }
-
-
- /**
- * A runnable calling lockInterruptibly that expects to be
- * interrupted
- */
- class InterruptedLockRunnable extends CheckedInterruptedRunnable {
- final ReentrantLock lock;
- InterruptedLockRunnable(ReentrantLock l) { lock = l; }
- public void realRun() throws InterruptedException {
- lock.lockInterruptibly();
- }
- }
-
- /**
- * Subclass to expose protected methods
- */
- static class PublicReentrantLock extends ReentrantLock {
- PublicReentrantLock() { super(); }
- public Collection<Thread> getQueuedThreads() {
- return super.getQueuedThreads();
- }
- public Collection<Thread> getWaitingThreads(Condition c) {
- return super.getWaitingThreads(c);
- }
- }
-
- /**
- * Constructor sets given fairness
- */
- public void testConstructor() {
- assertFalse(new ReentrantLock().isFair());
- assertFalse(new ReentrantLock(false).isFair());
- assertTrue(new ReentrantLock(true).isFair());
- }
-
- /**
- * locking an unlocked lock succeeds
- */
- public void testLock() {
- ReentrantLock rl = new ReentrantLock();
- rl.lock();
- assertTrue(rl.isLocked());
- rl.unlock();
- assertFalse(rl.isLocked());
- }
-
- /**
- * locking an unlocked fair lock succeeds
- */
- public void testFairLock() {
- ReentrantLock rl = new ReentrantLock(true);
- rl.lock();
- assertTrue(rl.isLocked());
- rl.unlock();
- }
-
- /**
- * Unlocking an unlocked lock throws IllegalMonitorStateException
- */
- public void testUnlock_IllegalMonitorStateException() {
- ReentrantLock rl = new ReentrantLock();
- try {
- rl.unlock();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * tryLock on an unlocked lock succeeds
- */
- public void testTryLock() {
- ReentrantLock rl = new ReentrantLock();
- assertTrue(rl.tryLock());
- assertTrue(rl.isLocked());
- rl.unlock();
- }
-
-
- /**
- * hasQueuedThreads reports whether there are waiting threads
- */
- public void testhasQueuedThreads() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertFalse(lock.hasQueuedThreads());
- lock.lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(lock.hasQueuedThreads());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueueLength reports number of waiting threads
- */
- public void testGetQueueLength() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertEquals(0, lock.getQueueLength());
- lock.lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, lock.getQueueLength());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, lock.getQueueLength());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueueLength reports number of waiting threads
- */
- public void testGetQueueLength_fair() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock(true);
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertEquals(0, lock.getQueueLength());
- lock.lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, lock.getQueueLength());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, lock.getQueueLength());
- t1.join();
- t2.join();
- }
-
- /**
- * hasQueuedThread(null) throws NPE
- */
- public void testHasQueuedThreadNPE() {
- final ReentrantLock sync = new ReentrantLock();
- try {
- sync.hasQueuedThread(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * hasQueuedThread reports whether a thread is queued.
- */
- public void testHasQueuedThread() throws InterruptedException {
- final ReentrantLock sync = new ReentrantLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(sync));
- Thread t2 = new Thread(new InterruptibleLockRunnable(sync));
- assertFalse(sync.hasQueuedThread(t1));
- assertFalse(sync.hasQueuedThread(t2));
- sync.lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThread(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThread(t1));
- assertTrue(sync.hasQueuedThread(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThread(t1));
- assertTrue(sync.hasQueuedThread(t2));
- sync.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThread(t1));
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThread(t2));
- t1.join();
- t2.join();
- }
-
-
- /**
- * getQueuedThreads includes waiting threads
- */
- public void testGetQueuedThreads() throws InterruptedException {
- final PublicReentrantLock lock = new PublicReentrantLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertTrue(lock.getQueuedThreads().isEmpty());
- lock.lock();
- assertTrue(lock.getQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().contains(t1));
- assertTrue(lock.getQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(lock.getQueuedThreads().contains(t1));
- assertTrue(lock.getQueuedThreads().contains(t2));
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
-
- /**
- * timed tryLock is interruptible.
- */
- public void testInterruptedException2() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lock();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.tryLock(MEDIUM_DELAY_MS,MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * TryLock on a locked lock fails
- */
- public void testTryLockWhenLocked() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(lock.tryLock());
- }});
-
- t.start();
- t.join();
- lock.unlock();
- }
-
- /**
- * Timed tryLock on a locked lock times out
- */
- public void testTryLock_Timeout() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(lock.tryLock(1, MILLISECONDS));
- }});
-
- t.start();
- t.join();
- lock.unlock();
- }
-
- /**
- * getHoldCount returns number of recursive holds
- */
- public void testGetHoldCount() {
- ReentrantLock lock = new ReentrantLock();
- for (int i = 1; i <= SIZE; i++) {
- lock.lock();
- assertEquals(i, lock.getHoldCount());
- }
- for (int i = SIZE; i > 0; i--) {
- lock.unlock();
- assertEquals(i-1, lock.getHoldCount());
- }
- }
-
-
- /**
- * isLocked is true when locked and false when not
- */
- public void testIsLocked() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lock();
- assertTrue(lock.isLocked());
- lock.unlock();
- assertFalse(lock.isLocked());
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- Thread.sleep(SMALL_DELAY_MS);
- lock.unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.isLocked());
- t.join();
- assertFalse(lock.isLocked());
- }
-
-
- /**
- * lockInterruptibly is interruptible.
- */
- public void testLockInterruptibly1() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lock();
- Thread t = new Thread(new InterruptedLockRunnable(lock));
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- lock.unlock();
- t.join();
- }
-
- /**
- * lockInterruptibly succeeds when unlocked, else is interruptible
- */
- public void testLockInterruptibly2() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- lock.lockInterruptibly();
- Thread t = new Thread(new InterruptedLockRunnable(lock));
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- assertTrue(lock.isLocked());
- assertTrue(lock.isHeldByCurrentThread());
- t.join();
- }
-
- /**
- * Calling await without holding lock throws IllegalMonitorStateException
- */
- public void testAwait_IllegalMonitor() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- try {
- c.await();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * Calling signal without holding lock throws IllegalMonitorStateException
- */
- public void testSignal_IllegalMonitor() {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- try {
- c.signal();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * awaitNanos without a signal times out
- */
- public void testAwaitNanos_Timeout() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- lock.lock();
- long t = c.awaitNanos(100);
- assertTrue(t <= 0);
- lock.unlock();
- }
-
- /**
- * timed await without a signal times out
- */
- public void testAwait_Timeout() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- lock.lock();
- assertFalse(c.await(SHORT_DELAY_MS, MILLISECONDS));
- lock.unlock();
- }
-
- /**
- * awaitUntil without a signal times out
- */
- public void testAwaitUntil_Timeout() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- lock.lock();
- java.util.Date d = new java.util.Date();
- assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
- lock.unlock();
- }
-
- /**
- * await returns when signalled
- */
- public void testAwait() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- c.await();
- lock.unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- c.signal();
- lock.unlock();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * hasWaiters throws NPE if null
- */
- public void testHasWaitersNPE() {
- final ReentrantLock lock = new ReentrantLock();
- try {
- lock.hasWaiters(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * getWaitQueueLength throws NPE if null
- */
- public void testGetWaitQueueLengthNPE() {
- final ReentrantLock lock = new ReentrantLock();
- try {
- lock.getWaitQueueLength(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * getWaitingThreads throws NPE if null
- */
- public void testGetWaitingThreadsNPE() {
- final PublicReentrantLock lock = new PublicReentrantLock();
- try {
- lock.getWaitingThreads(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * hasWaiters throws IAE if not owned
- */
- public void testHasWaitersIAE() {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- final ReentrantLock lock2 = new ReentrantLock();
- try {
- lock2.hasWaiters(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * hasWaiters throws IMSE if not locked
- */
- public void testHasWaitersIMSE() {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- try {
- lock.hasWaiters(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitQueueLength throws IAE if not owned
- */
- public void testGetWaitQueueLengthIAE() {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- final ReentrantLock lock2 = new ReentrantLock();
- try {
- lock2.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitQueueLength throws IMSE if not locked
- */
- public void testGetWaitQueueLengthIMSE() {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- try {
- lock.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitingThreads throws IAE if not owned
- */
- public void testGetWaitingThreadsIAE() {
- final PublicReentrantLock lock = new PublicReentrantLock();
- final Condition c = lock.newCondition();
- final PublicReentrantLock lock2 = new PublicReentrantLock();
- try {
- lock2.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitingThreads throws IMSE if not locked
- */
- public void testGetWaitingThreadsIMSE() {
- final PublicReentrantLock lock = new PublicReentrantLock();
- final Condition c = lock.newCondition();
- try {
- lock.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * hasWaiters returns true when a thread is waiting, else false
- */
- public void testHasWaiters() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- threadAssertFalse(lock.hasWaiters(c));
- threadAssertEquals(0, lock.getWaitQueueLength(c));
- c.await();
- lock.unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- assertTrue(lock.hasWaiters(c));
- assertEquals(1, lock.getWaitQueueLength(c));
- c.signal();
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- assertFalse(lock.hasWaiters(c));
- assertEquals(0, lock.getWaitQueueLength(c));
- lock.unlock();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * getWaitQueueLength returns number of waiting threads
- */
- public void testGetWaitQueueLength() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- threadAssertFalse(lock.hasWaiters(c));
- threadAssertEquals(0, lock.getWaitQueueLength(c));
- c.await();
- lock.unlock();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- threadAssertTrue(lock.hasWaiters(c));
- threadAssertEquals(1, lock.getWaitQueueLength(c));
- c.await();
- lock.unlock();
- }});
-
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- assertTrue(lock.hasWaiters(c));
- assertEquals(2, lock.getWaitQueueLength(c));
- c.signalAll();
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- assertFalse(lock.hasWaiters(c));
- assertEquals(0, lock.getWaitQueueLength(c));
- lock.unlock();
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * getWaitingThreads returns only and all waiting threads
- */
- public void testGetWaitingThreads() throws InterruptedException {
- final PublicReentrantLock lock = new PublicReentrantLock();
- final Condition c = lock.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- threadAssertTrue(lock.getWaitingThreads(c).isEmpty());
- c.await();
- lock.unlock();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- threadAssertFalse(lock.getWaitingThreads(c).isEmpty());
- c.await();
- lock.unlock();
- }});
-
- lock.lock();
- assertTrue(lock.getWaitingThreads(c).isEmpty());
- lock.unlock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- assertTrue(lock.hasWaiters(c));
- assertTrue(lock.getWaitingThreads(c).contains(t1));
- assertTrue(lock.getWaitingThreads(c).contains(t2));
- c.signalAll();
- lock.unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- assertFalse(lock.hasWaiters(c));
- assertTrue(lock.getWaitingThreads(c).isEmpty());
- lock.unlock();
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /** A helper class for uninterruptible wait tests */
- class UninterruptibleThread extends Thread {
- private ReentrantLock lock;
- private Condition c;
-
- public volatile boolean canAwake = false;
- public volatile boolean interrupted = false;
- public volatile boolean lockStarted = false;
-
- public UninterruptibleThread(ReentrantLock lock, Condition c) {
- this.lock = lock;
- this.c = c;
- }
-
- public synchronized void run() {
- lock.lock();
- lockStarted = true;
-
- while (!canAwake) {
- c.awaitUninterruptibly();
- }
-
- interrupted = isInterrupted();
- lock.unlock();
- }
- }
-
- /**
- * awaitUninterruptibly doesn't abort on interrupt
- */
- public void testAwaitUninterruptibly() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- UninterruptibleThread thread = new UninterruptibleThread(lock, c);
-
- thread.start();
-
- while (!thread.lockStarted) {
- Thread.sleep(100);
- }
-
- lock.lock();
- try {
- thread.interrupt();
- thread.canAwake = true;
- c.signal();
- } finally {
- lock.unlock();
- }
-
- thread.join();
- assertTrue(thread.interrupted);
- assertFalse(thread.isAlive());
- }
-
- /**
- * await is interruptible
- */
- public void testAwait_Interrupt() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- c.await();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitNanos is interruptible
- */
- public void testAwaitNanos_Interrupt() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- c.awaitNanos(MILLISECONDS.toNanos(LONG_DELAY_MS));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitUntil is interruptible
- */
- public void testAwaitUntil_Interrupt() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- java.util.Date d = new java.util.Date();
- c.awaitUntil(new java.util.Date(d.getTime() + 10000));
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * signalAll wakes up all threads
- */
- public void testSignalAll() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- c.await();
- lock.unlock();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- c.await();
- lock.unlock();
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- c.signalAll();
- lock.unlock();
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * await after multiple reentrant locking preserves lock count
- */
- public void testAwaitLockCount() throws InterruptedException {
- final ReentrantLock lock = new ReentrantLock();
- final Condition c = lock.newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- threadAssertEquals(1, lock.getHoldCount());
- c.await();
- threadAssertEquals(1, lock.getHoldCount());
- lock.unlock();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.lock();
- lock.lock();
- threadAssertEquals(2, lock.getHoldCount());
- c.await();
- threadAssertEquals(2, lock.getHoldCount());
- lock.unlock();
- lock.unlock();
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.lock();
- c.signalAll();
- lock.unlock();
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * A serialized lock deserializes as unlocked
- */
- public void testSerialization() throws Exception {
- ReentrantLock l = new ReentrantLock();
- l.lock();
- l.unlock();
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out =
- new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin =
- new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in =
- new ObjectInputStream(new BufferedInputStream(bin));
- ReentrantLock r = (ReentrantLock) in.readObject();
- r.lock();
- r.unlock();
- }
-
- /**
- * toString indicates current lock state
- */
- public void testToString() {
- ReentrantLock lock = new ReentrantLock();
- String us = lock.toString();
- assertTrue(us.indexOf("Unlocked") >= 0);
- lock.lock();
- String ls = lock.toString();
- assertTrue(ls.indexOf("Locked") >= 0);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java
deleted file mode 100644
index eb20255..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java
+++ /dev/null
@@ -1,1371 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.locks.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-import java.util.*;
-
-public class ReentrantReadWriteLockTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ReentrantReadWriteLockTest.class);
- }
-
- /**
- * A runnable calling lockInterruptibly
- */
- class InterruptibleLockRunnable extends CheckedRunnable {
- final ReentrantReadWriteLock lock;
- InterruptibleLockRunnable(ReentrantReadWriteLock l) { lock = l; }
- public void realRun() throws InterruptedException {
- lock.writeLock().lockInterruptibly();
- }
- }
-
-
- /**
- * A runnable calling lockInterruptibly that expects to be
- * interrupted
- */
- class InterruptedLockRunnable extends CheckedInterruptedRunnable {
- final ReentrantReadWriteLock lock;
- InterruptedLockRunnable(ReentrantReadWriteLock l) { lock = l; }
- public void realRun() throws InterruptedException {
- lock.writeLock().lockInterruptibly();
- }
- }
-
- /**
- * Subclass to expose protected methods
- */
- static class PublicReentrantReadWriteLock extends ReentrantReadWriteLock {
- PublicReentrantReadWriteLock() { super(); }
- public Collection<Thread> getQueuedThreads() {
- return super.getQueuedThreads();
- }
- public Collection<Thread> getWaitingThreads(Condition c) {
- return super.getWaitingThreads(c);
- }
- }
-
- /**
- * Constructor sets given fairness, and is in unlocked state
- */
- public void testConstructor() {
- ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
- assertFalse(rl.isFair());
- assertFalse(rl.isWriteLocked());
- assertEquals(0, rl.getReadLockCount());
- ReentrantReadWriteLock r2 = new ReentrantReadWriteLock(true);
- assertTrue(r2.isFair());
- assertFalse(r2.isWriteLocked());
- assertEquals(0, r2.getReadLockCount());
- ReentrantReadWriteLock r3 = new ReentrantReadWriteLock(false);
- assertFalse(r3.isFair());
- assertFalse(r3.isWriteLocked());
- assertEquals(0, r3.getReadLockCount());
- }
-
- /**
- * write-locking and read-locking an unlocked lock succeed
- */
- public void testLock() {
- ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
- rl.writeLock().lock();
- assertTrue(rl.isWriteLocked());
- assertTrue(rl.isWriteLockedByCurrentThread());
- assertTrue(rl.writeLock().isHeldByCurrentThread());
- assertEquals(0, rl.getReadLockCount());
- rl.writeLock().unlock();
- assertFalse(rl.isWriteLocked());
- assertFalse(rl.isWriteLockedByCurrentThread());
- assertFalse(rl.writeLock().isHeldByCurrentThread());
- assertEquals(0, rl.getReadLockCount());
- rl.readLock().lock();
- assertFalse(rl.isWriteLocked());
- assertFalse(rl.isWriteLockedByCurrentThread());
- assertEquals(1, rl.getReadLockCount());
- rl.readLock().unlock();
- assertFalse(rl.isWriteLocked());
- assertFalse(rl.isWriteLockedByCurrentThread());
- assertEquals(0, rl.getReadLockCount());
- }
-
-
- /**
- * locking an unlocked fair lock succeeds
- */
- public void testFairLock() {
- ReentrantReadWriteLock rl = new ReentrantReadWriteLock(true);
- rl.writeLock().lock();
- assertTrue(rl.isWriteLocked());
- assertTrue(rl.isWriteLockedByCurrentThread());
- assertTrue(rl.writeLock().isHeldByCurrentThread());
- assertEquals(0, rl.getReadLockCount());
- rl.writeLock().unlock();
- assertFalse(rl.isWriteLocked());
- assertFalse(rl.isWriteLockedByCurrentThread());
- assertFalse(rl.writeLock().isHeldByCurrentThread());
- assertEquals(0, rl.getReadLockCount());
- rl.readLock().lock();
- assertFalse(rl.isWriteLocked());
- assertFalse(rl.isWriteLockedByCurrentThread());
- assertEquals(1, rl.getReadLockCount());
- rl.readLock().unlock();
- assertFalse(rl.isWriteLocked());
- assertFalse(rl.isWriteLockedByCurrentThread());
- assertEquals(0, rl.getReadLockCount());
- }
-
- /**
- * getWriteHoldCount returns number of recursive holds
- */
- public void testGetWriteHoldCount() {
- ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- for (int i = 1; i <= SIZE; i++) {
- lock.writeLock().lock();
- assertEquals(i,lock.getWriteHoldCount());
- }
- for (int i = SIZE; i > 0; i--) {
- lock.writeLock().unlock();
- assertEquals(i-1,lock.getWriteHoldCount());
- }
- }
-
- /**
- * WriteLock.getHoldCount returns number of recursive holds
- */
- public void testGetHoldCount() {
- ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- for (int i = 1; i <= SIZE; i++) {
- lock.writeLock().lock();
- assertEquals(i,lock.writeLock().getHoldCount());
- }
- for (int i = SIZE; i > 0; i--) {
- lock.writeLock().unlock();
- assertEquals(i-1,lock.writeLock().getHoldCount());
- }
- }
-
- /**
- * getReadHoldCount returns number of recursive holds
- */
- public void testGetReadHoldCount() {
- ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- for (int i = 1; i <= SIZE; i++) {
- lock.readLock().lock();
- assertEquals(i,lock.getReadHoldCount());
- }
- for (int i = SIZE; i > 0; i--) {
- lock.readLock().unlock();
- assertEquals(i-1,lock.getReadHoldCount());
- }
- }
-
-
- /**
- * write-unlocking an unlocked lock throws IllegalMonitorStateException
- */
- public void testUnlock_IllegalMonitorStateException() {
- ReentrantReadWriteLock rl = new ReentrantReadWriteLock();
- try {
- rl.writeLock().unlock();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * write-lockInterruptibly is interruptible
- */
- public void testWriteLockInterruptibly_Interrupted() throws Exception {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lockInterruptibly();
- lock.writeLock().unlock();
- lock.writeLock().lockInterruptibly();
- lock.writeLock().unlock();
- }});
-
- lock.writeLock().lock();
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().unlock();
- t.join();
- }
-
- /**
- * timed write-tryLock is interruptible
- */
- public void testWriteTryLock_Interrupted() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().tryLock(SMALL_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- lock.writeLock().unlock();
- t.join();
- }
-
- /**
- * read-lockInterruptibly is interruptible
- */
- public void testReadLockInterruptibly_Interrupted() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.readLock().lockInterruptibly();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().unlock();
- t.join();
- }
-
- /**
- * timed read-tryLock is interruptible
- */
- public void testReadTryLock_Interrupted() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.readLock().tryLock(LONG_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * write-tryLock fails if locked
- */
- public void testWriteTryLockWhenLocked() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(lock.writeLock().tryLock());
- }});
-
- t.start();
- t.join();
- lock.writeLock().unlock();
- }
-
- /**
- * read-tryLock fails if locked
- */
- public void testReadTryLockWhenLocked() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(lock.readLock().tryLock());
- }});
-
- t.start();
- t.join();
- lock.writeLock().unlock();
- }
-
- /**
- * Multiple threads can hold a read lock when not write-locked
- */
- public void testMultipleReadLocks() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.readLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertTrue(lock.readLock().tryLock());
- lock.readLock().unlock();
- }});
-
- t.start();
- t.join();
- lock.readLock().unlock();
- }
-
- /**
- * A writelock succeeds after reading threads unlock
- */
- public void testWriteAfterMultipleReadLocks() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.readLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.readLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
- /**
- * Readlocks succeed after a writing thread unlocks
- */
- public void testReadAfterWriteLock() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
- /**
- * Read trylock succeeds if write locked by current thread
- */
- public void testReadHoldingWriteLock() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- assertTrue(lock.readLock().tryLock());
- lock.readLock().unlock();
- lock.writeLock().unlock();
- }
-
- /**
- * Read lock succeeds if write locked by current thread even if
- * other threads are waiting for readlock
- */
- public void testReadHoldingWriteLock2() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
-
- t1.start();
- t2.start();
- lock.readLock().lock();
- lock.readLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.readLock().lock();
- lock.readLock().unlock();
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
- /**
- * Read lock succeeds if write locked by current thread even if
- * other threads are waiting for writelock
- */
- public void testReadHoldingWriteLock3() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
-
- t1.start();
- t2.start();
- lock.readLock().lock();
- lock.readLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.readLock().lock();
- lock.readLock().unlock();
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
-
- /**
- * Write lock succeeds if write locked by current thread even if
- * other threads are waiting for writelock
- */
- public void testWriteHoldingWriteLock4() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
-
- t1.start();
- t2.start();
- lock.writeLock().lock();
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- lock.writeLock().unlock();
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
-
- /**
- * Fair Read trylock succeeds if write locked by current thread
- */
- public void testReadHoldingWriteLockFair() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
- lock.writeLock().lock();
- assertTrue(lock.readLock().tryLock());
- lock.readLock().unlock();
- lock.writeLock().unlock();
- }
-
- /**
- * Fair Read lock succeeds if write locked by current thread even if
- * other threads are waiting for readlock
- */
- public void testReadHoldingWriteLockFair2() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.readLock().lock();
- lock.readLock().unlock();
- }});
-
- t1.start();
- t2.start();
- lock.readLock().lock();
- lock.readLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.readLock().lock();
- lock.readLock().unlock();
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
-
- /**
- * Fair Read lock succeeds if write locked by current thread even if
- * other threads are waiting for writelock
- */
- public void testReadHoldingWriteLockFair3() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
-
- t1.start();
- t2.start();
- lock.readLock().lock();
- lock.readLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.readLock().lock();
- lock.readLock().unlock();
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
-
- /**
- * Fair Write lock succeeds if write locked by current thread even if
- * other threads are waiting for writelock
- */
- public void testWriteHoldingWriteLockFair4() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
- lock.writeLock().lock();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() {
- lock.writeLock().lock();
- lock.writeLock().unlock();
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.isWriteLockedByCurrentThread());
- assertTrue(lock.getWriteHoldCount() == 1);
- lock.writeLock().lock();
- assertTrue(lock.getWriteHoldCount() == 2);
- lock.writeLock().unlock();
- lock.writeLock().lock();
- lock.writeLock().unlock();
- lock.writeLock().unlock();
- t1.join(MEDIUM_DELAY_MS);
- t2.join(MEDIUM_DELAY_MS);
- assertTrue(!t1.isAlive());
- assertTrue(!t2.isAlive());
- }
-
-
- /**
- * Read tryLock succeeds if readlocked but not writelocked
- */
- public void testTryLockWhenReadLocked() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.readLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertTrue(lock.readLock().tryLock());
- lock.readLock().unlock();
- }});
-
- t.start();
- t.join();
- lock.readLock().unlock();
- }
-
-
-
- /**
- * write tryLock fails when readlocked
- */
- public void testWriteTryLockWhenReadLocked() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.readLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(lock.writeLock().tryLock());
- }});
-
- t.start();
- t.join();
- lock.readLock().unlock();
- }
-
-
- /**
- * Fair Read tryLock succeeds if readlocked but not writelocked
- */
- public void testTryLockWhenReadLockedFair() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
- lock.readLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertTrue(lock.readLock().tryLock());
- lock.readLock().unlock();
- }});
-
- t.start();
- t.join();
- lock.readLock().unlock();
- }
-
-
-
- /**
- * Fair write tryLock fails when readlocked
- */
- public void testWriteTryLockWhenReadLockedFair() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
- lock.readLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() {
- threadAssertFalse(lock.writeLock().tryLock());
- }});
-
- t.start();
- t.join();
- lock.readLock().unlock();
- }
-
-
-
- /**
- * write timed tryLock times out if locked
- */
- public void testWriteTryLock_Timeout() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(lock.writeLock().tryLock(1, MILLISECONDS));
- }});
-
- t.start();
- t.join();
- assertTrue(lock.writeLock().isHeldByCurrentThread());
- lock.writeLock().unlock();
- }
-
- /**
- * read timed tryLock times out if write-locked
- */
- public void testReadTryLock_Timeout() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lock();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- threadAssertFalse(lock.readLock().tryLock(1, MILLISECONDS));
- }});
-
- t.start();
- t.join();
- assertTrue(lock.writeLock().isHeldByCurrentThread());
- lock.writeLock().unlock();
- }
-
-
- /**
- * write lockInterruptibly succeeds if lock free else is interruptible
- */
- public void testWriteLockInterruptibly() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lockInterruptibly();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lockInterruptibly();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- t.join();
- lock.writeLock().unlock();
- }
-
- /**
- * read lockInterruptibly succeeds if lock free else is interruptible
- */
- public void testReadLockInterruptibly() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- lock.writeLock().lockInterruptibly();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.readLock().lockInterruptibly();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- lock.writeLock().unlock();
- }
-
- /**
- * Calling await without holding lock throws IllegalMonitorStateException
- */
- public void testAwait_IllegalMonitor() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- try {
- c.await();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * Calling signal without holding lock throws IllegalMonitorStateException
- */
- public void testSignal_IllegalMonitor() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- try {
- c.signal();
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
- /**
- * awaitNanos without a signal times out
- */
- public void testAwaitNanos_Timeout() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
-
- lock.writeLock().lock();
- long t = c.awaitNanos(100);
- assertTrue(t <= 0);
- lock.writeLock().unlock();
- }
-
-
- /**
- * timed await without a signal times out
- */
- public void testAwait_Timeout() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- lock.writeLock().lock();
- assertFalse(c.await(SHORT_DELAY_MS, MILLISECONDS));
- lock.writeLock().unlock();
- }
-
- /**
- * awaitUntil without a signal times out
- */
- public void testAwaitUntil_Timeout() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- lock.writeLock().lock();
- java.util.Date d = new java.util.Date();
- assertFalse(c.awaitUntil(new java.util.Date(d.getTime() + 10)));
- lock.writeLock().unlock();
- }
-
- /**
- * await returns when signalled
- */
- public void testAwait() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- c.await();
- lock.writeLock().unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- c.signal();
- lock.writeLock().unlock();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /** A helper class for uninterruptible wait tests */
- class UninterruptableThread extends Thread {
- private Lock lock;
- private Condition c;
-
- public volatile boolean canAwake = false;
- public volatile boolean interrupted = false;
- public volatile boolean lockStarted = false;
-
- public UninterruptableThread(Lock lock, Condition c) {
- this.lock = lock;
- this.c = c;
- }
-
- public synchronized void run() {
- lock.lock();
- lockStarted = true;
-
- while (!canAwake) {
- c.awaitUninterruptibly();
- }
-
- interrupted = isInterrupted();
- lock.unlock();
- }
- }
-
- /**
- * awaitUninterruptibly doesn't abort on interrupt
- */
- public void testAwaitUninterruptibly() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- UninterruptableThread thread = new UninterruptableThread(lock.writeLock(), c);
-
- thread.start();
-
- while (!thread.lockStarted) {
- Thread.sleep(100);
- }
-
- lock.writeLock().lock();
- try {
- thread.interrupt();
- thread.canAwake = true;
- c.signal();
- } finally {
- lock.writeLock().unlock();
- }
-
- thread.join();
- assertTrue(thread.interrupted);
- assertFalse(thread.isAlive());
- }
-
- /**
- * await is interruptible
- */
- public void testAwait_Interrupt() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- c.await();
- lock.writeLock().unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitNanos is interruptible
- */
- public void testAwaitNanos_Interrupt() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- c.awaitNanos(MILLISECONDS.toNanos(LONG_DELAY_MS));
- lock.writeLock().unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * awaitUntil is interruptible
- */
- public void testAwaitUntil_Interrupt() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- java.util.Date d = new java.util.Date();
- c.awaitUntil(new java.util.Date(d.getTime() + 10000));
- lock.writeLock().unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * signalAll wakes up all threads
- */
- public void testSignalAll() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- c.await();
- lock.writeLock().unlock();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- c.await();
- lock.writeLock().unlock();
- }});
-
- t1.start();
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- c.signalAll();
- lock.writeLock().unlock();
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * A serialized lock deserializes as unlocked
- */
- public void testSerialization() throws Exception {
- ReentrantReadWriteLock l = new ReentrantReadWriteLock();
- l.readLock().lock();
- l.readLock().unlock();
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- ReentrantReadWriteLock r = (ReentrantReadWriteLock) in.readObject();
- r.readLock().lock();
- r.readLock().unlock();
- }
-
- /**
- * hasQueuedThreads reports whether there are waiting threads
- */
- public void testhasQueuedThreads() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertFalse(lock.hasQueuedThreads());
- lock.writeLock().lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(lock.hasQueuedThreads());
- t1.join();
- t2.join();
- }
-
- /**
- * hasQueuedThread(null) throws NPE
- */
- public void testHasQueuedThreadNPE() {
- final ReentrantReadWriteLock sync = new ReentrantReadWriteLock();
- try {
- sync.hasQueuedThread(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * hasQueuedThread reports whether a thread is queued.
- */
- public void testHasQueuedThread() throws InterruptedException {
- final ReentrantReadWriteLock sync = new ReentrantReadWriteLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(sync));
- Thread t2 = new Thread(new InterruptibleLockRunnable(sync));
- assertFalse(sync.hasQueuedThread(t1));
- assertFalse(sync.hasQueuedThread(t2));
- sync.writeLock().lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThread(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(sync.hasQueuedThread(t1));
- assertTrue(sync.hasQueuedThread(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThread(t1));
- assertTrue(sync.hasQueuedThread(t2));
- sync.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThread(t1));
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(sync.hasQueuedThread(t2));
- t1.join();
- t2.join();
- }
-
-
- /**
- * getQueueLength reports number of waiting threads
- */
- public void testGetQueueLength() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertEquals(0, lock.getQueueLength());
- lock.writeLock().lock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, lock.getQueueLength());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, lock.getQueueLength());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueuedThreads includes waiting threads
- */
- public void testGetQueuedThreads() throws InterruptedException {
- final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertTrue(lock.getQueuedThreads().isEmpty());
- lock.writeLock().lock();
- assertTrue(lock.getQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().contains(t1));
- assertTrue(lock.getQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(lock.getQueuedThreads().contains(t1));
- assertTrue(lock.getQueuedThreads().contains(t2));
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * hasWaiters throws NPE if null
- */
- public void testHasWaitersNPE() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- try {
- lock.hasWaiters(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * getWaitQueueLength throws NPE if null
- */
- public void testGetWaitQueueLengthNPE() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- try {
- lock.getWaitQueueLength(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * getWaitingThreads throws NPE if null
- */
- public void testGetWaitingThreadsNPE() {
- final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
- try {
- lock.getWaitingThreads(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * hasWaiters throws IAE if not owned
- */
- public void testHasWaitersIAE() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- final ReentrantReadWriteLock lock2 = new ReentrantReadWriteLock();
- try {
- lock2.hasWaiters(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * hasWaiters throws IMSE if not locked
- */
- public void testHasWaitersIMSE() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- try {
- lock.hasWaiters(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitQueueLength throws IAE if not owned
- */
- public void testGetWaitQueueLengthIAE() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- final ReentrantReadWriteLock lock2 = new ReentrantReadWriteLock();
- try {
- lock2.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitQueueLength throws IMSE if not locked
- */
- public void testGetWaitQueueLengthIMSE() {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- try {
- lock.getWaitQueueLength(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * getWaitingThreads throws IAE if not owned
- */
- public void testGetWaitingThreadsIAE() {
- final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- final PublicReentrantReadWriteLock lock2 = new PublicReentrantReadWriteLock();
- try {
- lock2.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * getWaitingThreads throws IMSE if not locked
- */
- public void testGetWaitingThreadsIMSE() {
- final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- try {
- lock.getWaitingThreads(c);
- shouldThrow();
- } catch (IllegalMonitorStateException success) {}
- }
-
-
- /**
- * hasWaiters returns true when a thread is waiting, else false
- */
- public void testHasWaiters() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- threadAssertFalse(lock.hasWaiters(c));
- threadAssertEquals(0, lock.getWaitQueueLength(c));
- c.await();
- lock.writeLock().unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- assertTrue(lock.hasWaiters(c));
- assertEquals(1, lock.getWaitQueueLength(c));
- c.signal();
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- assertFalse(lock.hasWaiters(c));
- assertEquals(0, lock.getWaitQueueLength(c));
- lock.writeLock().unlock();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
- /**
- * getWaitQueueLength returns number of waiting threads
- */
- public void testGetWaitQueueLength() throws InterruptedException {
- final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- threadAssertFalse(lock.hasWaiters(c));
- threadAssertEquals(0, lock.getWaitQueueLength(c));
- c.await();
- lock.writeLock().unlock();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- assertTrue(lock.hasWaiters(c));
- assertEquals(1, lock.getWaitQueueLength(c));
- c.signal();
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- assertFalse(lock.hasWaiters(c));
- assertEquals(0, lock.getWaitQueueLength(c));
- lock.writeLock().unlock();
- t.join(SHORT_DELAY_MS);
- assertFalse(t.isAlive());
- }
-
-
- /**
- * getWaitingThreads returns only and all waiting threads
- */
- public void testGetWaitingThreads() throws InterruptedException {
- final PublicReentrantReadWriteLock lock = new PublicReentrantReadWriteLock();
- final Condition c = lock.writeLock().newCondition();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- threadAssertTrue(lock.getWaitingThreads(c).isEmpty());
- c.await();
- lock.writeLock().unlock();
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- lock.writeLock().lock();
- threadAssertFalse(lock.getWaitingThreads(c).isEmpty());
- c.await();
- lock.writeLock().unlock();
- }});
-
- lock.writeLock().lock();
- assertTrue(lock.getWaitingThreads(c).isEmpty());
- lock.writeLock().unlock();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- assertTrue(lock.hasWaiters(c));
- assertTrue(lock.getWaitingThreads(c).contains(t1));
- assertTrue(lock.getWaitingThreads(c).contains(t2));
- c.signalAll();
- lock.writeLock().unlock();
- Thread.sleep(SHORT_DELAY_MS);
- lock.writeLock().lock();
- assertFalse(lock.hasWaiters(c));
- assertTrue(lock.getWaitingThreads(c).isEmpty());
- lock.writeLock().unlock();
- t1.join(SHORT_DELAY_MS);
- t2.join(SHORT_DELAY_MS);
- assertFalse(t1.isAlive());
- assertFalse(t2.isAlive());
- }
-
- /**
- * toString indicates current lock state
- */
- public void testToString() {
- ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- String us = lock.toString();
- assertTrue(us.indexOf("Write locks = 0") >= 0);
- assertTrue(us.indexOf("Read locks = 0") >= 0);
- lock.writeLock().lock();
- String ws = lock.toString();
- assertTrue(ws.indexOf("Write locks = 1") >= 0);
- assertTrue(ws.indexOf("Read locks = 0") >= 0);
- lock.writeLock().unlock();
- lock.readLock().lock();
- lock.readLock().lock();
- String rs = lock.toString();
- assertTrue(rs.indexOf("Write locks = 0") >= 0);
- assertTrue(rs.indexOf("Read locks = 2") >= 0);
- }
-
- /**
- * readLock.toString indicates current lock state
- */
- public void testReadLockToString() {
- ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- String us = lock.readLock().toString();
- assertTrue(us.indexOf("Read locks = 0") >= 0);
- lock.readLock().lock();
- lock.readLock().lock();
- String rs = lock.readLock().toString();
- assertTrue(rs.indexOf("Read locks = 2") >= 0);
- }
-
- /**
- * writeLock.toString indicates current lock state
- */
- public void testWriteLockToString() {
- ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
- String us = lock.writeLock().toString();
- assertTrue(us.indexOf("Unlocked") >= 0);
- lock.writeLock().lock();
- String ls = lock.writeLock().toString();
- assertTrue(ls.indexOf("Locked") >= 0);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorSubclassTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorSubclassTest.java
deleted file mode 100644
index 21f4ced..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorSubclassTest.java
+++ /dev/null
@@ -1,1060 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.atomic.*;
-
-public class ScheduledExecutorSubclassTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ScheduledExecutorSubclassTest.class);
- }
-
- static class CustomTask<V> implements RunnableScheduledFuture<V> {
- RunnableScheduledFuture<V> task;
- volatile boolean ran;
- CustomTask(RunnableScheduledFuture<V> t) { task = t; }
- public boolean isPeriodic() { return task.isPeriodic(); }
- public void run() {
- ran = true;
- task.run();
- }
- public long getDelay(TimeUnit unit) { return task.getDelay(unit); }
- public int compareTo(Delayed t) {
- return task.compareTo(((CustomTask)t).task);
- }
- public boolean cancel(boolean mayInterruptIfRunning) {
- return task.cancel(mayInterruptIfRunning);
- }
- public boolean isCancelled() { return task.isCancelled(); }
- public boolean isDone() { return task.isDone(); }
- public V get() throws InterruptedException, ExecutionException {
- V v = task.get();
- assertTrue(ran);
- return v;
- }
- public V get(long time, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
- V v = task.get(time, unit);
- assertTrue(ran);
- return v;
- }
- }
-
-
- public class CustomExecutor extends ScheduledThreadPoolExecutor {
-
- protected <V> RunnableScheduledFuture<V> decorateTask(Runnable r, RunnableScheduledFuture<V> task) {
- return new CustomTask<V>(task);
- }
-
- protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> c, RunnableScheduledFuture<V> task) {
- return new CustomTask<V>(task);
- }
- CustomExecutor(int corePoolSize) { super(corePoolSize);}
- CustomExecutor(int corePoolSize, RejectedExecutionHandler handler) {
- super(corePoolSize, handler);
- }
-
- CustomExecutor(int corePoolSize, ThreadFactory threadFactory) {
- super(corePoolSize, threadFactory);
- }
- CustomExecutor(int corePoolSize, ThreadFactory threadFactory,
- RejectedExecutionHandler handler) {
- super(corePoolSize, threadFactory, handler);
- }
-
- }
-
-
- /**
- * execute successfully executes a runnable
- */
- public void testExecute() throws InterruptedException {
- TrackedShortRunnable runnable =new TrackedShortRunnable();
- CustomExecutor p1 = new CustomExecutor(1);
- p1.execute(runnable);
- assertFalse(runnable.done);
- Thread.sleep(SHORT_DELAY_MS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p1);
- }
-
-
- /**
- * delayed schedule of callable successfully executes after delay
- */
- public void testSchedule1() throws Exception {
- TrackedCallable callable = new TrackedCallable();
- CustomExecutor p1 = new CustomExecutor(1);
- Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(callable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(callable.done);
- assertEquals(Boolean.TRUE, f.get());
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p1);
- }
-
- /**
- * delayed schedule of runnable successfully executes after delay
- */
- public void testSchedule3() throws InterruptedException {
- TrackedShortRunnable runnable = new TrackedShortRunnable();
- CustomExecutor p1 = new CustomExecutor(1);
- p1.schedule(runnable, SMALL_DELAY_MS, MILLISECONDS);
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(runnable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p1);
- }
-
- /**
- * scheduleAtFixedRate executes runnable after given initial delay
- */
- public void testSchedule4() throws InterruptedException {
- TrackedShortRunnable runnable = new TrackedShortRunnable();
- CustomExecutor p1 = new CustomExecutor(1);
- ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(runnable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- h.cancel(true);
- joinPool(p1);
- }
-
- static class RunnableCounter implements Runnable {
- AtomicInteger count = new AtomicInteger(0);
- public void run() { count.getAndIncrement(); }
- }
-
- /**
- * scheduleWithFixedDelay executes runnable after given initial delay
- */
- public void testSchedule5() throws InterruptedException {
- TrackedShortRunnable runnable = new TrackedShortRunnable();
- CustomExecutor p1 = new CustomExecutor(1);
- ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(runnable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- h.cancel(true);
- joinPool(p1);
- }
-
- /**
- * scheduleAtFixedRate executes series of tasks at given rate
- */
- public void testFixedRateSequence() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- RunnableCounter counter = new RunnableCounter();
- ScheduledFuture h =
- p1.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
- Thread.sleep(SMALL_DELAY_MS);
- h.cancel(true);
- int c = counter.count.get();
- // By time scaling conventions, we must have at least
- // an execution per SHORT delay, but no more than one SHORT more
- assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
- assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
- joinPool(p1);
- }
-
- /**
- * scheduleWithFixedDelay executes series of tasks with given period
- */
- public void testFixedDelaySequence() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- RunnableCounter counter = new RunnableCounter();
- ScheduledFuture h =
- p1.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
- Thread.sleep(SMALL_DELAY_MS);
- h.cancel(true);
- int c = counter.count.get();
- assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
- assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
- joinPool(p1);
- }
-
-
- /**
- * execute (null) throws NPE
- */
- public void testExecuteNull() throws InterruptedException {
- CustomExecutor se = new CustomExecutor(1);
- try {
- se.execute(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- joinPool(se);
- }
-
- /**
- * schedule (null) throws NPE
- */
- public void testScheduleNull() throws InterruptedException {
- CustomExecutor se = new CustomExecutor(1);
- try {
- TrackedCallable callable = null;
- Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {}
- joinPool(se);
- }
-
- /**
- * execute throws RejectedExecutionException if shutdown
- */
- public void testSchedule1_RejectedExecutionException() {
- CustomExecutor se = new CustomExecutor(1);
- try {
- se.shutdown();
- se.schedule(new NoOpRunnable(),
- MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
-
- joinPool(se);
- }
-
- /**
- * schedule throws RejectedExecutionException if shutdown
- */
- public void testSchedule2_RejectedExecutionException() {
- CustomExecutor se = new CustomExecutor(1);
- try {
- se.shutdown();
- se.schedule(new NoOpCallable(),
- MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * schedule callable throws RejectedExecutionException if shutdown
- */
- public void testSchedule3_RejectedExecutionException() {
- CustomExecutor se = new CustomExecutor(1);
- try {
- se.shutdown();
- se.schedule(new NoOpCallable(),
- MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * scheduleAtFixedRate throws RejectedExecutionException if shutdown
- */
- public void testScheduleAtFixedRate1_RejectedExecutionException() {
- CustomExecutor se = new CustomExecutor(1);
- try {
- se.shutdown();
- se.scheduleAtFixedRate(new NoOpRunnable(),
- MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
- */
- public void testScheduleWithFixedDelay1_RejectedExecutionException() {
- CustomExecutor se = new CustomExecutor(1);
- try {
- se.shutdown();
- se.scheduleWithFixedDelay(new NoOpRunnable(),
- MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * getActiveCount increases but doesn't overestimate, when a
- * thread becomes active
- */
- public void testGetActiveCount() throws InterruptedException {
- CustomExecutor p2 = new CustomExecutor(2);
- assertEquals(0, p2.getActiveCount());
- p2.execute(new SmallRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, p2.getActiveCount());
- joinPool(p2);
- }
-
- /**
- * getCompletedTaskCount increases, but doesn't overestimate,
- * when tasks complete
- */
- public void testGetCompletedTaskCount() throws InterruptedException {
- CustomExecutor p2 = new CustomExecutor(2);
- assertEquals(0, p2.getCompletedTaskCount());
- p2.execute(new SmallRunnable());
- Thread.sleep(MEDIUM_DELAY_MS);
- assertEquals(1, p2.getCompletedTaskCount());
- joinPool(p2);
- }
-
- /**
- * getCorePoolSize returns size given in constructor if not otherwise set
- */
- public void testGetCorePoolSize() {
- CustomExecutor p1 = new CustomExecutor(1);
- assertEquals(1, p1.getCorePoolSize());
- joinPool(p1);
- }
-
- /**
- * getLargestPoolSize increases, but doesn't overestimate, when
- * multiple threads active
- */
- public void testGetLargestPoolSize() throws InterruptedException {
- CustomExecutor p2 = new CustomExecutor(2);
- assertEquals(0, p2.getLargestPoolSize());
- p2.execute(new SmallRunnable());
- p2.execute(new SmallRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, p2.getLargestPoolSize());
- joinPool(p2);
- }
-
- /**
- * getPoolSize increases, but doesn't overestimate, when threads
- * become active
- */
- public void testGetPoolSize() {
- CustomExecutor p1 = new CustomExecutor(1);
- assertEquals(0, p1.getPoolSize());
- p1.execute(new SmallRunnable());
- assertEquals(1, p1.getPoolSize());
- joinPool(p1);
- }
-
- /**
- * getTaskCount increases, but doesn't overestimate, when tasks
- * submitted
- */
- public void testGetTaskCount() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- assertEquals(0, p1.getTaskCount());
- for (int i = 0; i < 5; i++)
- p1.execute(new SmallRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(5, p1.getTaskCount());
- joinPool(p1);
- }
-
- /**
- * getThreadFactory returns factory in constructor if not set
- */
- public void testGetThreadFactory() {
- ThreadFactory tf = new SimpleThreadFactory();
- CustomExecutor p = new CustomExecutor(1, tf);
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
- /**
- * setThreadFactory sets the thread factory returned by getThreadFactory
- */
- public void testSetThreadFactory() {
- ThreadFactory tf = new SimpleThreadFactory();
- CustomExecutor p = new CustomExecutor(1);
- p.setThreadFactory(tf);
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
- /**
- * setThreadFactory(null) throws NPE
- */
- public void testSetThreadFactoryNull() {
- CustomExecutor p = new CustomExecutor(1);
- try {
- p.setThreadFactory(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * is isShutDown is false before shutdown, true after
- */
- public void testIsShutdown() {
- CustomExecutor p1 = new CustomExecutor(1);
- try {
- assertFalse(p1.isShutdown());
- }
- finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.isShutdown());
- }
-
-
- /**
- * isTerminated is false before termination, true after
- */
- public void testIsTerminated() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- try {
- p1.execute(new SmallRunnable());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- }
-
- /**
- * isTerminating is not true when running or when terminated
- */
- public void testIsTerminating() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- assertFalse(p1.isTerminating());
- try {
- p1.execute(new SmallRunnable());
- assertFalse(p1.isTerminating());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- assertFalse(p1.isTerminating());
- }
-
- /**
- * getQueue returns the work queue, which contains queued tasks
- */
- public void testGetQueue() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- BlockingQueue<Runnable> q = p1.getQueue();
- assertTrue(q.contains(tasks[4]));
- assertFalse(q.contains(tasks[0]));
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * remove(task) removes queued task, and fails to remove active task
- */
- public void testRemove() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- BlockingQueue<Runnable> q = p1.getQueue();
- assertFalse(p1.remove((Runnable)tasks[0]));
- assertTrue(q.contains((Runnable)tasks[4]));
- assertTrue(q.contains((Runnable)tasks[3]));
- assertTrue(p1.remove((Runnable)tasks[4]));
- assertFalse(p1.remove((Runnable)tasks[4]));
- assertFalse(q.contains((Runnable)tasks[4]));
- assertTrue(q.contains((Runnable)tasks[3]));
- assertTrue(p1.remove((Runnable)tasks[3]));
- assertFalse(q.contains((Runnable)tasks[3]));
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * purge removes cancelled tasks from the queue
- */
- public void testPurge() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- }
- try {
- int max = 5;
- if (tasks[4].cancel(true)) --max;
- if (tasks[3].cancel(true)) --max;
- // There must eventually be an interference-free point at
- // which purge will not fail. (At worst, when queue is empty.)
- int k;
- for (k = 0; k < SMALL_DELAY_MS; ++k) {
- p1.purge();
- long count = p1.getTaskCount();
- if (count >= 0 && count <= max)
- break;
- Thread.sleep(1);
- }
- assertTrue(k < SMALL_DELAY_MS);
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * shutDownNow returns a list containing tasks that were not run
- */
- public void testShutDownNow() {
- CustomExecutor p1 = new CustomExecutor(1);
- for (int i = 0; i < 5; i++)
- p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- List l;
- try {
- l = p1.shutdownNow();
- } catch (SecurityException ok) {
- return;
- }
- assertTrue(p1.isShutdown());
- assertTrue(l.size() > 0 && l.size() <= 5);
- joinPool(p1);
- }
-
- /**
- * In default setting, shutdown cancels periodic but not delayed
- * tasks at shutdown
- */
- public void testShutDown1() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
- assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());
-
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++)
- tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- BlockingQueue q = p1.getQueue();
- for (Iterator it = q.iterator(); it.hasNext();) {
- ScheduledFuture t = (ScheduledFuture)it.next();
- assertFalse(t.isCancelled());
- }
- assertTrue(p1.isShutdown());
- Thread.sleep(SMALL_DELAY_MS);
- for (int i = 0; i < 5; ++i) {
- assertTrue(tasks[i].isDone());
- assertFalse(tasks[i].isCancelled());
- }
- }
-
-
- /**
- * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
- * delayed tasks are cancelled at shutdown
- */
- public void testShutDown2() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++)
- tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(p1.isShutdown());
- BlockingQueue q = p1.getQueue();
- assertTrue(q.isEmpty());
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(p1.isTerminated());
- }
-
-
- /**
- * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
- * periodic tasks are not cancelled at shutdown
- */
- public void testShutDown3() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
- ScheduledFuture task =
- p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(p1.isShutdown());
- BlockingQueue q = p1.getQueue();
- assertTrue(q.isEmpty());
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(p1.isTerminated());
- }
-
- /**
- * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
- * periodic tasks are cancelled at shutdown
- */
- public void testShutDown4() throws InterruptedException {
- CustomExecutor p1 = new CustomExecutor(1);
- try {
- p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
- ScheduledFuture task =
- p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, MILLISECONDS);
- assertFalse(task.isCancelled());
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertFalse(task.isCancelled());
- assertFalse(p1.isTerminated());
- assertTrue(p1.isShutdown());
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(task.isCancelled());
- assertTrue(task.cancel(true));
- assertTrue(task.isDone());
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(p1.isTerminated());
- }
- finally {
- joinPool(p1);
- }
- }
-
- /**
- * completed submit of callable returns result
- */
- public void testSubmitCallable() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- Future<String> future = e.submit(new StringTask());
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of runnable returns successfully
- */
- public void testSubmitRunnable() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- Future<?> future = e.submit(new NoOpRunnable());
- future.get();
- assertTrue(future.isDone());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of (runnable, result) returns result
- */
- public void testSubmitRunnable2() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(null) throws NPE
- */
- public void testInvokeAny1() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- e.invokeAny(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(empty collection) throws IAE
- */
- public void testInvokeAny2() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- e.invokeAny(new ArrayList<Callable<String>>());
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws NPE if c has null elements
- */
- public void testInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws ExecutionException if no task completes
- */
- public void testInvokeAny4() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) returns result of some task
- */
- public void testInvokeAny5() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(null) throws NPE
- */
- public void testInvokeAll1() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- e.invokeAll(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(empty collection) returns empty collection
- */
- public void testInvokeAll2() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) throws NPE if c has null elements
- */
- public void testInvokeAll3() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of invokeAll(c) throws exception on failed task
- */
- public void testInvokeAll4() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) returns results of all completed tasks
- */
- public void testInvokeAll5() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(null) throws NPE
- */
- public void testTimedInvokeAny1() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(,,null) throws NPE
- */
- public void testTimedInvokeAnyNullTimeUnit() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(empty collection) throws IAE
- */
- public void testTimedInvokeAny2() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws ExecutionException if no task completes
- */
- public void testTimedInvokeAny4() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) returns result of some task
- */
- public void testTimedInvokeAny5() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(null) throws NPE
- */
- public void testTimedInvokeAll1() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(,,null) throws NPE
- */
- public void testTimedInvokeAllNullTimeUnit() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(empty collection) returns empty collection
- */
- public void testTimedInvokeAll2() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAll3() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of element of invokeAll(c) throws exception on failed task
- */
- public void testTimedInvokeAll4() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) returns results of all completed tasks
- */
- public void testTimedInvokeAll5() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) cancels tasks not completed by timeout
- */
- public void testTimedInvokeAll6() throws Exception {
- ExecutorService e = new CustomExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
- assertEquals(3, futures.size());
- Iterator<Future<String>> it = futures.iterator();
- Future<String> f1 = it.next();
- Future<String> f2 = it.next();
- Future<String> f3 = it.next();
- assertTrue(f1.isDone());
- assertTrue(f2.isDone());
- assertTrue(f3.isDone());
- assertFalse(f1.isCancelled());
- assertTrue(f2.isCancelled());
- } finally {
- joinPool(e);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java
deleted file mode 100755
index ff1796e..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java
+++ /dev/null
@@ -1,1012 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.atomic.*;
-
-public class ScheduledExecutorTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ScheduledExecutorTest.class);
- }
-
-
- /**
- * execute successfully executes a runnable
- */
- public void testExecute() throws InterruptedException {
- TrackedShortRunnable runnable =new TrackedShortRunnable();
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- p1.execute(runnable);
- assertFalse(runnable.done);
- Thread.sleep(SHORT_DELAY_MS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p1);
- }
-
-
- /**
- * delayed schedule of callable successfully executes after delay
- */
- public void testSchedule1() throws Exception {
- TrackedCallable callable = new TrackedCallable();
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- Future f = p1.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(callable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(callable.done);
- assertEquals(Boolean.TRUE, f.get());
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p1);
- }
-
- /**
- * delayed schedule of runnable successfully executes after delay
- */
- public void testSchedule3() throws InterruptedException {
- TrackedShortRunnable runnable = new TrackedShortRunnable();
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- p1.schedule(runnable, SMALL_DELAY_MS, MILLISECONDS);
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(runnable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p1);
- }
-
- /**
- * scheduleAtFixedRate executes runnable after given initial delay
- */
- public void testSchedule4() throws InterruptedException {
- TrackedShortRunnable runnable = new TrackedShortRunnable();
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- ScheduledFuture h = p1.scheduleAtFixedRate(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(runnable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- h.cancel(true);
- joinPool(p1);
- }
-
- static class RunnableCounter implements Runnable {
- AtomicInteger count = new AtomicInteger(0);
- public void run() { count.getAndIncrement(); }
- }
-
- /**
- * scheduleWithFixedDelay executes runnable after given initial delay
- */
- public void testSchedule5() throws InterruptedException {
- TrackedShortRunnable runnable = new TrackedShortRunnable();
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- ScheduledFuture h = p1.scheduleWithFixedDelay(runnable, SHORT_DELAY_MS, SHORT_DELAY_MS, MILLISECONDS);
- assertFalse(runnable.done);
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(runnable.done);
- h.cancel(true);
- joinPool(p1);
- }
-
- /**
- * scheduleAtFixedRate executes series of tasks at given rate
- */
- public void testFixedRateSequence() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- RunnableCounter counter = new RunnableCounter();
- ScheduledFuture h =
- p1.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
- Thread.sleep(SMALL_DELAY_MS);
- h.cancel(true);
- int c = counter.count.get();
- // By time scaling conventions, we must have at least
- // an execution per SHORT delay, but no more than one SHORT more
- assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
- assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
- joinPool(p1);
- }
-
- /**
- * scheduleWithFixedDelay executes series of tasks with given period
- */
- public void testFixedDelaySequence() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- RunnableCounter counter = new RunnableCounter();
- ScheduledFuture h =
- p1.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
- Thread.sleep(SMALL_DELAY_MS);
- h.cancel(true);
- int c = counter.count.get();
- assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
- assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
- joinPool(p1);
- }
-
-
- /**
- * execute (null) throws NPE
- */
- public void testExecuteNull() throws InterruptedException {
- ScheduledThreadPoolExecutor se = null;
- try {
- se = new ScheduledThreadPoolExecutor(1);
- se.execute(null);
- shouldThrow();
- } catch (NullPointerException success) {}
-
- joinPool(se);
- }
-
- /**
- * schedule (null) throws NPE
- */
- public void testScheduleNull() throws InterruptedException {
- ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
- try {
- TrackedCallable callable = null;
- Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {}
- joinPool(se);
- }
-
- /**
- * execute throws RejectedExecutionException if shutdown
- */
- public void testSchedule1_RejectedExecutionException() throws InterruptedException {
- ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
- try {
- se.shutdown();
- se.schedule(new NoOpRunnable(),
- MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
-
- joinPool(se);
- }
-
- /**
- * schedule throws RejectedExecutionException if shutdown
- */
- public void testSchedule2_RejectedExecutionException() throws InterruptedException {
- ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
- try {
- se.shutdown();
- se.schedule(new NoOpCallable(),
- MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * schedule callable throws RejectedExecutionException if shutdown
- */
- public void testSchedule3_RejectedExecutionException() throws InterruptedException {
- ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
- try {
- se.shutdown();
- se.schedule(new NoOpCallable(),
- MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * scheduleAtFixedRate throws RejectedExecutionException if shutdown
- */
- public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
- ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
- try {
- se.shutdown();
- se.scheduleAtFixedRate(new NoOpRunnable(),
- MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
- */
- public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
- ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
- try {
- se.shutdown();
- se.scheduleWithFixedDelay(new NoOpRunnable(),
- MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (RejectedExecutionException success) {
- } catch (SecurityException ok) {
- }
- joinPool(se);
- }
-
- /**
- * getActiveCount increases but doesn't overestimate, when a
- * thread becomes active
- */
- public void testGetActiveCount() throws InterruptedException {
- ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
- assertEquals(0, p2.getActiveCount());
- p2.execute(new SmallRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, p2.getActiveCount());
- joinPool(p2);
- }
-
- /**
- * getCompletedTaskCount increases, but doesn't overestimate,
- * when tasks complete
- */
- public void testGetCompletedTaskCount() throws InterruptedException {
- ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
- assertEquals(0, p2.getCompletedTaskCount());
- p2.execute(new SmallRunnable());
- Thread.sleep(MEDIUM_DELAY_MS);
- assertEquals(1, p2.getCompletedTaskCount());
- joinPool(p2);
- }
-
- /**
- * getCorePoolSize returns size given in constructor if not otherwise set
- */
- public void testGetCorePoolSize() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- assertEquals(1, p1.getCorePoolSize());
- joinPool(p1);
- }
-
- /**
- * getLargestPoolSize increases, but doesn't overestimate, when
- * multiple threads active
- */
- public void testGetLargestPoolSize() throws InterruptedException {
- ScheduledThreadPoolExecutor p2 = new ScheduledThreadPoolExecutor(2);
- assertEquals(0, p2.getLargestPoolSize());
- p2.execute(new SmallRunnable());
- p2.execute(new SmallRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, p2.getLargestPoolSize());
- joinPool(p2);
- }
-
- /**
- * getPoolSize increases, but doesn't overestimate, when threads
- * become active
- */
- public void testGetPoolSize() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- assertEquals(0, p1.getPoolSize());
- p1.execute(new SmallRunnable());
- assertEquals(1, p1.getPoolSize());
- joinPool(p1);
- }
-
- /**
- * getTaskCount increases, but doesn't overestimate, when tasks
- * submitted
- */
- public void testGetTaskCount() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- assertEquals(0, p1.getTaskCount());
- for (int i = 0; i < 5; i++)
- p1.execute(new SmallRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(5, p1.getTaskCount());
- joinPool(p1);
- }
-
- /**
- * getThreadFactory returns factory in constructor if not set
- */
- public void testGetThreadFactory() throws InterruptedException {
- ThreadFactory tf = new SimpleThreadFactory();
- ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
- /**
- * setThreadFactory sets the thread factory returned by getThreadFactory
- */
- public void testSetThreadFactory() throws InterruptedException {
- ThreadFactory tf = new SimpleThreadFactory();
- ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
- p.setThreadFactory(tf);
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
- /**
- * setThreadFactory(null) throws NPE
- */
- public void testSetThreadFactoryNull() throws InterruptedException {
- ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
- try {
- p.setThreadFactory(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * is isShutDown is false before shutdown, true after
- */
- public void testIsShutdown() {
-
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- try {
- assertFalse(p1.isShutdown());
- }
- finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.isShutdown());
- }
-
-
- /**
- * isTerminated is false before termination, true after
- */
- public void testIsTerminated() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- try {
- p1.execute(new SmallRunnable());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- }
-
- /**
- * isTerminating is not true when running or when terminated
- */
- public void testIsTerminating() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- assertFalse(p1.isTerminating());
- try {
- p1.execute(new SmallRunnable());
- assertFalse(p1.isTerminating());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
-
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- assertFalse(p1.isTerminating());
- }
-
- /**
- * getQueue returns the work queue, which contains queued tasks
- */
- public void testGetQueue() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- BlockingQueue<Runnable> q = p1.getQueue();
- assertTrue(q.contains(tasks[4]));
- assertFalse(q.contains(tasks[0]));
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * remove(task) removes queued task, and fails to remove active task
- */
- public void testRemove() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), 1, MILLISECONDS);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- BlockingQueue<Runnable> q = p1.getQueue();
- assertFalse(p1.remove((Runnable)tasks[0]));
- assertTrue(q.contains((Runnable)tasks[4]));
- assertTrue(q.contains((Runnable)tasks[3]));
- assertTrue(p1.remove((Runnable)tasks[4]));
- assertFalse(p1.remove((Runnable)tasks[4]));
- assertFalse(q.contains((Runnable)tasks[4]));
- assertTrue(q.contains((Runnable)tasks[3]));
- assertTrue(p1.remove((Runnable)tasks[3]));
- assertFalse(q.contains((Runnable)tasks[3]));
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * purge removes cancelled tasks from the queue
- */
- public void testPurge() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- }
- try {
- int max = 5;
- if (tasks[4].cancel(true)) --max;
- if (tasks[3].cancel(true)) --max;
- // There must eventually be an interference-free point at
- // which purge will not fail. (At worst, when queue is empty.)
- int k;
- for (k = 0; k < SMALL_DELAY_MS; ++k) {
- p1.purge();
- long count = p1.getTaskCount();
- if (count >= 0 && count <= max)
- break;
- Thread.sleep(1);
- }
- assertTrue(k < SMALL_DELAY_MS);
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * shutDownNow returns a list containing tasks that were not run
- */
- public void testShutDownNow() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- for (int i = 0; i < 5; i++)
- p1.schedule(new SmallPossiblyInterruptedRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- List l;
- try {
- l = p1.shutdownNow();
- } catch (SecurityException ok) {
- return;
- }
- assertTrue(p1.isShutdown());
- assertTrue(l.size() > 0 && l.size() <= 5);
- joinPool(p1);
- }
-
- /**
- * In default setting, shutdown cancels periodic but not delayed
- * tasks at shutdown
- */
- public void testShutDown1() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- assertTrue(p1.getExecuteExistingDelayedTasksAfterShutdownPolicy());
- assertFalse(p1.getContinueExistingPeriodicTasksAfterShutdownPolicy());
-
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++)
- tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- BlockingQueue q = p1.getQueue();
- for (Iterator it = q.iterator(); it.hasNext();) {
- ScheduledFuture t = (ScheduledFuture)it.next();
- assertFalse(t.isCancelled());
- }
- assertTrue(p1.isShutdown());
- Thread.sleep(SMALL_DELAY_MS);
- for (int i = 0; i < 5; ++i) {
- assertTrue(tasks[i].isDone());
- assertFalse(tasks[i].isCancelled());
- }
- }
-
-
- /**
- * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
- * delayed tasks are cancelled at shutdown
- */
- public void testShutDown2() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- p1.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
- ScheduledFuture[] tasks = new ScheduledFuture[5];
- for (int i = 0; i < 5; i++)
- tasks[i] = p1.schedule(new NoOpRunnable(), SHORT_DELAY_MS, MILLISECONDS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(p1.isShutdown());
- BlockingQueue q = p1.getQueue();
- assertTrue(q.isEmpty());
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(p1.isTerminated());
- }
-
-
- /**
- * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
- * periodic tasks are not cancelled at shutdown
- */
- public void testShutDown3() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
- ScheduledFuture task =
- p1.scheduleAtFixedRate(new NoOpRunnable(), 5, 5, MILLISECONDS);
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(p1.isShutdown());
- BlockingQueue q = p1.getQueue();
- assertTrue(q.isEmpty());
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(p1.isTerminated());
- }
-
- /**
- * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
- * periodic tasks are cancelled at shutdown
- */
- public void testShutDown4() throws InterruptedException {
- ScheduledThreadPoolExecutor p1 = new ScheduledThreadPoolExecutor(1);
- try {
- p1.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
- ScheduledFuture task =
- p1.scheduleAtFixedRate(new NoOpRunnable(), 1, 1, MILLISECONDS);
- assertFalse(task.isCancelled());
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertFalse(task.isCancelled());
- assertFalse(p1.isTerminated());
- assertTrue(p1.isShutdown());
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(task.isCancelled());
- assertTrue(task.cancel(true));
- assertTrue(task.isDone());
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(p1.isTerminated());
- }
- finally {
- joinPool(p1);
- }
- }
-
- /**
- * completed submit of callable returns result
- */
- public void testSubmitCallable() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- Future<String> future = e.submit(new StringTask());
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of runnable returns successfully
- */
- public void testSubmitRunnable() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- Future<?> future = e.submit(new NoOpRunnable());
- future.get();
- assertTrue(future.isDone());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of (runnable, result) returns result
- */
- public void testSubmitRunnable2() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(null) throws NPE
- */
- public void testInvokeAny1() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- e.invokeAny(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(empty collection) throws IAE
- */
- public void testInvokeAny2() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- e.invokeAny(new ArrayList<Callable<String>>());
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws NPE if c has null elements
- */
- public void testInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws ExecutionException if no task completes
- */
- public void testInvokeAny4() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) returns result of some task
- */
- public void testInvokeAny5() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(null) throws NPE
- */
- public void testInvokeAll1() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- e.invokeAll(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(empty collection) returns empty collection
- */
- public void testInvokeAll2() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) throws NPE if c has null elements
- */
- public void testInvokeAll3() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of invokeAll(c) throws exception on failed task
- */
- public void testInvokeAll4() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) returns results of all completed tasks
- */
- public void testInvokeAll5() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(null) throws NPE
- */
- public void testTimedInvokeAny1() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(,,null) throws NPE
- */
- public void testTimedInvokeAnyNullTimeUnit() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(empty collection) throws IAE
- */
- public void testTimedInvokeAny2() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws ExecutionException if no task completes
- */
- public void testTimedInvokeAny4() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) returns result of some task
- */
- public void testTimedInvokeAny5() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(null) throws NPE
- */
- public void testTimedInvokeAll1() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(,,null) throws NPE
- */
- public void testTimedInvokeAllNullTimeUnit() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(empty collection) returns empty collection
- */
- public void testTimedInvokeAll2() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAll3() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of element of invokeAll(c) throws exception on failed task
- */
- public void testTimedInvokeAll4() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) returns results of all completed tasks
- */
- public void testTimedInvokeAll5() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) cancels tasks not completed by timeout
- */
- public void testTimedInvokeAll6() throws Exception {
- ExecutorService e = new ScheduledThreadPoolExecutor(2);
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
- assertEquals(3, futures.size());
- Iterator<Future<String>> it = futures.iterator();
- Future<String> f1 = it.next();
- Future<String> f2 = it.next();
- Future<String> f3 = it.next();
- assertTrue(f1.isDone());
- assertTrue(f2.isDone());
- assertTrue(f3.isDone());
- assertFalse(f1.isCancelled());
- assertTrue(f2.isCancelled());
- } finally {
- joinPool(e);
- }
- }
-
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java b/luni/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java
deleted file mode 100755
index c27893c..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java
+++ /dev/null
@@ -1,765 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-
-public class SemaphoreTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(SemaphoreTest.class);
- }
-
- /**
- * Subclass to expose protected methods
- */
- static class PublicSemaphore extends Semaphore {
- PublicSemaphore(int p, boolean f) { super(p, f); }
- public Collection<Thread> getQueuedThreads() {
- return super.getQueuedThreads();
- }
- public void reducePermits(int p) {
- super.reducePermits(p);
- }
- }
-
- /**
- * A runnable calling acquire
- */
- class InterruptibleLockRunnable extends CheckedRunnable {
- final Semaphore lock;
- InterruptibleLockRunnable(Semaphore l) { lock = l; }
- public void realRun() {
- try {
- lock.acquire();
- }
- catch (InterruptedException ignored) {}
- }
- }
-
-
- /**
- * A runnable calling acquire that expects to be interrupted
- */
- class InterruptedLockRunnable extends CheckedInterruptedRunnable {
- final Semaphore lock;
- InterruptedLockRunnable(Semaphore l) { lock = l; }
- public void realRun() throws InterruptedException {
- lock.acquire();
- }
- }
-
- /**
- * Zero, negative, and positive initial values are allowed in constructor
- */
- public void testConstructor() {
- for (int permits : new int[] { -1, 0, 1 }) {
- for (boolean fair : new boolean[] { false, true }) {
- Semaphore s = new Semaphore(permits, fair);
- assertEquals(permits, s.availablePermits());
- assertEquals(fair, s.isFair());
- }
- }
- }
-
- /**
- * Constructor without fairness argument behaves as nonfair
- */
- public void testConstructor2() {
- for (int permits : new int[] { -1, 0, 1 }) {
- Semaphore s = new Semaphore(permits);
- assertEquals(permits, s.availablePermits());
- assertFalse(s.isFair());
- }
- }
-
- /**
- * tryAcquire succeeds when sufficient permits, else fails
- */
- public void testTryAcquireInSameThread() {
- Semaphore s = new Semaphore(2, false);
- assertEquals(2, s.availablePermits());
- assertTrue(s.tryAcquire());
- assertTrue(s.tryAcquire());
- assertEquals(0, s.availablePermits());
- assertFalse(s.tryAcquire());
- }
-
- /**
- * Acquire and release of semaphore succeed if initially available
- */
- public void testAcquireReleaseInSameThread()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, false);
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * Uninterruptible acquire and release of semaphore succeed if
- * initially available
- */
- public void testAcquireUninterruptiblyReleaseInSameThread()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, false);
- s.acquireUninterruptibly();
- s.release();
- s.acquireUninterruptibly();
- s.release();
- s.acquireUninterruptibly();
- s.release();
- s.acquireUninterruptibly();
- s.release();
- s.acquireUninterruptibly();
- s.release();
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * Timed Acquire and release of semaphore succeed if
- * initially available
- */
- public void testTimedAcquireReleaseInSameThread()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, false);
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * A release in one thread enables an acquire in another thread
- */
- public void testAcquireReleaseInDifferentThreads()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, false);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire();
- s.release();
- s.release();
- s.acquire();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- s.release();
- s.release();
- s.acquire();
- s.acquire();
- s.release();
- t.join();
- }
-
- /**
- * A release in one thread enables an uninterruptible acquire in another thread
- */
- public void testUninterruptibleAcquireReleaseInDifferentThreads()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, false);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquireUninterruptibly();
- s.release();
- s.release();
- s.acquireUninterruptibly();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- s.release();
- s.release();
- s.acquireUninterruptibly();
- s.acquireUninterruptibly();
- s.release();
- t.join();
- }
-
-
- /**
- * A release in one thread enables a timed acquire in another thread
- */
- public void testTimedAcquireReleaseInDifferentThreads()
- throws InterruptedException {
- final Semaphore s = new Semaphore(1, false);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- }});
-
- t.start();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- s.release();
- t.join();
- }
-
- /**
- * A waiting acquire blocks interruptibly
- */
- public void testAcquire_InterruptedException()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, false);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * A waiting timed acquire blocks interruptibly
- */
- public void testTryAcquire_InterruptedException()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, false);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- s.tryAcquire(MEDIUM_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * hasQueuedThreads reports whether there are waiting threads
- */
- public void testHasQueuedThreads() throws InterruptedException {
- final Semaphore lock = new Semaphore(1, false);
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertFalse(lock.hasQueuedThreads());
- lock.acquireUninterruptibly();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.hasQueuedThreads());
- lock.release();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(lock.hasQueuedThreads());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueueLength reports number of waiting threads
- */
- public void testGetQueueLength() throws InterruptedException {
- final Semaphore lock = new Semaphore(1, false);
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertEquals(0, lock.getQueueLength());
- lock.acquireUninterruptibly();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, lock.getQueueLength());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- lock.release();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, lock.getQueueLength());
- t1.join();
- t2.join();
- }
-
- /**
- * getQueuedThreads includes waiting threads
- */
- public void testGetQueuedThreads() throws InterruptedException {
- final PublicSemaphore lock = new PublicSemaphore(1, false);
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertTrue(lock.getQueuedThreads().isEmpty());
- lock.acquireUninterruptibly();
- assertTrue(lock.getQueuedThreads().isEmpty());
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().contains(t1));
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().contains(t1));
- assertTrue(lock.getQueuedThreads().contains(t2));
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(lock.getQueuedThreads().contains(t1));
- assertTrue(lock.getQueuedThreads().contains(t2));
- lock.release();
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(lock.getQueuedThreads().isEmpty());
- t1.join();
- t2.join();
- }
-
- /**
- * drainPermits reports and removes given number of permits
- */
- public void testDrainPermits() {
- Semaphore s = new Semaphore(0, false);
- assertEquals(0, s.availablePermits());
- assertEquals(0, s.drainPermits());
- s.release(10);
- assertEquals(10, s.availablePermits());
- assertEquals(10, s.drainPermits());
- assertEquals(0, s.availablePermits());
- assertEquals(0, s.drainPermits());
- }
-
- /**
- * reducePermits reduces number of permits
- */
- public void testReducePermits() {
- PublicSemaphore s = new PublicSemaphore(10, false);
- assertEquals(10, s.availablePermits());
- s.reducePermits(1);
- assertEquals(9, s.availablePermits());
- s.reducePermits(10);
- assertEquals(-1, s.availablePermits());
- }
-
- /**
- * a deserialized serialized semaphore has same number of permits
- */
- public void testSerialization() throws Exception {
- Semaphore l = new Semaphore(3, false);
- l.acquire();
- l.release();
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- Semaphore r = (Semaphore) in.readObject();
- assertEquals(3, r.availablePermits());
- assertFalse(r.isFair());
- r.acquire();
- r.release();
- }
-
-
- /**
- * Zero, negative, and positive initial values are allowed in constructor
- */
- public void testConstructor_fair() {
- Semaphore s0 = new Semaphore(0, true);
- assertEquals(0, s0.availablePermits());
- assertTrue(s0.isFair());
- Semaphore s1 = new Semaphore(-1, true);
- assertEquals(-1, s1.availablePermits());
- Semaphore s2 = new Semaphore(-1, true);
- assertEquals(-1, s2.availablePermits());
- }
-
- /**
- * tryAcquire succeeds when sufficient permits, else fails
- */
- public void testTryAcquireInSameThread_fair() {
- Semaphore s = new Semaphore(2, true);
- assertEquals(2, s.availablePermits());
- assertTrue(s.tryAcquire());
- assertTrue(s.tryAcquire());
- assertEquals(0, s.availablePermits());
- assertFalse(s.tryAcquire());
- }
-
- /**
- * tryAcquire(n) succeeds when sufficient permits, else fails
- */
- public void testTryAcquireNInSameThread_fair() {
- Semaphore s = new Semaphore(2, true);
- assertEquals(2, s.availablePermits());
- assertTrue(s.tryAcquire(2));
- assertEquals(0, s.availablePermits());
- assertFalse(s.tryAcquire());
- }
-
- /**
- * Acquire and release of semaphore succeed if initially available
- */
- public void testAcquireReleaseInSameThread_fair()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, true);
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- s.acquire();
- s.release();
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * Acquire(n) and release(n) of semaphore succeed if initially available
- */
- public void testAcquireReleaseNInSameThread_fair()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, true);
- s.release(1);
- s.acquire(1);
- s.release(2);
- s.acquire(2);
- s.release(3);
- s.acquire(3);
- s.release(4);
- s.acquire(4);
- s.release(5);
- s.acquire(5);
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * Acquire(n) and release(n) of semaphore succeed if initially available
- */
- public void testAcquireUninterruptiblyReleaseNInSameThread_fair() {
- Semaphore s = new Semaphore(1, true);
- s.release(1);
- s.acquireUninterruptibly(1);
- s.release(2);
- s.acquireUninterruptibly(2);
- s.release(3);
- s.acquireUninterruptibly(3);
- s.release(4);
- s.acquireUninterruptibly(4);
- s.release(5);
- s.acquireUninterruptibly(5);
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * release(n) in one thread enables timed acquire(n) in another thread
- */
- public void testTimedAcquireReleaseNInSameThread_fair()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, true);
- s.release(1);
- assertTrue(s.tryAcquire(1, SHORT_DELAY_MS, MILLISECONDS));
- s.release(2);
- assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, MILLISECONDS));
- s.release(3);
- assertTrue(s.tryAcquire(3, SHORT_DELAY_MS, MILLISECONDS));
- s.release(4);
- assertTrue(s.tryAcquire(4, SHORT_DELAY_MS, MILLISECONDS));
- s.release(5);
- assertTrue(s.tryAcquire(5, SHORT_DELAY_MS, MILLISECONDS));
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * release in one thread enables timed acquire in another thread
- */
- public void testTimedAcquireReleaseInSameThread_fair()
- throws InterruptedException {
- Semaphore s = new Semaphore(1, true);
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- s.release();
- assertEquals(1, s.availablePermits());
- }
-
- /**
- * A release in one thread enables an acquire in another thread
- */
- public void testAcquireReleaseInDifferentThreads_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire();
- s.acquire();
- s.acquire();
- s.acquire();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- s.release();
- s.release();
- s.release();
- s.release();
- s.release();
- s.release();
- t.join();
- assertEquals(2, s.availablePermits());
- }
-
- /**
- * release(n) in one thread enables acquire(n) in another thread
- */
- public void testAcquireReleaseNInDifferentThreads_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire();
- s.release(2);
- s.acquire();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- s.release(2);
- s.acquire(2);
- s.release(1);
- t.join();
- }
-
- /**
- * release(n) in one thread enables acquire(n) in another thread
- */
- public void testAcquireReleaseNInDifferentThreads_fair2()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire(2);
- s.acquire(2);
- s.release(4);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- s.release(6);
- s.acquire(2);
- s.acquire(2);
- s.release(2);
- t.join();
- }
-
-
- /**
- * release in one thread enables timed acquire in another thread
- */
- public void testTimedAcquireReleaseInDifferentThreads_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(1, true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- assertTrue(s.tryAcquire(SHORT_DELAY_MS, MILLISECONDS));
- }});
-
- t.start();
- s.release();
- s.release();
- s.release();
- s.release();
- s.release();
- t.join();
- }
-
- /**
- * release(n) in one thread enables timed acquire(n) in another thread
- */
- public void testTimedAcquireReleaseNInDifferentThreads_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(2, true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, MILLISECONDS));
- s.release(2);
- assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, MILLISECONDS));
- s.release(2);
- }});
-
- t.start();
- assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, MILLISECONDS));
- s.release(2);
- assertTrue(s.tryAcquire(2, SHORT_DELAY_MS, MILLISECONDS));
- s.release(2);
- t.join();
- }
-
- /**
- * A waiting acquire blocks interruptibly
- */
- public void testAcquire_InterruptedException_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, true);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * A waiting acquire(n) blocks interruptibly
- */
- public void testAcquireN_InterruptedException_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(2, true);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- s.acquire(3);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * A waiting tryAcquire blocks interruptibly
- */
- public void testTryAcquire_InterruptedException_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(0, true);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- s.tryAcquire(MEDIUM_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * A waiting tryAcquire(n) blocks interruptibly
- */
- public void testTryAcquireN_InterruptedException_fair()
- throws InterruptedException {
- final Semaphore s = new Semaphore(1, true);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- s.tryAcquire(4, MEDIUM_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * getQueueLength reports number of waiting threads
- */
- public void testGetQueueLength_fair() throws InterruptedException {
- final Semaphore lock = new Semaphore(1, true);
- Thread t1 = new Thread(new InterruptedLockRunnable(lock));
- Thread t2 = new Thread(new InterruptibleLockRunnable(lock));
- assertEquals(0, lock.getQueueLength());
- lock.acquireUninterruptibly();
- t1.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- t2.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, lock.getQueueLength());
- t1.interrupt();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, lock.getQueueLength());
- lock.release();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, lock.getQueueLength());
- t1.join();
- t2.join();
- }
-
-
- /**
- * a deserialized serialized semaphore has same number of permits
- */
- public void testSerialization_fair() throws Exception {
- Semaphore l = new Semaphore(3, true);
-
- l.acquire();
- l.release();
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(l);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- Semaphore r = (Semaphore) in.readObject();
- assertEquals(3, r.availablePermits());
- assertTrue(r.isFair());
- r.acquire();
- r.release();
- }
-
- /**
- * toString indicates current number of permits
- */
- public void testToString() {
- Semaphore s = new Semaphore(0);
- String us = s.toString();
- assertTrue(us.indexOf("Permits = 0") >= 0);
- s.release();
- String s1 = s.toString();
- assertTrue(s1.indexOf("Permits = 1") >= 0);
- s.release();
- String s2 = s.toString();
- assertTrue(s2.indexOf("Permits = 2") >= 0);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java b/luni/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java
deleted file mode 100755
index 9393c5c..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java
+++ /dev/null
@@ -1,727 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.*;
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.io.*;
-
-public class SynchronousQueueTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(SynchronousQueueTest.class);
- }
-
- /**
- * A SynchronousQueue is both empty and full
- */
- public void testEmptyFull() {
- SynchronousQueue q = new SynchronousQueue();
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertEquals(0, q.remainingCapacity());
- assertFalse(q.offer(zero));
- }
-
- /**
- * A fair SynchronousQueue is both empty and full
- */
- public void testFairEmptyFull() {
- SynchronousQueue q = new SynchronousQueue(true);
- assertTrue(q.isEmpty());
- assertEquals(0, q.size());
- assertEquals(0, q.remainingCapacity());
- assertFalse(q.offer(zero));
- }
-
- /**
- * offer(null) throws NPE
- */
- public void testOfferNull() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- q.offer(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * add(null) throws NPE
- */
- public void testAddNull() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- q.add(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * offer fails if no active taker
- */
- public void testOffer() {
- SynchronousQueue q = new SynchronousQueue();
- assertFalse(q.offer(one));
- }
-
- /**
- * add throws ISE if no active taker
- */
- public void testAdd() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- assertEquals(0, q.remainingCapacity());
- q.add(one);
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * addAll(null) throws NPE
- */
- public void testAddAll1() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- q.addAll(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * addAll(this) throws IAE
- */
- public void testAddAllSelf() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- q.addAll(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * addAll of a collection with null elements throws NPE
- */
- public void testAddAll2() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- Integer[] ints = new Integer[1];
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (NullPointerException success) {}
- }
- /**
- * addAll throws ISE if no active taker
- */
- public void testAddAll4() {
- try {
- SynchronousQueue q = new SynchronousQueue();
- Integer[] ints = new Integer[1];
- for (int i = 0; i < 1; ++i)
- ints[i] = new Integer(i);
- q.addAll(Arrays.asList(ints));
- shouldThrow();
- } catch (IllegalStateException success) {}
- }
-
- /**
- * put(null) throws NPE
- */
- public void testPutNull() throws InterruptedException {
- try {
- SynchronousQueue q = new SynchronousQueue();
- q.put(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * put blocks interruptibly if no active taker
- */
- public void testBlockingPut() throws InterruptedException {
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- SynchronousQueue q = new SynchronousQueue();
- q.put(zero);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * put blocks waiting for take
- */
- public void testPutWithTake() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- int added = 0;
- try {
- while (true) {
- q.put(added);
- ++added;
- }
- } catch (InterruptedException success) {
- assertTrue(added == 1);
- }
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed offer times out if elements not taken
- */
- public void testTimedOffer() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(q.offer(new Object(), SHORT_DELAY_MS, MILLISECONDS));
- q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * take blocks interruptibly when empty
- */
- public void testTakeFromEmpty() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- q.take();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * put blocks interruptibly if no active taker
- */
- public void testFairBlockingPut() throws InterruptedException {
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- SynchronousQueue q = new SynchronousQueue(true);
- q.put(zero);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * put blocks waiting for take
- */
- public void testFairPutWithTake() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue(true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- int added = 0;
- try {
- while (true) {
- q.put(added);
- ++added;
- }
- } catch (InterruptedException success) {
- assertTrue(added == 1);
- }
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(0, q.take());
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed offer times out if elements not taken
- */
- public void testFairTimedOffer() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue(true);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(q.offer(new Object(), SHORT_DELAY_MS, MILLISECONDS));
- q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * take blocks interruptibly when empty
- */
- public void testFairTakeFromEmpty() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue(true);
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- q.take();
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * poll fails unless active taker
- */
- public void testPoll() {
- SynchronousQueue q = new SynchronousQueue();
- assertNull(q.poll());
- }
-
- /**
- * timed pool with zero timeout times out if no active taker
- */
- public void testTimedPoll0() throws InterruptedException {
- SynchronousQueue q = new SynchronousQueue();
- assertNull(q.poll(0, MILLISECONDS));
- }
-
- /**
- * timed pool with nonzero timeout times out if no active taker
- */
- public void testTimedPoll() throws InterruptedException {
- SynchronousQueue q = new SynchronousQueue();
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testInterruptedTimedPoll() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testTimedPollWithOffer() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
- /**
- * Interrupted timed poll throws InterruptedException instead of
- * returning timeout status
- */
- public void testFairInterruptedTimedPoll() throws InterruptedException {
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- SynchronousQueue q = new SynchronousQueue(true);
- q.poll(SMALL_DELAY_MS, MILLISECONDS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timed poll before a delayed offer fails; after offer succeeds;
- * on interruption throws
- */
- public void testFairTimedPollWithOffer() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue(true);
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
- assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
- try {
- q.poll(LONG_DELAY_MS, MILLISECONDS);
- threadShouldThrow();
- } catch (InterruptedException success) {}
- }});
-
- t.start();
- Thread.sleep(SMALL_DELAY_MS);
- assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
- t.interrupt();
- t.join();
- }
-
-
- /**
- * peek returns null
- */
- public void testPeek() {
- SynchronousQueue q = new SynchronousQueue();
- assertNull(q.peek());
- }
-
- /**
- * element throws NSEE
- */
- public void testElement() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- q.element();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove throws NSEE if no active taker
- */
- public void testRemove() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- q.remove();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * remove(x) returns false
- */
- public void testRemoveElement() {
- SynchronousQueue q = new SynchronousQueue();
- assertFalse(q.remove(zero));
- assertTrue(q.isEmpty());
- }
-
- /**
- * contains returns false
- */
- public void testContains() {
- SynchronousQueue q = new SynchronousQueue();
- assertFalse(q.contains(zero));
- }
-
- /**
- * clear ensures isEmpty
- */
- public void testClear() {
- SynchronousQueue q = new SynchronousQueue();
- q.clear();
- assertTrue(q.isEmpty());
- }
-
- /**
- * containsAll returns false unless empty
- */
- public void testContainsAll() {
- SynchronousQueue q = new SynchronousQueue();
- Integer[] empty = new Integer[0];
- assertTrue(q.containsAll(Arrays.asList(empty)));
- Integer[] ints = new Integer[1]; ints[0] = zero;
- assertFalse(q.containsAll(Arrays.asList(ints)));
- }
-
- /**
- * retainAll returns false
- */
- public void testRetainAll() {
- SynchronousQueue q = new SynchronousQueue();
- Integer[] empty = new Integer[0];
- assertFalse(q.retainAll(Arrays.asList(empty)));
- Integer[] ints = new Integer[1]; ints[0] = zero;
- assertFalse(q.retainAll(Arrays.asList(ints)));
- }
-
- /**
- * removeAll returns false
- */
- public void testRemoveAll() {
- SynchronousQueue q = new SynchronousQueue();
- Integer[] empty = new Integer[0];
- assertFalse(q.removeAll(Arrays.asList(empty)));
- Integer[] ints = new Integer[1]; ints[0] = zero;
- assertFalse(q.containsAll(Arrays.asList(ints)));
- }
-
-
- /**
- * toArray is empty
- */
- public void testToArray() {
- SynchronousQueue q = new SynchronousQueue();
- Object[] o = q.toArray();
- assertEquals(o.length, 0);
- }
-
- /**
- * toArray(a) is nulled at position 0
- */
- public void testToArray2() {
- SynchronousQueue q = new SynchronousQueue();
- Integer[] ints = new Integer[1];
- assertNull(ints[0]);
- }
-
- /**
- * toArray(null) throws NPE
- */
- public void testToArray_BadArg() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- Object o[] = q.toArray(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * iterator does not traverse any elements
- */
- public void testIterator() {
- SynchronousQueue q = new SynchronousQueue();
- Iterator it = q.iterator();
- assertFalse(it.hasNext());
- try {
- Object x = it.next();
- shouldThrow();
- } catch (NoSuchElementException success) {}
- }
-
- /**
- * iterator remove throws ISE
- */
- public void testIteratorRemove() {
- SynchronousQueue q = new SynchronousQueue();
- Iterator it = q.iterator();
- try {
- it.remove();
- shouldThrow();
- } catch (IllegalStateException success) {
- } catch (UnsupportedOperationException success) { // android-added
- }
- }
-
- /**
- * toString returns a non-null string
- */
- public void testToString() {
- SynchronousQueue q = new SynchronousQueue();
- String s = q.toString();
- assertNotNull(s);
- }
-
-
- /**
- * offer transfers elements across Executor tasks
- */
- public void testOfferInExecutor() {
- final SynchronousQueue q = new SynchronousQueue();
- ExecutorService executor = Executors.newFixedThreadPool(2);
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertFalse(q.offer(one));
- assertTrue(q.offer(one, MEDIUM_DELAY_MS, MILLISECONDS));
- assertEquals(0, q.remainingCapacity());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SMALL_DELAY_MS);
- assertSame(one, q.take());
- }});
-
- joinPool(executor);
- }
-
- /**
- * poll retrieves elements across Executor threads
- */
- public void testPollInExecutor() {
- final SynchronousQueue q = new SynchronousQueue();
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- assertNull(q.poll());
- assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
- assertTrue(q.isEmpty());
- }});
-
- executor.execute(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(SHORT_DELAY_MS);
- q.put(one);
- }});
-
- joinPool(executor);
- }
-
- /**
- * a deserialized serialized queue is usable
- */
- public void testSerialization() throws Exception {
- SynchronousQueue q = new SynchronousQueue();
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- SynchronousQueue r = (SynchronousQueue)in.readObject();
- assertEquals(q.size(), r.size());
- while (!q.isEmpty())
- assertEquals(q.remove(), r.remove());
- }
-
- /**
- * drainTo(null) throws NPE
- */
- public void testDrainToNull() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- q.drainTo(null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this) throws IAE
- */
- public void testDrainToSelf() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- q.drainTo(q);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c) of empty queue doesn't transfer elements
- */
- public void testDrainTo() {
- SynchronousQueue q = new SynchronousQueue();
- ArrayList l = new ArrayList();
- q.drainTo(l);
- assertEquals(q.size(), 0);
- assertEquals(l.size(), 0);
- }
-
- /**
- * drainTo empties queue, unblocking a waiting put.
- */
- public void testDrainToWithActivePut() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(new Integer(1));
- }});
-
- t.start();
- ArrayList l = new ArrayList();
- Thread.sleep(SHORT_DELAY_MS);
- q.drainTo(l);
- assertTrue(l.size() <= 1);
- if (l.size() > 0)
- assertEquals(l.get(0), new Integer(1));
- t.join();
- assertTrue(l.size() <= 1);
- }
-
- /**
- * drainTo(null, n) throws NPE
- */
- public void testDrainToNullN() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- q.drainTo(null, 0);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * drainTo(this, n) throws IAE
- */
- public void testDrainToSelfN() {
- SynchronousQueue q = new SynchronousQueue();
- try {
- q.drainTo(q, 0);
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * drainTo(c, n) empties up to n elements of queue into c
- */
- public void testDrainToN() throws InterruptedException {
- final SynchronousQueue q = new SynchronousQueue();
- Thread t1 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(one);
- }});
-
- Thread t2 = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- q.put(two);
- }});
-
- t1.start();
- t2.start();
- ArrayList l = new ArrayList();
- Thread.sleep(SHORT_DELAY_MS);
- q.drainTo(l, 1);
- assertTrue(l.size() == 1);
- q.drainTo(l, 1);
- assertTrue(l.size() == 2);
- assertTrue(l.contains(one));
- assertTrue(l.contains(two));
- t1.join();
- t2.join();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/SystemTest.java b/luni/src/test/java/tests/api/java/util/concurrent/SystemTest.java
deleted file mode 100644
index e906186..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/SystemTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-
-public class SystemTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(SystemTest.class);
- }
-
- /**
- * Worst case rounding for millisecs; set for 60 cycle millis clock.
- * This value might need to be changed on JVMs with coarser
- * System.currentTimeMillis clocks.
- */
- static final long MILLIS_ROUND = 17;
-
- /**
- * Nanos between readings of millis is no longer than millis (plus
- * possible rounding).
- * This shows only that nano timing not (much) worse than milli.
- */
- public void testNanoTime1() throws InterruptedException {
- long m1 = System.currentTimeMillis();
- Thread.sleep(1);
- long n1 = System.nanoTime();
- Thread.sleep(SHORT_DELAY_MS);
- long n2 = System.nanoTime();
- Thread.sleep(1);
- long m2 = System.currentTimeMillis();
- long millis = m2 - m1;
- long nanos = n2 - n1;
- assertTrue(nanos >= 0);
- long nanosAsMillis = nanos / 1000000;
- assertTrue(nanosAsMillis <= millis + MILLIS_ROUND);
- }
-
- /**
- * Millis between readings of nanos is less than nanos, adjusting
- * for rounding.
- * This shows only that nano timing not (much) worse than milli.
- */
- public void testNanoTime2() throws InterruptedException {
- long n1 = System.nanoTime();
- Thread.sleep(1);
- long m1 = System.currentTimeMillis();
- Thread.sleep(SHORT_DELAY_MS);
- long m2 = System.currentTimeMillis();
- Thread.sleep(1);
- long n2 = System.nanoTime();
- long millis = m2 - m1;
- long nanos = n2 - n1;
-
- assertTrue(nanos >= 0);
- long nanosAsMillis = nanos / 1000000;
- assertTrue(millis <= nanosAsMillis + MILLIS_ROUND);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java
deleted file mode 100644
index d54bce0..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.Semaphore;
-
-public class ThreadLocalTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ThreadLocalTest.class);
- }
-
- static ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
- public Integer initialValue() {
- return one;
- }
- };
-
- static InheritableThreadLocal<Integer> itl =
- new InheritableThreadLocal<Integer>() {
- protected Integer initialValue() {
- return zero;
- }
-
- protected Integer childValue(Integer parentValue) {
- return new Integer(parentValue.intValue() + 1);
- }
- };
-
- /**
- * remove causes next access to return initial value
- */
- public void testRemove() {
- assertSame(tl.get(), one);
- tl.set(two);
- assertSame(tl.get(), two);
- tl.remove();
- assertSame(tl.get(), one);
- }
-
- /**
- * remove in InheritableThreadLocal causes next access to return
- * initial value
- */
- public void testRemoveITL() {
- assertSame(itl.get(), zero);
- itl.set(two);
- assertSame(itl.get(), two);
- itl.remove();
- assertSame(itl.get(), zero);
- }
-
- private class ITLThread extends Thread {
- final int[] x;
- ITLThread(int[] array) { x = array; }
- public void run() {
- Thread child = null;
- if (itl.get().intValue() < x.length - 1) {
- child = new ITLThread(x);
- child.start();
- }
- Thread.currentThread().yield();
-
- int threadId = itl.get().intValue();
- for (int j = 0; j < threadId; j++) {
- x[threadId]++;
- Thread.currentThread().yield();
- }
-
- if (child != null) { // Wait for child (if any)
- try {
- child.join();
- } catch (InterruptedException e) {
- threadUnexpectedException(e);
- }
- }
- }
- }
-
- /**
- * InheritableThreadLocal propagates generic values.
- */
- public void testGenericITL() throws InterruptedException {
- final int threadCount = 10;
- final int x[] = new int[threadCount];
- Thread progenitor = new ITLThread(x);
- progenitor.start();
- progenitor.join();
- for (int i = 0; i < threadCount; i++) {
- assertEquals(i, x[i]);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorSubclassTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorSubclassTest.java
deleted file mode 100644
index 911a35f..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorSubclassTest.java
+++ /dev/null
@@ -1,1578 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.locks.*;
-
-import junit.framework.*;
-import java.util.*;
-
-public class ThreadPoolExecutorSubclassTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ThreadPoolExecutorSubclassTest.class);
- }
-
- static class CustomTask<V> implements RunnableFuture<V> {
- final Callable<V> callable;
- final ReentrantLock lock = new ReentrantLock();
- final Condition cond = lock.newCondition();
- boolean done;
- boolean cancelled;
- V result;
- Thread thread;
- Exception exception;
- CustomTask(Callable<V> c) {
- if (c == null) throw new NullPointerException();
- callable = c;
- }
- CustomTask(final Runnable r, final V res) {
- if (r == null) throw new NullPointerException();
- callable = new Callable<V>() {
- public V call() throws Exception { r.run(); return res; }};
- }
- public boolean isDone() {
- lock.lock(); try { return done; } finally { lock.unlock() ; }
- }
- public boolean isCancelled() {
- lock.lock(); try { return cancelled; } finally { lock.unlock() ; }
- }
- public boolean cancel(boolean mayInterrupt) {
- lock.lock();
- try {
- if (!done) {
- cancelled = true;
- done = true;
- if (mayInterrupt && thread != null)
- thread.interrupt();
- return true;
- }
- return false;
- }
- finally { lock.unlock() ; }
- }
- public void run() {
- boolean runme;
- lock.lock();
- try {
- runme = !done;
- if (!runme)
- thread = Thread.currentThread();
- }
- finally { lock.unlock() ; }
- if (!runme) return;
- V v = null;
- Exception e = null;
- try {
- v = callable.call();
- }
- catch (Exception ex) {
- e = ex;
- }
- lock.lock();
- try {
- result = v;
- exception = e;
- done = true;
- thread = null;
- cond.signalAll();
- }
- finally { lock.unlock(); }
- }
- public V get() throws InterruptedException, ExecutionException {
- lock.lock();
- try {
- while (!done)
- cond.await();
- if (exception != null)
- throw new ExecutionException(exception);
- return result;
- }
- finally { lock.unlock(); }
- }
- public V get(long timeout, TimeUnit unit)
- throws InterruptedException, ExecutionException, TimeoutException {
- long nanos = unit.toNanos(timeout);
- lock.lock();
- try {
- for (;;) {
- if (done) break;
- if (nanos < 0)
- throw new TimeoutException();
- nanos = cond.awaitNanos(nanos);
- }
- if (exception != null)
- throw new ExecutionException(exception);
- return result;
- }
- finally { lock.unlock(); }
- }
- }
-
-
- static class CustomTPE extends ThreadPoolExecutor {
- protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
- return new CustomTask<V>(c);
- }
- protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
- return new CustomTask<V>(r, v);
- }
-
- CustomTPE(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue) {
- super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
- workQueue);
- }
- CustomTPE(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue,
- ThreadFactory threadFactory) {
- super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
- threadFactory);
- }
-
- CustomTPE(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue,
- RejectedExecutionHandler handler) {
- super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
- handler);
- }
- CustomTPE(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue,
- ThreadFactory threadFactory,
- RejectedExecutionHandler handler) {
- super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
- workQueue, threadFactory, handler);
- }
-
- volatile boolean beforeCalled = false;
- volatile boolean afterCalled = false;
- volatile boolean terminatedCalled = false;
- public CustomTPE() {
- super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
- }
- protected void beforeExecute(Thread t, Runnable r) {
- beforeCalled = true;
- }
- protected void afterExecute(Runnable r, Throwable t) {
- afterCalled = true;
- }
- protected void terminated() {
- terminatedCalled = true;
- }
-
- }
-
- static class FailingThreadFactory implements ThreadFactory {
- int calls = 0;
- public Thread newThread(Runnable r) {
- if (++calls > 1) return null;
- return new Thread(r);
- }
- }
-
-
- /**
- * execute successfully executes a runnable
- */
- public void testExecute() throws InterruptedException {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- p1.execute(new ShortRunnable());
- Thread.sleep(SMALL_DELAY_MS);
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * getActiveCount increases but doesn't overestimate, when a
- * thread becomes active
- */
- public void testGetActiveCount() throws InterruptedException {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getActiveCount());
- p2.execute(new MediumRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, p2.getActiveCount());
- joinPool(p2);
- }
-
- /**
- * prestartCoreThread starts a thread if under corePoolSize, else doesn't
- */
- public void testPrestartCoreThread() {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getPoolSize());
- assertTrue(p2.prestartCoreThread());
- assertEquals(1, p2.getPoolSize());
- assertTrue(p2.prestartCoreThread());
- assertEquals(2, p2.getPoolSize());
- assertFalse(p2.prestartCoreThread());
- assertEquals(2, p2.getPoolSize());
- joinPool(p2);
- }
-
- /**
- * prestartAllCoreThreads starts all corePoolSize threads
- */
- public void testPrestartAllCoreThreads() {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getPoolSize());
- p2.prestartAllCoreThreads();
- assertEquals(2, p2.getPoolSize());
- p2.prestartAllCoreThreads();
- assertEquals(2, p2.getPoolSize());
- joinPool(p2);
- }
-
- /**
- * getCompletedTaskCount increases, but doesn't overestimate,
- * when tasks complete
- */
- public void testGetCompletedTaskCount() throws InterruptedException {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getCompletedTaskCount());
- p2.execute(new ShortRunnable());
- Thread.sleep(SMALL_DELAY_MS);
- assertEquals(1, p2.getCompletedTaskCount());
- try { p2.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p2);
- }
-
- /**
- * getCorePoolSize returns size given in constructor if not otherwise set
- */
- public void testGetCorePoolSize() {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(1, p1.getCorePoolSize());
- joinPool(p1);
- }
-
- /**
- * getKeepAliveTime returns value given in constructor if not otherwise set
- */
- public void testGetKeepAliveTime() {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(1, p2.getKeepAliveTime(TimeUnit.SECONDS));
- joinPool(p2);
- }
-
-
- /**
- * getThreadFactory returns factory in constructor if not set
- */
- public void testGetThreadFactory() {
- ThreadFactory tf = new SimpleThreadFactory();
- ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), tf, new NoOpREHandler());
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
- /**
- * setThreadFactory sets the thread factory returned by getThreadFactory
- */
- public void testSetThreadFactory() {
- ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- ThreadFactory tf = new SimpleThreadFactory();
- p.setThreadFactory(tf);
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
-
- /**
- * setThreadFactory(null) throws NPE
- */
- public void testSetThreadFactoryNull() {
- ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- p.setThreadFactory(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * getRejectedExecutionHandler returns handler in constructor if not set
- */
- public void testGetRejectedExecutionHandler() {
- RejectedExecutionHandler h = new NoOpREHandler();
- ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), h);
- assertSame(h, p.getRejectedExecutionHandler());
- joinPool(p);
- }
-
- /**
- * setRejectedExecutionHandler sets the handler returned by
- * getRejectedExecutionHandler
- */
- public void testSetRejectedExecutionHandler() {
- ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- RejectedExecutionHandler h = new NoOpREHandler();
- p.setRejectedExecutionHandler(h);
- assertSame(h, p.getRejectedExecutionHandler());
- joinPool(p);
- }
-
-
- /**
- * setRejectedExecutionHandler(null) throws NPE
- */
- public void testSetRejectedExecutionHandlerNull() {
- ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- p.setRejectedExecutionHandler(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * getLargestPoolSize increases, but doesn't overestimate, when
- * multiple threads active
- */
- public void testGetLargestPoolSize() throws InterruptedException {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getLargestPoolSize());
- p2.execute(new MediumRunnable());
- p2.execute(new MediumRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, p2.getLargestPoolSize());
- joinPool(p2);
- }
-
- /**
- * getMaximumPoolSize returns value given in constructor if not
- * otherwise set
- */
- public void testGetMaximumPoolSize() {
- ThreadPoolExecutor p2 = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(2, p2.getMaximumPoolSize());
- joinPool(p2);
- }
-
- /**
- * getPoolSize increases, but doesn't overestimate, when threads
- * become active
- */
- public void testGetPoolSize() {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p1.getPoolSize());
- p1.execute(new MediumRunnable());
- assertEquals(1, p1.getPoolSize());
- joinPool(p1);
- }
-
- /**
- * getTaskCount increases, but doesn't overestimate, when tasks submitted
- */
- public void testGetTaskCount() throws InterruptedException {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p1.getTaskCount());
- p1.execute(new MediumRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, p1.getTaskCount());
- joinPool(p1);
- }
-
- /**
- * isShutDown is false before shutdown, true after
- */
- public void testIsShutdown() {
-
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(p1.isShutdown());
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(p1.isShutdown());
- joinPool(p1);
- }
-
-
- /**
- * isTerminated is false before termination, true after
- */
- public void testIsTerminated() throws InterruptedException {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(p1.isTerminated());
- try {
- p1.execute(new MediumRunnable());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- }
-
- /**
- * isTerminating is not true when running or when terminated
- */
- public void testIsTerminating() throws InterruptedException {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(p1.isTerminating());
- try {
- p1.execute(new SmallRunnable());
- assertFalse(p1.isTerminating());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- assertFalse(p1.isTerminating());
- }
-
- /**
- * getQueue returns the work queue, which contains queued tasks
- */
- public void testGetQueue() throws InterruptedException {
- BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, q);
- FutureTask[] tasks = new FutureTask[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
- p1.execute(tasks[i]);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- BlockingQueue<Runnable> wq = p1.getQueue();
- assertSame(q, wq);
- assertFalse(wq.contains(tasks[0]));
- assertTrue(wq.contains(tasks[4]));
- for (int i = 1; i < 5; ++i)
- tasks[i].cancel(true);
- p1.shutdownNow();
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * remove(task) removes queued task, and fails to remove active task
- */
- public void testRemove() throws InterruptedException {
- BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, q);
- FutureTask[] tasks = new FutureTask[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
- p1.execute(tasks[i]);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(p1.remove(tasks[0]));
- assertTrue(q.contains(tasks[4]));
- assertTrue(q.contains(tasks[3]));
- assertTrue(p1.remove(tasks[4]));
- assertFalse(p1.remove(tasks[4]));
- assertFalse(q.contains(tasks[4]));
- assertTrue(q.contains(tasks[3]));
- assertTrue(p1.remove(tasks[3]));
- assertFalse(q.contains(tasks[3]));
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * purge removes cancelled tasks from the queue
- */
- public void testPurge() {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- FutureTask[] tasks = new FutureTask[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
- p1.execute(tasks[i]);
- }
- tasks[4].cancel(true);
- tasks[3].cancel(true);
- p1.purge();
- long count = p1.getTaskCount();
- assertTrue(count >= 2 && count < 5);
- joinPool(p1);
- }
-
- /**
- * shutDownNow returns a list containing tasks that were not run
- */
- public void testShutDownNow() {
- ThreadPoolExecutor p1 = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List l;
- try {
- for (int i = 0; i < 5; i++)
- p1.execute(new MediumPossiblyInterruptedRunnable());
- }
- finally {
- try {
- l = p1.shutdownNow();
- } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.isShutdown());
- assertTrue(l.size() <= 4);
- }
-
- // Exception Tests
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor1() {
- try {
- new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor2() {
- try {
- new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor3() {
- try {
- new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor4() {
- try {
- new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor5() {
- try {
- new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException() {
- try {
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor6() {
- try {
- new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor7() {
- try {
- new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor8() {
- try {
- new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor9() {
- try {
- new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor10() {
- try {
- new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException2() {
- try {
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if threadFactory is set to null
- */
- public void testConstructorNullPointerException3() {
- try {
- ThreadFactory f = null;
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),f);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor11() {
- try {
- new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor12() {
- try {
- new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor13() {
- try {
- new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor14() {
- try {
- new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor15() {
- try {
- new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException4() {
- try {
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new NoOpREHandler());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if handler is set to null
- */
- public void testConstructorNullPointerException5() {
- try {
- RejectedExecutionHandler r = null;
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),r);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor16() {
- try {
- new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor17() {
- try {
- new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor18() {
- try {
- new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor19() {
- try {
- new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor20() {
- try {
- new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException6() {
- try {
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if handler is set to null
- */
- public void testConstructorNullPointerException7() {
- try {
- RejectedExecutionHandler r = null;
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),r);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if ThreadFactory is set top null
- */
- public void testConstructorNullPointerException8() {
- try {
- ThreadFactory f = null;
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),f,new NoOpREHandler());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * execute throws RejectedExecutionException
- * if saturated.
- */
- public void testSaturatedExecute() {
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
- try {
-
- for (int i = 0; i < 5; ++i) {
- p.execute(new MediumRunnable());
- }
- shouldThrow();
- } catch (RejectedExecutionException success) {}
- joinPool(p);
- }
-
- /**
- * executor using CallerRunsPolicy runs task if saturated.
- */
- public void testSaturatedExecute2() {
- RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
- try {
-
- TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
- for (int i = 0; i < 5; ++i) {
- tasks[i] = new TrackedNoOpRunnable();
- }
- TrackedLongRunnable mr = new TrackedLongRunnable();
- p.execute(mr);
- for (int i = 0; i < 5; ++i) {
- p.execute(tasks[i]);
- }
- for (int i = 1; i < 5; ++i) {
- assertTrue(tasks[i].done);
- }
- try { p.shutdownNow(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * executor using DiscardPolicy drops task if saturated.
- */
- public void testSaturatedExecute3() {
- RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
- try {
-
- TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
- for (int i = 0; i < 5; ++i) {
- tasks[i] = new TrackedNoOpRunnable();
- }
- p.execute(new TrackedLongRunnable());
- for (int i = 0; i < 5; ++i) {
- p.execute(tasks[i]);
- }
- for (int i = 0; i < 5; ++i) {
- assertFalse(tasks[i].done);
- }
- try { p.shutdownNow(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * executor using DiscardOldestPolicy drops oldest task if saturated.
- */
- public void testSaturatedExecute4() {
- RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
- try {
- p.execute(new TrackedLongRunnable());
- TrackedLongRunnable r2 = new TrackedLongRunnable();
- p.execute(r2);
- assertTrue(p.getQueue().contains(r2));
- TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
- p.execute(r3);
- assertFalse(p.getQueue().contains(r2));
- assertTrue(p.getQueue().contains(r3));
- try { p.shutdownNow(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * execute throws RejectedExecutionException if shutdown
- */
- public void testRejectedExecutionExceptionOnShutdown() {
- ThreadPoolExecutor tpe =
- new CustomTPE(1,1,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(1));
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- try {
- tpe.execute(new NoOpRunnable());
- shouldThrow();
- } catch (RejectedExecutionException success) {}
-
- joinPool(tpe);
- }
-
- /**
- * execute using CallerRunsPolicy drops task on shutdown
- */
- public void testCallerRunsOnShutdown() {
- RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
-
- try { p.shutdown(); } catch (SecurityException ok) { return; }
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- p.execute(r);
- assertFalse(r.done);
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * execute using DiscardPolicy drops task on shutdown
- */
- public void testDiscardOnShutdown() {
- RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
-
- try { p.shutdown(); } catch (SecurityException ok) { return; }
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- p.execute(r);
- assertFalse(r.done);
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * execute using DiscardOldestPolicy drops task on shutdown
- */
- public void testDiscardOldestOnShutdown() {
- RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
- ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
-
- try { p.shutdown(); } catch (SecurityException ok) { return; }
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- p.execute(r);
- assertFalse(r.done);
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * execute (null) throws NPE
- */
- public void testExecuteNull() {
- ThreadPoolExecutor tpe = null;
- try {
- tpe = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
- tpe.execute(null);
- shouldThrow();
- } catch (NullPointerException success) {}
-
- joinPool(tpe);
- }
-
- /**
- * setCorePoolSize of negative value throws IllegalArgumentException
- */
- public void testCorePoolSizeIllegalArgumentException() {
- ThreadPoolExecutor tpe =
- new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setCorePoolSize(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
- /**
- * setMaximumPoolSize(int) throws IllegalArgumentException if
- * given a value less the core pool size
- */
- public void testMaximumPoolSizeIllegalArgumentException() {
- ThreadPoolExecutor tpe =
- new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setMaximumPoolSize(1);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
- /**
- * setMaximumPoolSize throws IllegalArgumentException
- * if given a negative value
- */
- public void testMaximumPoolSizeIllegalArgumentException2() {
- ThreadPoolExecutor tpe =
- new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setMaximumPoolSize(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
-
- /**
- * setKeepAliveTime throws IllegalArgumentException
- * when given a negative value
- */
- public void testKeepAliveTimeIllegalArgumentException() {
- ThreadPoolExecutor tpe =
- new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
-
- try {
- tpe.setKeepAliveTime(-1,MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
- /**
- * terminated() is called on termination
- */
- public void testTerminated() {
- CustomTPE tpe = new CustomTPE();
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(tpe.terminatedCalled);
- joinPool(tpe);
- }
-
- /**
- * beforeExecute and afterExecute are called when executing task
- */
- public void testBeforeAfter() throws InterruptedException {
- CustomTPE tpe = new CustomTPE();
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- tpe.execute(r);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(r.done);
- assertTrue(tpe.beforeCalled);
- assertTrue(tpe.afterCalled);
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(tpe);
- }
- }
-
- /**
- * completed submit of callable returns result
- */
- public void testSubmitCallable() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- Future<String> future = e.submit(new StringTask());
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of runnable returns successfully
- */
- public void testSubmitRunnable() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- Future<?> future = e.submit(new NoOpRunnable());
- future.get();
- assertTrue(future.isDone());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of (runnable, result) returns result
- */
- public void testSubmitRunnable2() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
-
- /**
- * invokeAny(null) throws NPE
- */
- public void testInvokeAny1() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(empty collection) throws IAE
- */
- public void testInvokeAny2() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(new ArrayList<Callable<String>>());
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws NPE if c has null elements
- */
- public void testInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws ExecutionException if no task completes
- */
- public void testInvokeAny4() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) returns result of some task
- */
- public void testInvokeAny5() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(null) throws NPE
- */
- public void testInvokeAll1() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAll(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(empty collection) returns empty collection
- */
- public void testInvokeAll2() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) throws NPE if c has null elements
- */
- public void testInvokeAll3() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of element of invokeAll(c) throws exception on failed task
- */
- public void testInvokeAll4() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) returns results of all completed tasks
- */
- public void testInvokeAll5() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
-
-
- /**
- * timed invokeAny(null) throws NPE
- */
- public void testTimedInvokeAny1() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(,,null) throws NPE
- */
- public void testTimedInvokeAnyNullTimeUnit() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(empty collection) throws IAE
- */
- public void testTimedInvokeAny2() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws ExecutionException if no task completes
- */
- public void testTimedInvokeAny4() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) returns result of some task
- */
- public void testTimedInvokeAny5() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(null) throws NPE
- */
- public void testTimedInvokeAll1() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(,,null) throws NPE
- */
- public void testTimedInvokeAllNullTimeUnit() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(empty collection) returns empty collection
- */
- public void testTimedInvokeAll2() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAll3() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of element of invokeAll(c) throws exception on failed task
- */
- public void testTimedInvokeAll4() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) returns results of all completed tasks
- */
- public void testTimedInvokeAll5() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) cancels tasks not completed by timeout
- */
- public void testTimedInvokeAll6() throws Exception {
- ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
- assertEquals(3, futures.size());
- Iterator<Future<String>> it = futures.iterator();
- Future<String> f1 = it.next();
- Future<String> f2 = it.next();
- Future<String> f3 = it.next();
- assertTrue(f1.isDone());
- assertTrue(f2.isDone());
- assertTrue(f3.isDone());
- assertFalse(f1.isCancelled());
- assertTrue(f2.isCancelled());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * Execution continues if there is at least one thread even if
- * thread factory fails to create more
- */
- public void testFailingThreadFactory() throws InterruptedException {
- ExecutorService e = new CustomTPE(100, 100, LONG_DELAY_MS, MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new FailingThreadFactory());
- try {
- for (int k = 0; k < 100; ++k) {
- e.execute(new NoOpRunnable());
- }
- Thread.sleep(LONG_DELAY_MS);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * allowsCoreThreadTimeOut is by default false.
- */
- public void testAllowsCoreThreadTimeOut() {
- ThreadPoolExecutor tpe = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(tpe.allowsCoreThreadTimeOut());
- joinPool(tpe);
- }
-
- /**
- * allowCoreThreadTimeOut(true) causes idle threads to time out
- */
- public void testAllowCoreThreadTimeOut_true() throws InterruptedException {
- ThreadPoolExecutor tpe = new CustomTPE(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- tpe.allowCoreThreadTimeOut(true);
- tpe.execute(new NoOpRunnable());
- try {
- Thread.sleep(MEDIUM_DELAY_MS);
- assertEquals(0, tpe.getPoolSize());
- } finally {
- joinPool(tpe);
- }
- }
-
- /**
- * allowCoreThreadTimeOut(false) causes idle threads not to time out
- */
- public void testAllowCoreThreadTimeOut_false() throws InterruptedException {
- ThreadPoolExecutor tpe = new CustomTPE(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- tpe.allowCoreThreadTimeOut(false);
- tpe.execute(new NoOpRunnable());
- try {
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(tpe.getPoolSize() >= 1);
- } finally {
- joinPool(tpe);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java
deleted file mode 100755
index b706185..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java
+++ /dev/null
@@ -1,1511 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import java.util.concurrent.*;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import java.util.concurrent.atomic.*;
-import junit.framework.*;
-import java.util.*;
-
-public class ThreadPoolExecutorTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ThreadPoolExecutorTest.class);
- }
-
- static class ExtendedTPE extends ThreadPoolExecutor {
- volatile boolean beforeCalled = false;
- volatile boolean afterCalled = false;
- volatile boolean terminatedCalled = false;
- public ExtendedTPE() {
- super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
- }
- protected void beforeExecute(Thread t, Runnable r) {
- beforeCalled = true;
- }
- protected void afterExecute(Runnable r, Throwable t) {
- afterCalled = true;
- }
- protected void terminated() {
- terminatedCalled = true;
- }
- }
-
- static class FailingThreadFactory implements ThreadFactory {
- int calls = 0;
- public Thread newThread(Runnable r) {
- if (++calls > 1) return null;
- return new Thread(r);
- }
- }
-
-
- /**
- * execute successfully executes a runnable
- */
- public void testExecute() throws InterruptedException {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- p1.execute(new ShortRunnable());
- Thread.sleep(SMALL_DELAY_MS);
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * getActiveCount increases but doesn't overestimate, when a
- * thread becomes active
- */
- public void testGetActiveCount() throws InterruptedException {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getActiveCount());
- p2.execute(new MediumRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, p2.getActiveCount());
- joinPool(p2);
- }
-
- /**
- * prestartCoreThread starts a thread if under corePoolSize, else doesn't
- */
- public void testPrestartCoreThread() {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getPoolSize());
- assertTrue(p2.prestartCoreThread());
- assertEquals(1, p2.getPoolSize());
- assertTrue(p2.prestartCoreThread());
- assertEquals(2, p2.getPoolSize());
- assertFalse(p2.prestartCoreThread());
- assertEquals(2, p2.getPoolSize());
- joinPool(p2);
- }
-
- /**
- * prestartAllCoreThreads starts all corePoolSize threads
- */
- public void testPrestartAllCoreThreads() {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getPoolSize());
- p2.prestartAllCoreThreads();
- assertEquals(2, p2.getPoolSize());
- p2.prestartAllCoreThreads();
- assertEquals(2, p2.getPoolSize());
- joinPool(p2);
- }
-
- /**
- * getCompletedTaskCount increases, but doesn't overestimate,
- * when tasks complete
- */
- public void testGetCompletedTaskCount() throws InterruptedException {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getCompletedTaskCount());
- p2.execute(new ShortRunnable());
- Thread.sleep(SMALL_DELAY_MS);
- assertEquals(1, p2.getCompletedTaskCount());
- try { p2.shutdown(); } catch (SecurityException ok) { return; }
- joinPool(p2);
- }
-
- /**
- * getCorePoolSize returns size given in constructor if not otherwise set
- */
- public void testGetCorePoolSize() {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(1, p1.getCorePoolSize());
- joinPool(p1);
- }
-
- /**
- * getKeepAliveTime returns value given in constructor if not otherwise set
- */
- public void testGetKeepAliveTime() {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(1, p2.getKeepAliveTime(TimeUnit.SECONDS));
- joinPool(p2);
- }
-
-
- /**
- * getThreadFactory returns factory in constructor if not set
- */
- public void testGetThreadFactory() {
- ThreadFactory tf = new SimpleThreadFactory();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), tf, new NoOpREHandler());
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
- /**
- * setThreadFactory sets the thread factory returned by getThreadFactory
- */
- public void testSetThreadFactory() {
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- ThreadFactory tf = new SimpleThreadFactory();
- p.setThreadFactory(tf);
- assertSame(tf, p.getThreadFactory());
- joinPool(p);
- }
-
-
- /**
- * setThreadFactory(null) throws NPE
- */
- public void testSetThreadFactoryNull() {
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- p.setThreadFactory(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * getRejectedExecutionHandler returns handler in constructor if not set
- */
- public void testGetRejectedExecutionHandler() {
- RejectedExecutionHandler h = new NoOpREHandler();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), h);
- assertSame(h, p.getRejectedExecutionHandler());
- joinPool(p);
- }
-
- /**
- * setRejectedExecutionHandler sets the handler returned by
- * getRejectedExecutionHandler
- */
- public void testSetRejectedExecutionHandler() {
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- RejectedExecutionHandler h = new NoOpREHandler();
- p.setRejectedExecutionHandler(h);
- assertSame(h, p.getRejectedExecutionHandler());
- joinPool(p);
- }
-
-
- /**
- * setRejectedExecutionHandler(null) throws NPE
- */
- public void testSetRejectedExecutionHandlerNull() {
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- p.setRejectedExecutionHandler(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * getLargestPoolSize increases, but doesn't overestimate, when
- * multiple threads active
- */
- public void testGetLargestPoolSize() throws InterruptedException {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p2.getLargestPoolSize());
- p2.execute(new MediumRunnable());
- p2.execute(new MediumRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(2, p2.getLargestPoolSize());
- joinPool(p2);
- }
-
- /**
- * getMaximumPoolSize returns value given in constructor if not
- * otherwise set
- */
- public void testGetMaximumPoolSize() {
- ThreadPoolExecutor p2 = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(2, p2.getMaximumPoolSize());
- joinPool(p2);
- }
-
- /**
- * getPoolSize increases, but doesn't overestimate, when threads
- * become active
- */
- public void testGetPoolSize() {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p1.getPoolSize());
- p1.execute(new MediumRunnable());
- assertEquals(1, p1.getPoolSize());
- joinPool(p1);
- }
-
- /**
- * getTaskCount increases, but doesn't overestimate, when tasks submitted
- */
- public void testGetTaskCount() throws InterruptedException {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertEquals(0, p1.getTaskCount());
- p1.execute(new MediumRunnable());
- Thread.sleep(SHORT_DELAY_MS);
- assertEquals(1, p1.getTaskCount());
- joinPool(p1);
- }
-
- /**
- * isShutDown is false before shutdown, true after
- */
- public void testIsShutdown() {
-
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(p1.isShutdown());
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(p1.isShutdown());
- joinPool(p1);
- }
-
-
- /**
- * isTerminated is false before termination, true after
- */
- public void testIsTerminated() throws InterruptedException {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(p1.isTerminated());
- try {
- p1.execute(new MediumRunnable());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- }
-
- /**
- * isTerminating is not true when running or when terminated
- */
- public void testIsTerminating() throws InterruptedException {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(p1.isTerminating());
- try {
- p1.execute(new SmallRunnable());
- assertFalse(p1.isTerminating());
- } finally {
- try { p1.shutdown(); } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
- assertTrue(p1.isTerminated());
- assertFalse(p1.isTerminating());
- }
-
- /**
- * getQueue returns the work queue, which contains queued tasks
- */
- public void testGetQueue() throws InterruptedException {
- BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, q);
- FutureTask[] tasks = new FutureTask[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
- p1.execute(tasks[i]);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- BlockingQueue<Runnable> wq = p1.getQueue();
- assertSame(q, wq);
- assertFalse(wq.contains(tasks[0]));
- assertTrue(wq.contains(tasks[4]));
- for (int i = 1; i < 5; ++i)
- tasks[i].cancel(true);
- p1.shutdownNow();
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * remove(task) removes queued task, and fails to remove active task
- */
- public void testRemove() throws InterruptedException {
- BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, q);
- FutureTask[] tasks = new FutureTask[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
- p1.execute(tasks[i]);
- }
- try {
- Thread.sleep(SHORT_DELAY_MS);
- assertFalse(p1.remove(tasks[0]));
- assertTrue(q.contains(tasks[4]));
- assertTrue(q.contains(tasks[3]));
- assertTrue(p1.remove(tasks[4]));
- assertFalse(p1.remove(tasks[4]));
- assertFalse(q.contains(tasks[4]));
- assertTrue(q.contains(tasks[3]));
- assertTrue(p1.remove(tasks[3]));
- assertFalse(q.contains(tasks[3]));
- } finally {
- joinPool(p1);
- }
- }
-
- /**
- * purge removes cancelled tasks from the queue
- */
- public void testPurge() {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- FutureTask[] tasks = new FutureTask[5];
- for (int i = 0; i < 5; i++) {
- tasks[i] = new FutureTask(new MediumPossiblyInterruptedRunnable(), Boolean.TRUE);
- p1.execute(tasks[i]);
- }
- tasks[4].cancel(true);
- tasks[3].cancel(true);
- p1.purge();
- long count = p1.getTaskCount();
- assertTrue(count >= 2 && count < 5);
- joinPool(p1);
- }
-
- /**
- * shutDownNow returns a list containing tasks that were not run
- */
- public void testShutDownNow() {
- ThreadPoolExecutor p1 = new ThreadPoolExecutor(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List l;
- try {
- for (int i = 0; i < 5; i++)
- p1.execute(new MediumPossiblyInterruptedRunnable());
- }
- finally {
- try {
- l = p1.shutdownNow();
- } catch (SecurityException ok) { return; }
- }
- assertTrue(p1.isShutdown());
- assertTrue(l.size() <= 4);
- }
-
- // Exception Tests
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor1() {
- try {
- new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor2() {
- try {
- new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor3() {
- try {
- new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor4() {
- try {
- new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor5() {
- try {
- new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException() {
- try {
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor6() {
- try {
- new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor7() {
- try {
- new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor8() {
- try {
- new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor9() {
- try {
- new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor10() {
- try {
- new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException2() {
- try {
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if threadFactory is set to null
- */
- public void testConstructorNullPointerException3() {
- try {
- ThreadFactory f = null;
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),f);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor11() {
- try {
- new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor12() {
- try {
- new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor13() {
- try {
- new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor14() {
- try {
- new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor15() {
- try {
- new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException4() {
- try {
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null,new NoOpREHandler());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if handler is set to null
- */
- public void testConstructorNullPointerException5() {
- try {
- RejectedExecutionHandler r = null;
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),r);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * Constructor throws if corePoolSize argument is less than zero
- */
- public void testConstructor16() {
- try {
- new ThreadPoolExecutor(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is less than zero
- */
- public void testConstructor17() {
- try {
- new ThreadPoolExecutor(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if maximumPoolSize is equal to zero
- */
- public void testConstructor18() {
- try {
- new ThreadPoolExecutor(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if keepAliveTime is less than zero
- */
- public void testConstructor19() {
- try {
- new ThreadPoolExecutor(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if corePoolSize is greater than the maximumPoolSize
- */
- public void testConstructor20() {
- try {
- new ThreadPoolExecutor(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (IllegalArgumentException success) {}
- }
-
- /**
- * Constructor throws if workQueue is set to null
- */
- public void testConstructorNullPointerException6() {
- try {
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if handler is set to null
- */
- public void testConstructorNullPointerException7() {
- try {
- RejectedExecutionHandler r = null;
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),r);
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
- /**
- * Constructor throws if ThreadFactory is set top null
- */
- public void testConstructorNullPointerException8() {
- try {
- ThreadFactory f = null;
- new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),f,new NoOpREHandler());
- shouldThrow();
- } catch (NullPointerException success) {}
- }
-
-
- /**
- * execute throws RejectedExecutionException
- * if saturated.
- */
- public void testSaturatedExecute() {
- ThreadPoolExecutor p =
- new ThreadPoolExecutor(1, 1,
- LONG_DELAY_MS, MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(1));
- try {
- for (int i = 0; i < 2; ++i)
- p.execute(new MediumRunnable());
- for (int i = 0; i < 2; ++i) {
- try {
- p.execute(new MediumRunnable());
- shouldThrow();
- } catch (RejectedExecutionException success) {}
- }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * executor using CallerRunsPolicy runs task if saturated.
- */
- public void testSaturatedExecute2() {
- RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
- try {
-
- TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
- for (int i = 0; i < 5; ++i) {
- tasks[i] = new TrackedNoOpRunnable();
- }
- TrackedLongRunnable mr = new TrackedLongRunnable();
- p.execute(mr);
- for (int i = 0; i < 5; ++i) {
- p.execute(tasks[i]);
- }
- for (int i = 1; i < 5; ++i) {
- assertTrue(tasks[i].done);
- }
- try { p.shutdownNow(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * executor using DiscardPolicy drops task if saturated.
- */
- public void testSaturatedExecute3() {
- RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
- try {
-
- TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
- for (int i = 0; i < 5; ++i) {
- tasks[i] = new TrackedNoOpRunnable();
- }
- p.execute(new TrackedLongRunnable());
- for (int i = 0; i < 5; ++i) {
- p.execute(tasks[i]);
- }
- for (int i = 0; i < 5; ++i) {
- assertFalse(tasks[i].done);
- }
- try { p.shutdownNow(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * executor using DiscardOldestPolicy drops oldest task if saturated.
- */
- public void testSaturatedExecute4() {
- RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
- try {
- p.execute(new TrackedLongRunnable());
- TrackedLongRunnable r2 = new TrackedLongRunnable();
- p.execute(r2);
- assertTrue(p.getQueue().contains(r2));
- TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
- p.execute(r3);
- assertFalse(p.getQueue().contains(r2));
- assertTrue(p.getQueue().contains(r3));
- try { p.shutdownNow(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * execute throws RejectedExecutionException if shutdown
- */
- public void testRejectedExecutionExceptionOnShutdown() {
- ThreadPoolExecutor tpe =
- new ThreadPoolExecutor(1,1,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(1));
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- try {
- tpe.execute(new NoOpRunnable());
- shouldThrow();
- } catch (RejectedExecutionException success) {}
-
- joinPool(tpe);
- }
-
- /**
- * execute using CallerRunsPolicy drops task on shutdown
- */
- public void testCallerRunsOnShutdown() {
- RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
-
- try { p.shutdown(); } catch (SecurityException ok) { return; }
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- p.execute(r);
- assertFalse(r.done);
- } finally {
- joinPool(p);
- }
- }
-
- /**
- * execute using DiscardPolicy drops task on shutdown
- */
- public void testDiscardOnShutdown() {
- RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
-
- try { p.shutdown(); } catch (SecurityException ok) { return; }
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- p.execute(r);
- assertFalse(r.done);
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * execute using DiscardOldestPolicy drops task on shutdown
- */
- public void testDiscardOldestOnShutdown() {
- RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
- ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
-
- try { p.shutdown(); } catch (SecurityException ok) { return; }
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- p.execute(r);
- assertFalse(r.done);
- } finally {
- joinPool(p);
- }
- }
-
-
- /**
- * execute (null) throws NPE
- */
- public void testExecuteNull() {
- ThreadPoolExecutor tpe = new ThreadPoolExecutor(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.execute(null);
- shouldThrow();
- } catch (NullPointerException success) {}
-
- joinPool(tpe);
- }
-
- /**
- * setCorePoolSize of negative value throws IllegalArgumentException
- */
- public void testCorePoolSizeIllegalArgumentException() {
- ThreadPoolExecutor tpe =
- new ThreadPoolExecutor(1, 2,
- LONG_DELAY_MS, MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setCorePoolSize(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
- /**
- * setMaximumPoolSize(int) throws IllegalArgumentException if
- * given a value less the core pool size
- */
- public void testMaximumPoolSizeIllegalArgumentException() {
- ThreadPoolExecutor tpe =
- new ThreadPoolExecutor(2, 3,
- LONG_DELAY_MS, MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setMaximumPoolSize(1);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
- /**
- * setMaximumPoolSize throws IllegalArgumentException
- * if given a negative value
- */
- public void testMaximumPoolSizeIllegalArgumentException2() {
- ThreadPoolExecutor tpe =
- new ThreadPoolExecutor(2, 3,
- LONG_DELAY_MS, MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setMaximumPoolSize(-1);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
-
- /**
- * setKeepAliveTime throws IllegalArgumentException
- * when given a negative value
- */
- public void testKeepAliveTimeIllegalArgumentException() {
- ThreadPoolExecutor tpe =
- new ThreadPoolExecutor(2, 3,
- LONG_DELAY_MS, MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(10));
- try {
- tpe.setKeepAliveTime(-1,MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- }
- joinPool(tpe);
- }
-
- /**
- * terminated() is called on termination
- */
- public void testTerminated() {
- ExtendedTPE tpe = new ExtendedTPE();
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- assertTrue(tpe.terminatedCalled);
- joinPool(tpe);
- }
-
- /**
- * beforeExecute and afterExecute are called when executing task
- */
- public void testBeforeAfter() throws InterruptedException {
- ExtendedTPE tpe = new ExtendedTPE();
- try {
- TrackedNoOpRunnable r = new TrackedNoOpRunnable();
- tpe.execute(r);
- Thread.sleep(SHORT_DELAY_MS);
- assertTrue(r.done);
- assertTrue(tpe.beforeCalled);
- assertTrue(tpe.afterCalled);
- try { tpe.shutdown(); } catch (SecurityException ok) { return; }
- } finally {
- joinPool(tpe);
- }
- }
-
- /**
- * completed submit of callable returns result
- */
- public void testSubmitCallable() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- Future<String> future = e.submit(new StringTask());
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of runnable returns successfully
- */
- public void testSubmitRunnable() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- Future<?> future = e.submit(new NoOpRunnable());
- future.get();
- assertTrue(future.isDone());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * completed submit of (runnable, result) returns result
- */
- public void testSubmitRunnable2() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
- String result = future.get();
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
-
- /**
- * invokeAny(null) throws NPE
- */
- public void testInvokeAny1() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(empty collection) throws IAE
- */
- public void testInvokeAny2() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(new ArrayList<Callable<String>>());
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws NPE if c has null elements
- */
- public void testInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) throws ExecutionException if no task completes
- */
- public void testInvokeAny4() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAny(c) returns result of some task
- */
- public void testInvokeAny5() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(null) throws NPE
- */
- public void testInvokeAll1() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAll(null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(empty collection) returns empty collection
- */
- public void testInvokeAll2() throws InterruptedException {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) throws NPE if c has null elements
- */
- public void testInvokeAll3() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of element of invokeAll(c) throws exception on failed task
- */
- public void testInvokeAll4() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- }
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * invokeAll(c) returns results of all completed tasks
- */
- public void testInvokeAll5() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures = e.invokeAll(l);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
-
-
- /**
- * timed invokeAny(null) throws NPE
- */
- public void testTimedInvokeAny1() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(,,null) throws NPE
- */
- public void testTimedInvokeAnyNullTimeUnit() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(empty collection) throws IAE
- */
- public void testTimedInvokeAny2() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (IllegalArgumentException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAny3() throws Exception {
- CountDownLatch latch = new CountDownLatch(1);
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(latchAwaitingStringTask(latch));
- l.add(null);
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- latch.countDown();
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) throws ExecutionException if no task completes
- */
- public void testTimedInvokeAny4() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- try {
- e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAny(c) returns result of some task
- */
- public void testTimedInvokeAny5() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertSame(TEST_STRING, result);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(null) throws NPE
- */
- public void testTimedInvokeAll1() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(,,null) throws NPE
- */
- public void testTimedInvokeAllNullTimeUnit() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, null);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(empty collection) returns empty collection
- */
- public void testTimedInvokeAll2() throws InterruptedException {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
- assertTrue(r.isEmpty());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) throws NPE if c has null elements
- */
- public void testTimedInvokeAll3() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(null);
- try {
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- shouldThrow();
- } catch (NullPointerException success) {
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * get of element of invokeAll(c) throws exception on failed task
- */
- public void testTimedInvokeAll4() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new NPETask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(1, futures.size());
- try {
- futures.get(0).get();
- shouldThrow();
- } catch (ExecutionException success) {
- assertTrue(success.getCause() instanceof NullPointerException);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) returns results of all completed tasks
- */
- public void testTimedInvokeAll5() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
- assertEquals(2, futures.size());
- for (Future<String> future : futures)
- assertSame(TEST_STRING, future.get());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * timed invokeAll(c) cancels tasks not completed by timeout
- */
- public void testTimedInvokeAll6() throws Exception {
- ExecutorService e = new ThreadPoolExecutor(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- l.add(new StringTask());
- l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
- l.add(new StringTask());
- List<Future<String>> futures =
- e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
- assertEquals(3, futures.size());
- Iterator<Future<String>> it = futures.iterator();
- Future<String> f1 = it.next();
- Future<String> f2 = it.next();
- Future<String> f3 = it.next();
- assertTrue(f1.isDone());
- assertTrue(f2.isDone());
- assertTrue(f3.isDone());
- assertFalse(f1.isCancelled());
- assertTrue(f2.isCancelled());
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * Execution continues if there is at least one thread even if
- * thread factory fails to create more
- */
- public void testFailingThreadFactory() throws InterruptedException {
- ExecutorService e = new ThreadPoolExecutor(100, 100, LONG_DELAY_MS, MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new FailingThreadFactory());
- try {
- List<Callable<String>> l = new ArrayList<Callable<String>>();
- for (int k = 0; k < 100; ++k) {
- e.execute(new NoOpRunnable());
- }
- Thread.sleep(LONG_DELAY_MS);
- } finally {
- joinPool(e);
- }
- }
-
- /**
- * allowsCoreThreadTimeOut is by default false.
- */
- public void testAllowsCoreThreadTimeOut() {
- ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- assertFalse(tpe.allowsCoreThreadTimeOut());
- joinPool(tpe);
- }
-
- /**
- * allowCoreThreadTimeOut(true) causes idle threads to time out
- */
- public void testAllowCoreThreadTimeOut_true() throws InterruptedException {
- ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- tpe.allowCoreThreadTimeOut(true);
- tpe.execute(new NoOpRunnable());
- try {
- Thread.sleep(MEDIUM_DELAY_MS);
- assertEquals(0, tpe.getPoolSize());
- } finally {
- joinPool(tpe);
- }
- }
-
- /**
- * allowCoreThreadTimeOut(false) causes idle threads not to time out
- */
- public void testAllowCoreThreadTimeOut_false() throws InterruptedException {
- ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 10, 10, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
- tpe.allowCoreThreadTimeOut(false);
- tpe.execute(new NoOpRunnable());
- try {
- Thread.sleep(MEDIUM_DELAY_MS);
- assertTrue(tpe.getPoolSize() >= 1);
- } finally {
- joinPool(tpe);
- }
- }
-
- /**
- * execute allows the same task to be submitted multiple times, even
- * if rejected
- */
- public void testRejectedRecycledTask() throws InterruptedException {
- final int nTasks = 1000;
- final AtomicInteger nRun = new AtomicInteger(0);
- final Runnable recycledTask = new Runnable() {
- public void run() {
- nRun.getAndIncrement();
- } };
- final ThreadPoolExecutor p =
- new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS,
- new ArrayBlockingQueue(30));
- try {
- for (int i = 0; i < nTasks; ++i) {
- for (;;) {
- try {
- p.execute(recycledTask);
- break;
- }
- catch (RejectedExecutionException ignore) {
- }
- }
- }
- Thread.sleep(5000); // enough time to run all tasks
- assertEquals(nRun.get(), nTasks);
- } finally {
- p.shutdown();
- }
- }
-
- // BEGIN android-added
- /** http://b/3046427 */
- public void testRejected() {
- BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(2);
- ExecutorService executor = new ThreadPoolExecutor(0, 2, 1, TimeUnit.SECONDS, queue);
- executor.submit(new Sleeper()); // thread #1
- executor.submit(new Sleeper()); // thread #2
- executor.submit(new Sleeper()); // queue #1
- executor.submit(new Sleeper()); // queue #2
- try {
- executor.submit(new Sleeper());
- fail();
- } catch (RejectedExecutionException expected) {
- System.out.println(expected.getMessage());
- assertNotNull(expected.getMessage());
- }
- executor.shutdown();
- }
-
- static class Sleeper implements Runnable {
- public void run() {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- // END android-added
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/ThreadTest.java b/luni/src/test/java/tests/api/java/util/concurrent/ThreadTest.java
deleted file mode 100755
index e9f28ac..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/ThreadTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-
-public class ThreadTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(ThreadTest.class);
- }
-
- static class MyHandler implements Thread.UncaughtExceptionHandler {
- public void uncaughtException(Thread t, Throwable e) {
- e.printStackTrace();
- }
- }
-
- /**
- * getUncaughtExceptionHandler returns ThreadGroup unless set,
- * otherwise returning value of last setUncaughtExceptionHandler.
- */
- public void testGetAndSetUncaughtExceptionHandler() {
- // these must be done all at once to avoid state
- // dependencies across tests
- Thread current = Thread.currentThread();
- ThreadGroup tg = current.getThreadGroup();
- MyHandler eh = new MyHandler();
- assertEquals(tg, current.getUncaughtExceptionHandler());
- current.setUncaughtExceptionHandler(eh);
- assertEquals(eh, current.getUncaughtExceptionHandler());
- current.setUncaughtExceptionHandler(null);
- assertEquals(tg, current.getUncaughtExceptionHandler());
- }
-
- /**
- * getDefaultUncaughtExceptionHandler returns value of last
- * setDefaultUncaughtExceptionHandler.
- */
- public void testGetAndSetDefaultUncaughtExceptionHandler() {
- assertEquals(null, Thread.getDefaultUncaughtExceptionHandler());
- // failure due to securityException is OK.
- // Would be nice to explicitly test both ways, but cannot yet.
- try {
- Thread current = Thread.currentThread();
- ThreadGroup tg = current.getThreadGroup();
- MyHandler eh = new MyHandler();
- Thread.setDefaultUncaughtExceptionHandler(eh);
- assertEquals(eh, Thread.getDefaultUncaughtExceptionHandler());
- Thread.setDefaultUncaughtExceptionHandler(null);
- }
- catch (SecurityException ok) {
- }
- assertEquals(null, Thread.getDefaultUncaughtExceptionHandler());
- }
-
-
- // How to test actually using UEH within junit?
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java b/luni/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java
deleted file mode 100755
index 84be0c4..0000000
--- a/luni/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java
+++ /dev/null
@@ -1,427 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/licenses/publicdomain
- * Other contributors include Andrew Wright, Jeffrey Hayes,
- * Pat Fisher, Mike Judd.
- */
-
-package tests.api.java.util.concurrent; // android-added
-
-import junit.framework.*;
-import java.util.concurrent.*;
-import java.io.*;
-
-public class TimeUnitTest extends JSR166TestCase {
- public static Test suite() {
- return new TestSuite(TimeUnitTest.class);
- }
-
- // (loops to 88888 check increments at all time divisions.)
-
- /**
- * convert correctly converts sample values across the units
- */
- public void testConvert() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*60*60*24,
- TimeUnit.SECONDS.convert(t,
- TimeUnit.DAYS));
- assertEquals(t*60*60,
- TimeUnit.SECONDS.convert(t,
- TimeUnit.HOURS));
- assertEquals(t*60,
- TimeUnit.SECONDS.convert(t,
- TimeUnit.MINUTES));
- assertEquals(t,
- TimeUnit.SECONDS.convert(t,
- TimeUnit.SECONDS));
- assertEquals(t,
- TimeUnit.SECONDS.convert(1000L*t,
- TimeUnit.MILLISECONDS));
- assertEquals(t,
- TimeUnit.SECONDS.convert(1000000L*t,
- TimeUnit.MICROSECONDS));
- assertEquals(t,
- TimeUnit.SECONDS.convert(1000000000L*t,
- TimeUnit.NANOSECONDS));
-
-
- assertEquals(1000L*t*60*60*24,
- TimeUnit.MILLISECONDS.convert(t,
- TimeUnit.DAYS));
- assertEquals(1000L*t*60*60,
- TimeUnit.MILLISECONDS.convert(t,
- TimeUnit.HOURS));
- assertEquals(1000L*t*60,
- TimeUnit.MILLISECONDS.convert(t,
- TimeUnit.MINUTES));
- assertEquals(1000L*t,
- TimeUnit.MILLISECONDS.convert(t,
- TimeUnit.SECONDS));
- assertEquals(t,
- TimeUnit.MILLISECONDS.convert(t,
- TimeUnit.MILLISECONDS));
- assertEquals(t,
- TimeUnit.MILLISECONDS.convert(1000L*t,
- TimeUnit.MICROSECONDS));
- assertEquals(t,
- TimeUnit.MILLISECONDS.convert(1000000L*t,
- TimeUnit.NANOSECONDS));
-
- assertEquals(1000000L*t*60*60*24,
- TimeUnit.MICROSECONDS.convert(t,
- TimeUnit.DAYS));
- assertEquals(1000000L*t*60*60,
- TimeUnit.MICROSECONDS.convert(t,
- TimeUnit.HOURS));
- assertEquals(1000000L*t*60,
- TimeUnit.MICROSECONDS.convert(t,
- TimeUnit.MINUTES));
- assertEquals(1000000L*t,
- TimeUnit.MICROSECONDS.convert(t,
- TimeUnit.SECONDS));
- assertEquals(1000L*t,
- TimeUnit.MICROSECONDS.convert(t,
- TimeUnit.MILLISECONDS));
- assertEquals(t,
- TimeUnit.MICROSECONDS.convert(t,
- TimeUnit.MICROSECONDS));
- assertEquals(t,
- TimeUnit.MICROSECONDS.convert(1000L*t,
- TimeUnit.NANOSECONDS));
-
- assertEquals(1000000000L*t*60*60*24,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.DAYS));
- assertEquals(1000000000L*t*60*60,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.HOURS));
- assertEquals(1000000000L*t*60,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.MINUTES));
- assertEquals(1000000000L*t,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.SECONDS));
- assertEquals(1000000L*t,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.MILLISECONDS));
- assertEquals(1000L*t,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.MICROSECONDS));
- assertEquals(t,
- TimeUnit.NANOSECONDS.convert(t,
- TimeUnit.NANOSECONDS));
- }
- }
-
- /**
- * toNanos correctly converts sample values in different units to
- * nanoseconds
- */
- public void testToNanos() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*1000000000L*60*60*24,
- TimeUnit.DAYS.toNanos(t));
- assertEquals(t*1000000000L*60*60,
- TimeUnit.HOURS.toNanos(t));
- assertEquals(t*1000000000L*60,
- TimeUnit.MINUTES.toNanos(t));
- assertEquals(1000000000L*t,
- TimeUnit.SECONDS.toNanos(t));
- assertEquals(1000000L*t,
- TimeUnit.MILLISECONDS.toNanos(t));
- assertEquals(1000L*t,
- TimeUnit.MICROSECONDS.toNanos(t));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toNanos(t));
- }
- }
-
- /**
- * toMicros correctly converts sample values in different units to
- * microseconds
- */
- public void testToMicros() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*1000000L*60*60*24,
- TimeUnit.DAYS.toMicros(t));
- assertEquals(t*1000000L*60*60,
- TimeUnit.HOURS.toMicros(t));
- assertEquals(t*1000000L*60,
- TimeUnit.MINUTES.toMicros(t));
- assertEquals(1000000L*t,
- TimeUnit.SECONDS.toMicros(t));
- assertEquals(1000L*t,
- TimeUnit.MILLISECONDS.toMicros(t));
- assertEquals(t,
- TimeUnit.MICROSECONDS.toMicros(t));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toMicros(t*1000L));
- }
- }
-
- /**
- * toMillis correctly converts sample values in different units to
- * milliseconds
- */
- public void testToMillis() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*1000L*60*60*24,
- TimeUnit.DAYS.toMillis(t));
- assertEquals(t*1000L*60*60,
- TimeUnit.HOURS.toMillis(t));
- assertEquals(t*1000L*60,
- TimeUnit.MINUTES.toMillis(t));
- assertEquals(1000L*t,
- TimeUnit.SECONDS.toMillis(t));
- assertEquals(t,
- TimeUnit.MILLISECONDS.toMillis(t));
- assertEquals(t,
- TimeUnit.MICROSECONDS.toMillis(t*1000L));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toMillis(t*1000000L));
- }
- }
-
- /**
- * toSeconds correctly converts sample values in different units to
- * seconds
- */
- public void testToSeconds() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*60*60*24,
- TimeUnit.DAYS.toSeconds(t));
- assertEquals(t*60*60,
- TimeUnit.HOURS.toSeconds(t));
- assertEquals(t*60,
- TimeUnit.MINUTES.toSeconds(t));
- assertEquals(t,
- TimeUnit.SECONDS.toSeconds(t));
- assertEquals(t,
- TimeUnit.MILLISECONDS.toSeconds(t*1000L));
- assertEquals(t,
- TimeUnit.MICROSECONDS.toSeconds(t*1000000L));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toSeconds(t*1000000000L));
- }
- }
-
- /**
- * toMinutes correctly converts sample values in different units to
- * minutes
- */
- public void testToMinutes() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*60*24,
- TimeUnit.DAYS.toMinutes(t));
- assertEquals(t*60,
- TimeUnit.HOURS.toMinutes(t));
- assertEquals(t,
- TimeUnit.MINUTES.toMinutes(t));
- assertEquals(t,
- TimeUnit.SECONDS.toMinutes(t*60));
- assertEquals(t,
- TimeUnit.MILLISECONDS.toMinutes(t*1000L*60));
- assertEquals(t,
- TimeUnit.MICROSECONDS.toMinutes(t*1000000L*60));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toMinutes(t*1000000000L*60));
- }
- }
-
- /**
- * toHours correctly converts sample values in different units to
- * hours
- */
- public void testToHours() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t*24,
- TimeUnit.DAYS.toHours(t));
- assertEquals(t,
- TimeUnit.HOURS.toHours(t));
- assertEquals(t,
- TimeUnit.MINUTES.toHours(t*60));
- assertEquals(t,
- TimeUnit.SECONDS.toHours(t*60*60));
- assertEquals(t,
- TimeUnit.MILLISECONDS.toHours(t*1000L*60*60));
- assertEquals(t,
- TimeUnit.MICROSECONDS.toHours(t*1000000L*60*60));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toHours(t*1000000000L*60*60));
- }
- }
-
- /**
- * toDays correctly converts sample values in different units to
- * days
- */
- public void testToDays() {
- for (long t = 0; t < 88888; ++t) {
- assertEquals(t,
- TimeUnit.DAYS.toDays(t));
- assertEquals(t,
- TimeUnit.HOURS.toDays(t*24));
- assertEquals(t,
- TimeUnit.MINUTES.toDays(t*60*24));
- assertEquals(t,
- TimeUnit.SECONDS.toDays(t*60*60*24));
- assertEquals(t,
- TimeUnit.MILLISECONDS.toDays(t*1000L*60*60*24));
- assertEquals(t,
- TimeUnit.MICROSECONDS.toDays(t*1000000L*60*60*24));
- assertEquals(t,
- TimeUnit.NANOSECONDS.toDays(t*1000000000L*60*60*24));
- }
- }
-
-
- /**
- * convert saturates positive too-large values to Long.MAX_VALUE
- * and negative to LONG.MIN_VALUE
- */
- public void testConvertSaturate() {
- assertEquals(Long.MAX_VALUE,
- TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
- TimeUnit.SECONDS));
- assertEquals(Long.MIN_VALUE,
- TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
- TimeUnit.SECONDS));
- assertEquals(Long.MAX_VALUE,
- TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
- TimeUnit.MINUTES));
- assertEquals(Long.MIN_VALUE,
- TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
- TimeUnit.MINUTES));
- assertEquals(Long.MAX_VALUE,
- TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
- TimeUnit.HOURS));
- assertEquals(Long.MIN_VALUE,
- TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
- TimeUnit.HOURS));
- assertEquals(Long.MAX_VALUE,
- TimeUnit.NANOSECONDS.convert(Long.MAX_VALUE / 2,
- TimeUnit.DAYS));
- assertEquals(Long.MIN_VALUE,
- TimeUnit.NANOSECONDS.convert(-Long.MAX_VALUE / 4,
- TimeUnit.DAYS));
- }
-
- /**
- * toNanos saturates positive too-large values to Long.MAX_VALUE
- * and negative to LONG.MIN_VALUE
- */
- public void testToNanosSaturate() {
- assertEquals(Long.MAX_VALUE,
- TimeUnit.MILLISECONDS.toNanos(Long.MAX_VALUE / 2));
- assertEquals(Long.MIN_VALUE,
- TimeUnit.MILLISECONDS.toNanos(-Long.MAX_VALUE / 3));
- }
-
-
- /**
- * toString returns string containing common name of unit
- */
- public void testToString() {
- String s = TimeUnit.SECONDS.toString();
- assertTrue(s.indexOf("ECOND") >= 0);
- }
-
-
- /**
- * Timed wait without holding lock throws
- * IllegalMonitorStateException
- */
- public void testTimedWait_IllegalMonitorException() throws Exception {
- Thread t = new Thread(new CheckedRunnable() {
- public void realRun() throws InterruptedException {
- Object o = new Object();
- TimeUnit tu = TimeUnit.MILLISECONDS;
- try {
- tu.timedWait(o,LONG_DELAY_MS);
- threadShouldThrow();
- } catch (IllegalMonitorStateException success) {}}});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * timedWait throws InterruptedException when interrupted
- */
- public void testTimedWait() throws InterruptedException {
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- Object o = new Object();
-
- TimeUnit tu = TimeUnit.MILLISECONDS;
- synchronized(o) {
- tu.timedWait(o,MEDIUM_DELAY_MS);
- }
- }});
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
-
- /**
- * timedJoin throws InterruptedException when interrupted
- */
- public void testTimedJoin() throws InterruptedException {
- final Thread s = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- Thread.sleep(MEDIUM_DELAY_MS);
- }});
- final Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- TimeUnit tu = TimeUnit.MILLISECONDS;
- tu.timedJoin(s, MEDIUM_DELAY_MS);
- }});;
- s.start();
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- s.interrupt();
- s.join();
- }
-
- /**
- * timedSleep throws InterruptedException when interrupted
- */
- public void testTimedSleep() throws InterruptedException {
- Thread t = new Thread(new CheckedInterruptedRunnable() {
- public void realRun() throws InterruptedException {
- TimeUnit tu = TimeUnit.MILLISECONDS;
- tu.sleep(MEDIUM_DELAY_MS);
- }});
-
- t.start();
- Thread.sleep(SHORT_DELAY_MS);
- t.interrupt();
- t.join();
- }
-
- /**
- * a deserialized serialized unit is the same instance
- */
- public void testSerialization() throws Exception {
- TimeUnit q = TimeUnit.MILLISECONDS;
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
- ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
- out.writeObject(q);
- out.close();
-
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
- TimeUnit r = (TimeUnit)in.readObject();
- assertSame(q, r);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
index d8d186e..a34977b 100644
--- a/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
+++ b/luni/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
@@ -759,31 +759,12 @@
}
}
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "wrap cannot be forced to fail",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
public void test_wrap_01() throws IOException, InterruptedException {
prepareEngines();
doHandshake();
-
ByteBuffer bbs = ByteBuffer.allocate(100);
ByteBuffer bbd = ByteBuffer.allocate(20000);
-
- try {
- @SuppressWarnings("unused")
- SSLEngineResult result = clientEngine.engine.wrap(new ByteBuffer[] { bbs }, 0, 1, bbd);
- //fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
+ clientEngine.engine.wrap(new ByteBuffer[] { bbs }, 0, 1, bbd);
}
/**
@@ -1344,30 +1325,12 @@
}
}
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "wrap cannot be forced to produce SSLException",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
public void test_wrap_ByteBuffer_ByteBuffer_01() throws IOException, InterruptedException {
prepareEngines();
doHandshake();
ByteBuffer bbs = ByteBuffer.allocate(20);
ByteBuffer bbd = ByteBuffer.allocate(20000);
-
- try {
- clientEngine.engine.wrap(bbs, bbd);
- //fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
+ clientEngine.engine.wrap(bbs, bbd);
}
/**
diff --git a/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java b/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java
index 14417a9..852a052 100644
--- a/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java
+++ b/luni/src/test/java/tests/api/javax/security/cert/CertificateTest.java
@@ -40,19 +40,6 @@
import javax.security.cert.CertificateEncodingException;
import javax.security.cert.CertificateException;
-/**
- */
-@TestTargetClass(
- value = Certificate.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not specific enough for black-box testing",
- method = "toString",
- args = {}
- )
- }
-)
public class CertificateTest extends TestCase {
/**
diff --git a/luni/src/test/java/tests/concurrent/AllTests.java b/luni/src/test/java/tests/concurrent/AllTests.java
deleted file mode 100644
index 4c49f54..0000000
--- a/luni/src/test/java/tests/concurrent/AllTests.java
+++ /dev/null
@@ -1,36 +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 tests.concurrent;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Test suite for the concurrent module
- */
-public class AllTests {
- /**
- * Collects all JSR166 unit tests as one suite
- */
- public static Test suite ( ) {
- TestSuite suite = new TestSuite("JSR166 Unit Tests");
-
- suite.addTest(tests.api.java.util.concurrent.JSR166TestCase.suite());
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/java/security/SecureClassLoaderTest.java b/luni/src/test/java/tests/java/security/SecureClassLoaderTest.java
index 5e6c021..9a0761b 100644
--- a/luni/src/test/java/tests/java/security/SecureClassLoaderTest.java
+++ b/luni/src/test/java/tests/java/security/SecureClassLoaderTest.java
@@ -23,9 +23,6 @@
package tests.java.security;
import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
import junit.framework.TestCase;
@@ -38,25 +35,7 @@
import java.security.ProtectionDomain;
import java.security.SecureClassLoader;
import java.security.cert.Certificate;
-@TestTargetClass(value=SecureClassLoader.class,
- untestedMethods={
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "cannot be tested",
- method = "defineClass",
- args = {
- java.lang.String.class, byte[].class, int.class,
- int.class, java.security.CodeSource.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "cannot be tested",
- method = "defineClass",
- args = {
- java.lang.String.class, java.nio.ByteBuffer.class,
- java.security.CodeSource.class}
- )
-})
+
/**
* Unit test for SecureClassLoader.
*
@@ -186,15 +165,6 @@
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00,
(byte) 0x21, };
- /**
- * Tests SecureClassLoader(ClassLoader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verification with null parameter missed",
- method = "SecureClassLoader",
- args = {java.lang.ClassLoader.class}
- )
@KnownFailure("Android doesn't allow null parent.")
public void testSecureClassLoaderClassLoader() throws Exception {
URL[] urls = new URL[] { new URL("http://localhost") };
@@ -208,15 +178,6 @@
}
}
- /**
- * Tests getPermission
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getPermissions",
- args = {java.security.CodeSource.class}
- )
public void testGetPermissions() throws Exception {
URL url = new URL("http://localhost");
CodeSource cs = new CodeSource(url, (Certificate[]) null);
@@ -228,12 +189,6 @@
// /**
// * Tests defineClass(String, byte[], int, int, CodeSource)
// */
-// @TestTargetNew(
-// level = TestLevel.NOT_FEASIBLE,
-// notes = "ClassFormatError, IndexOutOfBoundsException, SecurityException checking missed",
-// method = "defineClass",
-// args = {java.lang.String.class, byte[].class, int.class, int.class, java.security.CodeSource.class}
-// )
// public void _testDefineClassStringbyteArrayintintCodeSource() {
// MyClassLoader ldr = new MyClassLoader();
// Class klass = ldr.define(null, klassData, 0, klassData.length, null);
@@ -243,12 +198,6 @@
// /**
// * Tests defineClass(String, ByteBuffer, CodeSource)
// */
-// @TestTargetNew(
-// level = TestLevel.NOT_FEASIBLE,
-// notes = "ClassFormatError, SecurityException checking missed",
-// method = "defineClass",
-// args = {java.lang.String.class, java.nio.ByteBuffer.class, java.security.CodeSource.class}
-// )
// public void _testDefineClassStringByteBufferCodeSource() {
// MyClassLoader ldr = new MyClassLoader();
// ByteBuffer bbuf = ByteBuffer.wrap(klassData);
diff --git a/luni/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java b/luni/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java
index 459a06e..799ab55 100644
--- a/luni/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java
+++ b/luni/src/test/java/tests/java/sql/DatabaseMetaDataNotSupportedTest.java
@@ -132,28 +132,10 @@
/**
* @tests java.sql.DatabaseMetaData#allProceduresAreCallable()
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Granting not supported.",
- method = "allProceduresAreCallable",
- args = {}
- )
public void test_allProceduresAreCallable() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.allProceduresAreCallable());
}
- /**
- * @tests {@link java.sql.DatabaseMetaData#allTablesAreSelectable()}
- *
- * // NOT_FEASIBLE GRANT and REVOKE are not supported
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "test fails. GRANT and REVOKE not supported",
- method = "allTablesAreSelectable",
- args = {}
- )
@KnownFailure("Not supported ops applied")
public void test_allTablesAreSelectable() throws SQLException {
// grant SELECT privileges
@@ -198,57 +180,29 @@
/**
* @tests java.sql.DatabaseMetaData#dataDefinitionCausesTransactionCommit()
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "dataDefinitionCausesTransactionCommit",
- args = {}
- )
- public void test_dataDefinitionCausesTransactionCommit()
- throws SQLException {
+ public void test_dataDefinitionCausesTransactionCommit() throws SQLException {
// NOT_FEASIBLE: SQLITE does not implement this functionality
}
/**
* @tests java.sql.DatabaseMetaData#dataDefinitionIgnoredInTransactions()
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "dataDefinitionIgnoredInTransactions",
- args = {}
- )
public void test_dataDefinitionIgnoredInTransactions() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.dataDefinitionIgnoredInTransactions());
}
/**
* @tests java.sql.DatabaseMetaData#deletesAreDetected(int)
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "deletesAreDetected",
- args = {int.class}
- )
public void test_deletesAreDetectedI() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.deletesAreDetected(0));
}
/**
* @tests java.sql.DatabaseMetaData#doesMaxRowSizeIncludeBlobs()
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "doesMaxRowSizeIncludeBlobs",
- args = {}
- )
@KnownFailure("not supported")
public void test_doesMaxRowSizeIncludeBlobs() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.doesMaxRowSizeIncludeBlobs());
}
@@ -256,26 +210,10 @@
* @tests java.sql.DatabaseMetaData #getAttributes(java.lang.String,
* java.lang.String, java.lang.String, java.lang.String)
*/
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getAttributes",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_getAttributesLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
}
- /**
- * @tests java.sql.DatabaseMetaData#getCatalogs()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. not supported. Received result wasn't checked.",
- method = "getCatalogs",
- args = {}
- )
public void test_getCatalogs() throws SQLException {
ResultSet rs = meta.getCatalogs();
// NOT_FEASIBLE getCatalog is not supported
@@ -332,18 +270,6 @@
}
- /**
- * @tests {@link java.sql.DatabaseMetaData #getIndexInfo(java.lang.String,
- * java.lang.String, java.lang.String, boolean, boolean)}
- *
- * NOT_FEASIBLE getCatalog is not supported
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. not supported. Received result wasn't checked.",
- method = "getIndexInfo",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, boolean.class, boolean.class}
- )
@KnownFailure("not supported")
public void test_getIndexInfoLjava_lang_StringLjava_lang_StringLjava_lang_StringZZ()
throws SQLException {
@@ -389,18 +315,6 @@
rs.close();
}
- /**
- * @tests {@link java.sql.DatabaseMetaData #getColumnPrivileges(java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String)}
- *
- * NOT_FEASIBLE GRANT is not supported
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. Received result wasn't checked.",
- method = "getColumnPrivileges",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
@KnownFailure("not supported. Privileges are not supported.")
public void test_getColumnPrivilegesLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
@@ -449,18 +363,6 @@
}
- /**
- * @tests {@link java.sql.DatabaseMetaData #getExportedKeys(java.lang.String,
- * java.lang.String, java.lang.String)}
- *
- * NOT_FEASIBLE foreign keys are not supported
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. not supported. Received result wasn't checked.",
- method = "getExportedKeys",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
@KnownFailure("not supported")
public void test_getExportedKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
@@ -513,32 +415,11 @@
rs.close();
}
- /**
- * @tests java.sql.DatabaseMetaData #getProcedureColumns(java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getProcedureColumns",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_getProcedureColumnsLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
meta.getProcedureColumns("", "", "", "");
}
- /**
- * @tests java.sql.DatabaseMetaData #getProcedures(java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getProcedures",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_getProceduresLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
// NOT_FEASIBLE: SQLITE does not implement this functionality
@@ -596,48 +477,16 @@
}
}
- /**
- * @tests java.sql.DatabaseMetaData #getSuperTables(java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getSuperTables",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_getSuperTablesLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
// NOT_FEASIBLE: SQLITE does not implement this functionality
}
- /**
- * @tests java.sql.DatabaseMetaData #getSuperTypes(java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getSuperTypes",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
public void test_getSuperTypesLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
// NOT_FEASIBLE: SQLITE does not implement this functionality
}
- /**
- * @tests java.sql.DatabaseMetaData #getTablePrivileges(java.lang.String,
- * java.lang.String, java.lang.String)
- *
- * NOT_FEASIBLE GRANT is not supported
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. Received result wasn't checked.",
- method = "getTablePrivileges",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
@KnownFailure("not supported. Privileges are not supported.")
public void test_getTablePrivilegesLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
@@ -734,33 +583,11 @@
privileges.close();
}
- /**
- * @tests java.sql.DatabaseMetaData #getUDTs(java.lang.String,
- * java.lang.String, java.lang.String, int[])
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getUDTs",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, int[].class}
- )
public void test_getUDTsLjava_lang_StringLjava_lang_StringLjava_lang_String$I()
throws SQLException {
// NOT_FEASIBLE: JDBC does not implement this functionality
}
- /**
- * @tests java.sql.DatabaseMetaData #getVersionColumns(java.lang.String,
- * java.lang.String, java.lang.String)
- *
- * NOT_FEASIBLE trigger is not supported
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. Received result wasn't checked.Triggers not supported",
- method = "getVersionColumns",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
@KnownFailure("Not supported ops applied")
public void test_getVersionColumnsLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
@@ -809,88 +636,28 @@
}
}
- /**
- * @tests java.sql.DatabaseMetaData#locatorsUpdateCopy()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "locatorsUpdateCopy",
- args = {}
- )
@KnownFailure("not supported")
public void test_locatorsUpdateCopy() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.locatorsUpdateCopy());
}
- /**
- * @tests java.sql.DatabaseMetaData#nullPlusNonNullIsNull()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "nullPlusNonNullIsNull",
- args = {}
- )
public void test_nullPlusNonNullIsNull() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.nullPlusNonNullIsNull());
}
- /**
- * @tests java.sql.DatabaseMetaData#nullsAreSortedAtEnd()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "nullsAreSortedAtEnd",
- args = {}
- )
public void test_nullsAreSortedAtEnd() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.nullsAreSortedAtEnd());
}
- /**
- * @tests java.sql.DatabaseMetaData#nullsAreSortedAtStart()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "nullsAreSortedAtStart",
- args = {}
- )
public void test_nullsAreSortedAtStart() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.nullsAreSortedAtStart());
}
- /**
- * @tests java.sql.DatabaseMetaData#nullsAreSortedHigh()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "nullsAreSortedHigh",
- args = {}
- )
public void test_nullsAreSortedHigh() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.nullsAreSortedHigh());
}
- /**
- * @tests java.sql.DatabaseMetaData#nullsAreSortedLow()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "nullsAreSortedLow",
- args = {}
- )
public void test_nullsAreSortedLow() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.nullsAreSortedLow());
}
@@ -955,645 +722,191 @@
meta.ownUpdatesAreVisible(100));
}
- /**
- * @tests java.sql.DatabaseMetaData#storesLowerCaseIdentifiers()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "storesLowerCaseIdentifiers",
- args = {}
- )
public void test_storesLowerCaseIdentifiers() throws SQLException {
assertFalse(meta.storesLowerCaseIdentifiers());
}
- /**
- * @tests java.sql.DatabaseMetaData#storesLowerCaseQuotedIdentifiers()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "storesLowerCaseQuotedIdentifiers",
- args = {}
- )
public void test_storesLowerCaseQuotedIdentifiers() throws SQLException {
assertFalse(meta.storesLowerCaseQuotedIdentifiers());
}
- /**
- * @tests java.sql.DatabaseMetaData#storesUpperCaseIdentifiers()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "storesUpperCaseIdentifiers",
- args = {}
- )
public void test_storesUpperCaseIdentifiers() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.storesUpperCaseIdentifiers());
}
- /**
- * @tests java.sql.DatabaseMetaData#storesUpperCaseQuotedIdentifiers()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "storesUpperCaseQuotedIdentifiers",
- args = {}
- )
public void test_storesUpperCaseQuotedIdentifiers() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.storesUpperCaseQuotedIdentifiers());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsANSI92EntryLevelSQL()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsANSI92EntryLevelSQL",
- args = {}
- )
@KnownFailure("not supported")
public void test_supportsANSI92EntryLevelSQL() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsANSI92EntryLevelSQL());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsANSI92FullSQL()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsANSI92FullSQL",
- args = {}
- )
public void test_supportsANSI92FullSQL() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsANSI92FullSQL());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsANSI92IntermediateSQL()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsANSI92IntermediateSQL",
- args = {}
- )
public void test_supportsANSI92IntermediateSQL() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsANSI92IntermediateSQL());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsAlterTableWithAddColumn()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsAlterTableWithAddColumn",
- args = {}
- )
public void test_supportsAlterTableWithAddColumn() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsAlterTableWithAddColumn());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsAlterTableWithDropColumn()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsAlterTableWithDropColumn",
- args = {}
- )
public void test_supportsAlterTableWithDropColumn() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsAlterTableWithDropColumn());
-
}
public void test_supportsBatchUpdates() throws SQLException {
assertTrue(meta.supportsBatchUpdates());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCatalogsInDataManipulation()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCatalogsInDataManipulation",
- args = {}
- )
public void test_supportsCatalogsInDataManipulation() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsCatalogsInDataManipulation());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCatalogsInIndexDefinitions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCatalogsInIndexDefinitions",
- args = {}
- )
public void test_supportsCatalogsInIndexDefinitions() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsCatalogsInIndexDefinitions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCatalogsInPrivilegeDefinitions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCatalogsInPrivilegeDefinitions",
- args = {}
- )
- public void test_supportsCatalogsInPrivilegeDefinitions()
- throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
+ public void test_supportsCatalogsInPrivilegeDefinitions() throws SQLException {
assertFalse(meta.supportsCatalogsInPrivilegeDefinitions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCatalogsInProcedureCalls()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCatalogsInProcedureCalls",
- args = {}
- )
public void test_supportsCatalogsInProcedureCalls() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsCatalogsInProcedureCalls());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCatalogsInTableDefinitions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCatalogsInTableDefinitions",
- args = {}
- )
public void test_supportsCatalogsInTableDefinitions() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsCatalogsInTableDefinitions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsConvert()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsConvert",
- args = {}
- )
public void test_supportsConvert() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsConvert());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsConvert(int, int)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsConvert",
- args = {int.class, int.class}
- )
public void test_supportsConvertII() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsConvert());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCoreSQLGrammar()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCoreSQLGrammar",
- args = {}
- )
public void test_supportsCoreSQLGrammar() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsCoreSQLGrammar());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsCorrelatedSubqueries()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsCorrelatedSubqueries",
- args = {}
- )
public void test_supportsCorrelatedSubqueries() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsCorrelatedSubqueries());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsDataDefinitionAndDataManipulationTransactions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsDataDefinitionAndDataManipulationTransactions",
- args = {}
- )
@KnownFailure("not supported")
- public void test_supportsDataDefinitionAndDataManipulationTransactions()
- throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
+ public void test_supportsDataDefinitionAndDataManipulationTransactions() throws SQLException {
assertFalse(meta.supportsDataDefinitionAndDataManipulationTransactions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsDataManipulationTransactionsOnly()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsDataManipulationTransactionsOnly",
- args = {}
- )
- public void test_supportsDataManipulationTransactionsOnly()
- throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
+ public void test_supportsDataManipulationTransactionsOnly() throws SQLException {
assertFalse(meta.supportsDataManipulationTransactionsOnly());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsDifferentTableCorrelationNames()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsDifferentTableCorrelationNames",
- args = {}
- )
- public void test_supportsDifferentTableCorrelationNames()
- throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
+ public void test_supportsDifferentTableCorrelationNames() throws SQLException {
assertFalse(meta.supportsDifferentTableCorrelationNames());
}
-
- /**
- * @tests java.sql.DatabaseMetaData#supportsExtendedSQLGrammar()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsExtendedSQLGrammar",
- args = {}
- )
public void test_supportsExtendedSQLGrammar() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsExtendedSQLGrammar());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsFullOuterJoins()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsFullOuterJoins",
- args = {}
- )
public void test_supportsFullOuterJoins() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsFullOuterJoins());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsGetGeneratedKeys()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsGetGeneratedKeys",
- args = {}
- )
public void test_supportsGetGeneratedKeys() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsGetGeneratedKeys());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsGroupByBeyondSelect()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsGroupByBeyondSelect",
- args = {}
- )
public void test_supportsGroupByBeyondSelect() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsGroupByBeyondSelect());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsIntegrityEnhancementFacility()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsIntegrityEnhancementFacility",
- args = {}
- )
public void test_supportsIntegrityEnhancementFacility() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsIntegrityEnhancementFacility());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsLikeEscapeClause()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsLikeEscapeClause",
- args = {}
- )
public void test_supportsLikeEscapeClause() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsLikeEscapeClause());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsLimitedOuterJoins()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsLimitedOuterJoins",
- args = {}
- )
public void test_supportsLimitedOuterJoins() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsLimitedOuterJoins());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsMinimumSQLGrammar()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsMinimumSQLGrammar",
- args = {}
- )
@KnownFailure("not supported")
public void test_supportsMinimumSQLGrammar() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsMinimumSQLGrammar());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsMixedCaseIdentifiers()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsMixedCaseIdentifiers",
- args = {}
- )
public void test_supportsMixedCaseIdentifiers() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsMixedCaseIdentifiers());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsMixedCaseQuotedIdentifiers()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsMixedCaseQuotedIdentifiers",
- args = {}
- )
public void test_supportsMixedCaseQuotedIdentifiers() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsMixedCaseQuotedIdentifiers());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsMultipleOpenResults()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsMultipleOpenResults",
- args = {}
- )
public void test_supportsMultipleOpenResults() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsMultipleOpenResults());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsMultipleResultSets()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsMultipleResultSets",
- args = {}
- )
public void test_supportsMultipleResultSets() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsMultipleResultSets());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsMultipleTransactions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsMultipleTransactions",
- args = {}
- )
public void test_supportsMultipleTransactions() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsMultipleTransactions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsNamedParameters()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsNamedParameters",
- args = {}
- )
public void test_supportsNamedParameters() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsNamedParameters());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsOpenCursorsAcrossCommit()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsOpenCursorsAcrossCommit",
- args = {}
- )
public void test_supportsOpenCursorsAcrossCommit() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsOpenCursorsAcrossCommit());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsOpenCursorsAcrossRollback()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsOpenCursorsAcrossRollback",
- args = {}
- )
public void test_supportsOpenCursorsAcrossRollback() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsOpenCursorsAcrossRollback());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsOpenStatementsAcrossCommit()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsOpenStatementsAcrossCommit",
- args = {}
- )
public void test_supportsOpenStatementsAcrossCommit() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsOpenStatementsAcrossCommit());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsOpenStatementsAcrossRollback()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsOpenStatementsAcrossRollback",
- args = {}
- )
public void test_supportsOpenStatementsAcrossRollback() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsOpenStatementsAcrossRollback());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsOuterJoins()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsOuterJoins",
- args = {}
- )
public void test_supportsOuterJoins() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsOuterJoins());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsPositionedDelete()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsPositionedDelete",
- args = {}
- )
public void test_supportsPositionedDelete() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsPositionedDelete());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsPositionedUpdate()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsPositionedUpdate",
- args = {}
- )
public void test_supportsPositionedUpdate() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsPositionedUpdate());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsResultSetConcurrency(int, int)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsResultSetConcurrency",
- args = {int.class, int.class}
- )
public void test_supportsResultSetConcurrencyII() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsResultSetConcurrency(0,0));
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsResultSetHoldability(int)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsResultSetHoldability",
- args = {int.class}
- )
public void test_supportsResultSetHoldabilityI() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsResultSetHoldability(0));
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsResultSetType(int)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported. Verification with invalid parameters missed.",
- method = "supportsResultSetType",
- args = {int.class}
- )
@KnownFailure("not supported")
public void test_supportsResultSetTypeI() throws SQLException {
- // NOT_FEASIBLE not supported
assertTrue("database supports TYPE_FORWARD_ONLY type", meta
.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY));
assertFalse("database doesn't support TYPE_SCROLL_INSENSITIVE type",
@@ -1604,170 +917,52 @@
.supportsResultSetType(100));
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSavepoints()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSavepoints",
- args = {}
- )
public void test_supportsSavepoints() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSavepoints());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSchemasInDataManipulation()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSchemasInDataManipulation",
- args = {}
- )
public void test_supportsSchemasInDataManipulation() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSchemasInDataManipulation());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSchemasInIndexDefinitions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSchemasInIndexDefinitions",
- args = {}
- )
public void test_supportsSchemasInIndexDefinitions() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSchemasInIndexDefinitions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSchemasInPrivilegeDefinitions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSchemasInPrivilegeDefinitions",
- args = {}
- )
- public void test_supportsSchemasInPrivilegeDefinitions()
- throws SQLException {
+ public void test_supportsSchemasInPrivilegeDefinitions() throws SQLException {
// NOT_FEASIBLE: SQLITE does not implement this functionality
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSchemasInProcedureCalls()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSchemasInProcedureCalls",
- args = {}
- )
public void test_supportsSchemasInProcedureCalls() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSchemasInProcedureCalls());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSchemasInTableDefinitions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSchemasInTableDefinitions",
- args = {}
- )
public void test_supportsSchemasInTableDefinitions() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSchemasInTableDefinitions());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsStatementPooling()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsStatementPooling",
- args = {}
- )
public void test_supportsStatementPooling() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsStatementPooling());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsStoredProcedures()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsStoredProcedures",
- args = {}
- )
public void test_supportsStoredProcedures() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsStoredProcedures());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSubqueriesInComparisons()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSubqueriesInComparisons",
- args = {}
- )
@KnownFailure("not supported")
public void test_supportsSubqueriesInComparisons() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSubqueriesInComparisons());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSubqueriesInIns()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSubqueriesInIns",
- args = {}
- )
@KnownFailure("not supported")
public void test_supportsSubqueriesInIns() throws SQLException {
assertFalse(meta.supportsSubqueriesInIns());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsSubqueriesInQuantifieds()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsSubqueriesInQuantifieds",
- args = {}
- )
public void test_supportsSubqueriesInQuantifieds() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.supportsSubqueriesInQuantifieds());
}
- /**
- * @tests java.sql.DatabaseMetaData#supportsTransactions()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "supportsTransactions",
- args = {}
- )
@KnownFailure("not supported")
public void test_supportsTransactions() throws SQLException {
assertFalse(meta.supportsTransactions());
@@ -1781,32 +976,12 @@
assertTrue(meta.supportsUnionAll());
}
- /**
- * @tests java.sql.DatabaseMetaData#usesLocalFilePerTable()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "usesLocalFilePerTable",
- args = {}
- )
public void test_usesLocalFilePerTable() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.usesLocalFilePerTable());
}
- /**
- * @tests java.sql.DatabaseMetaData#usesLocalFiles()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "usesLocalFiles",
- args = {}
- )
@KnownFailure("not supported")
public void test_usesLocalFiles() throws SQLException {
- // NOT_FEASIBLE: SQLITE does not implement this functionality
assertFalse(meta.usesLocalFiles());
}
diff --git a/luni/src/test/java/tests/java/sql/DatabaseMetaDataTest.java b/luni/src/test/java/tests/java/sql/DatabaseMetaDataTest.java
index 09abcd4..d334fc1 100755
--- a/luni/src/test/java/tests/java/sql/DatabaseMetaDataTest.java
+++ b/luni/src/test/java/tests/java/sql/DatabaseMetaDataTest.java
@@ -774,16 +774,6 @@
}
- /**
- * @tests java.sql.DatabaseMetaData #getImportedKeys(java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Test fails: Keys are not supported",
- method = "getImportedKeys",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
@KnownFailure("Keys are not supported: Ticket 91")
public void test_getImportedKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
throws SQLException {
@@ -1435,18 +1425,7 @@
}
- /**
- * @tests java.sql.DatabaseMetaData#getUserName()
- *
- * NOT_FEASIBLE not supported
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException checking test fails",
- method = "getUserName",
- args = {}
- )
- @KnownFailure("Ticket 98")
+ @KnownFailure("Ticket 98")
public void s() throws SQLException {
assertEquals("Wrong user name", Support_SQL.sqlUser, meta.getUserName());
diff --git a/luni/src/test/java/tests/javax/sql/ConnectionEventListenerTest.java b/luni/src/test/java/tests/javax/sql/ConnectionEventListenerTest.java
deleted file mode 100644
index a89b026..0000000
--- a/luni/src/test/java/tests/javax/sql/ConnectionEventListenerTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.sql.ConnectionEvent;
-import javax.sql.ConnectionEventListener;
-
-@TestTargetClass(ConnectionEventListener.class)
-public class ConnectionEventListenerTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.ConnectionEventListener#connectionClosed(javax.sql.ConnectionEvent)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connectionClosed",
- args = {javax.sql.ConnectionEvent.class}
- )
- public void testConnectionClosed() {
- fail("Not yet implemented"); // TODO
- }
-
- /**
- * @test {@link javax.sql.ConnectionEventListener#connectionErrorOccurred(ConnectionEvent)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connectionErrorOccurred",
- args = {javax.sql.ConnectionEvent.class}
- )
- public void testConnectionErrorOccurred() {
- fail("Not yet implemented"); // TODO
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/ConnectionPoolDataSourceTest.java b/luni/src/test/java/tests/javax/sql/ConnectionPoolDataSourceTest.java
deleted file mode 100644
index 7dafc46..0000000
--- a/luni/src/test/java/tests/javax/sql/ConnectionPoolDataSourceTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.PrintWriter;
-
-import javax.sql.ConnectionPoolDataSource;
-
-
-@TestTargetClass(ConnectionPoolDataSource.class)
-public class ConnectionPoolDataSourceTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.ConnectionPoolDataSource#getLoginTimeout()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLoginTimeout",
- args = {}
- )
- public void testGetLoginTimeout() {
- fail("Not yet implemented"); // NOT_FEASIBLE
- }
-
- /**
- * @tests {@link javax.sql.ConnectionPoolDataSource#getLogWriter()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLogWriter",
- args = {}
- )
- public void testGetLogWriter() {
- fail("Not yet implemented"); // NOT_FEASIBLE
- }
-
- /**
- * @tests {@link javax.sql.ConnectionPoolDataSource#getPooledConnection()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getPooledConnection",
- args = {}
- )
- public void testGetPooledConnection() {
- fail("Not yet implemented"); // NOT_FEASIBLE
- }
-
- /**
- * @tests {@link javax.sql.ConnectionPoolDataSource#getPooledConnection(String, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getPooledConnection",
- args = {String.class, String.class}
- )
- public void testGetPooledConnectionStringString() {
- fail("Not yet implemented"); // NOT_FEASIBLE
- }
-
- /**
- * @tests {@link javax.sql.ConnectionPoolDataSource#setLoginTimeout(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setLoginTimeout",
- args = {int.class}
- )
- public void testSetLoginTimeout() {
- fail("Not yet implemented"); // NOT_FEASIBLE
- }
-
- /**
- * @tests {@link javax.sql.ConnectionPoolDataSource#setLogWriter(java.io.PrintWriter)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setLogWriter",
- args = {java.io.PrintWriter.class}
- )
- public void testSetLogWriter() {
- fail("Not yet implemented"); // NOT_FEASIBLE
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/DataSourceTest.java b/luni/src/test/java/tests/javax/sql/DataSourceTest.java
deleted file mode 100644
index 30563c9..0000000
--- a/luni/src/test/java/tests/javax/sql/DataSourceTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.PrintWriter;
-
-import javax.sql.DataSource;
-
-@TestTargetClass(DataSource.class)
-public class DataSourceTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.DataSource#getConnection()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getConnection",
- args = {}
- )
- public void testGetConnection() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.DataSource#getConnection(String, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getConnection",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void testGetConnectionStringString() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.DataSource#getLoginTimeout()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLoginTimeout",
- args = {}
- )
- public void testGetLoginTimeout() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.DataSource#getLogWriter()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLogWriter",
- args = {}
- )
- public void testGetLogWriter() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.DataSource#setLoginTimeout(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setLoginTimeout",
- args = {int.class}
- )
- public void testSetLoginTimeout() {
- fail("Not yet implemented");
- }
-
-
- /**
- * @tests {@link javax.sql.DataSource#setLogWriter(java.io.PrintWriter)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setLogWriter",
- args = {PrintWriter.class}
- )
- public void testSetLogWriter() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/PooledConnectionTest.java b/luni/src/test/java/tests/javax/sql/PooledConnectionTest.java
deleted file mode 100644
index 2902e8b..0000000
--- a/luni/src/test/java/tests/javax/sql/PooledConnectionTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import javax.sql.ConnectionEventListener;
-import javax.sql.PooledConnection;
-
-@TestTargetClass(PooledConnection.class)
-public class PooledConnectionTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.PooledConnection#addConnectionEventListener(javax.sql.ConnectionEventListener)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "addConnectionEventListener",
- args = {javax.sql.ConnectionEventListener.class}
- )
- public void testAddConnectionEventListener() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.PooledConnection#close()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "close",
- args = {}
- )
- public void testClose() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.PooledConnection#getConnection()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getConnection",
- args = {}
- )
- public void testGetConnection() {
- fail("Not yet implemented");
- }
-
-
- /**
- * @tests {@link javax.sql.PooledConnection#removeConnectionEventListener(ConnectionEventListener)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "removeConnectionEventListener",
- args = {javax.sql.ConnectionEventListener.class}
- )
- public void testRemoveConnectionEventListener() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/RowSetInternalTest.java b/luni/src/test/java/tests/javax/sql/RowSetInternalTest.java
deleted file mode 100644
index ff9de34..0000000
--- a/luni/src/test/java/tests/javax/sql/RowSetInternalTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.sql.RowSetInternal;
-import javax.sql.RowSetMetaData;
-
-@TestTargetClass(RowSetInternal.class)
-public class RowSetInternalTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.RowSetInternal#getConnection()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getConnection",
- args = {}
- )
- public void testGetConnection() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetInternal#getOriginal()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOriginal",
- args = {}
- )
- public void testGetOriginal() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetInternal#getOriginalRow()}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOriginalRow",
- args = {}
- )
- public void testGetOriginalRow() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getParams",
- args = {}
- )
- public void testGetParams() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetInternal#setMetaData(javax.sql.RowSetMetaData)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setMetaData",
- args = {javax.sql.RowSetMetaData.class}
- )
- public void testSetMetaData() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/RowSetListenerTest.java b/luni/src/test/java/tests/javax/sql/RowSetListenerTest.java
deleted file mode 100644
index d238a42..0000000
--- a/luni/src/test/java/tests/javax/sql/RowSetListenerTest.java
+++ /dev/null
@@ -1,74 +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 tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.sql.RowSetEvent;
-import javax.sql.RowSetListener;
-
-/**
- *
- */
-@TestTargetClass(RowSetListener.class)
-public class RowSetListenerTest extends TestCase {
-
- /**
- * Test method for {@link javax.sql.RowSetListener#cursorMoved(javax.sql.RowSetEvent)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "cursorMoved",
- args = {javax.sql.RowSetEvent.class}
- )
- public void testCursorMoved() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link javax.sql.RowSetListener#rowChanged(javax.sql.RowSetEvent)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "rowChanged",
- args = {javax.sql.RowSetEvent.class}
- )
- public void testRowChanged() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link javax.sql.RowSetListener#rowSetChanged(javax.sql.RowSetEvent)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "rowSetChanged",
- args = {javax.sql.RowSetEvent.class}
- )
- public void testRowSetChanged() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/RowSetMetaDataTest.java b/luni/src/test/java/tests/javax/sql/RowSetMetaDataTest.java
deleted file mode 100644
index 73a2f75..0000000
--- a/luni/src/test/java/tests/javax/sql/RowSetMetaDataTest.java
+++ /dev/null
@@ -1,241 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.sql.RowSetMetaData;
-
-/**
- * @author AGR
- *
- */
-@TestTargetClass(RowSetMetaData.class)
-public class RowSetMetaDataTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setAutoIncrement(int, boolean)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setAutoIncrement",
- args = {int.class, boolean.class}
- )
- public void testSetAutoIncrement() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setCaseSensitive(int, boolean)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCaseSensitive",
- args = {int.class, boolean.class}
- )
- public void testSetCaseSensitive() {
- fail("Not yet implemented");
- }
-
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setCatalogName(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCatalogName",
- args = {int.class, java.lang.String.class}
- )
- public void testSetCatalogName() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setColumnCount(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setColumnCount",
- args = {int.class}
- )
- public void testSetColumnCount() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setColumnDisplaySize(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setColumnDisplaySize",
- args = {int.class, int.class}
- )
- public void testSetColumnDisplaySize() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setColumnLabel(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setColumnLabel",
- args = {int.class, java.lang.String.class}
- )
- public void testSetColumnLabel() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setColumnName(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setColumnName",
- args = {int.class, java.lang.String.class}
- )
- public void testSetColumnName() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setColumnType(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setColumnType",
- args = {int.class, int.class}
- )
- public void testSetColumnType() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setColumnTypeName(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setColumnTypeName",
- args = {int.class, java.lang.String.class}
- )
- public void testSetColumnTypeName() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setCurrency(int, boolean)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCurrency",
- args = {int.class, boolean.class}
- )
- public void testSetCurrency() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setNullable(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setNullable",
- args = {int.class, int.class}
- )
- public void testSetNullable() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setPrecision(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setPrecision",
- args = {int.class, int.class}
- )
- public void testSetPrecision() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setScale(int, int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setScale",
- args = {int.class, int.class}
- )
- public void testSetScale() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setSchemaName(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setSchemaName",
- args = {int.class, java.lang.String.class}
- )
- public void testSetSchemaName() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setSearchable(int, boolean)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setSearchable",
- args = {int.class, boolean.class}
- )
- public void testSetSearchable() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setSigned(int, boolean)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setSigned",
- args = {int.class, boolean.class}
- )
- public void testSetSigned() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSetMetaData#setTableName(int, String)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTableName",
- args = {int.class, java.lang.String.class}
- )
- public void testSetTableName() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/RowSetReaderTest.java b/luni/src/test/java/tests/javax/sql/RowSetReaderTest.java
deleted file mode 100644
index 0a24234..0000000
--- a/luni/src/test/java/tests/javax/sql/RowSetReaderTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.sql.RowSetInternal;
-import javax.sql.RowSetReader;
-
-@TestTargetClass(RowSetReader.class)
-public class RowSetReaderTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.RowSetReader#readData(RowSetInternal)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readData",
- args = {javax.sql.RowSetInternal.class}
- )
- public void testReadData() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/javax/sql/RowSetTest.java b/luni/src/test/java/tests/javax/sql/RowSetTest.java
deleted file mode 100644
index cea214e..0000000
--- a/luni/src/test/java/tests/javax/sql/RowSetTest.java
+++ /dev/null
@@ -1,624 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.InputStream;
-import java.io.Reader;
-import java.math.BigDecimal;
-import java.sql.Array;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.Date;
-import java.sql.Ref;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Calendar;
-import java.util.Map;
-
-import javax.sql.RowSet;
-import javax.sql.RowSetListener;
-
-/**
- *No Implementation class of this interface is available: tests not feasible
- */
-@TestTargetClass(RowSet.class)
-public class RowSetTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.RowSet#addRowSetListener(javax.sql.RowSetListener)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "addRowSetListener",
- args = {javax.sql.RowSetListener.class}
- )
- public void testAddRowSetListener() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSet#clearParameters()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "clearParameters",
- args = {}
- )
- public void testClearParameters() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSet#addRowSetListener(javax.sql.RowSetListener)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "execute",
- args = {}
- )
- public void testExecute() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSet#getCommand()}.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCommand",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getCommand",
- args = {}
- )
- })
- public void testSetGetCommand() {
- fail("Not yet implemented");
- }
-
- /**
- * @tests {@link javax.sql.RowSet#getDataSourceName()}.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDataSourceName",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDataSourceName",
- args = {}
- )
- })
- public void testSetGetDataSourceName() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getEscapeProcessing",
- args = {}
- )
- public void testSetGetEscapeProcessing() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getMaxFieldSize",
- args = {}
- )
- public void testSetGetMaxFieldSize() {
- fail("Not yet implemented");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getMaxRows",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setMaxRows",
- args = {int.class}
- )
- })
- public void testSetGetMaxRows() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getPassword",
- args = {}
- )
- public void testSetGetPassword() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getQueryTimeout",
- args = {}
- )
- public void testSetGetQueryTimeout() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTransactionIsolation",
- args = {}
- )
- public void testSetGetTransactionIsolation() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTypeMap",
- args = {}
- )
- public void testSetGetTypeMap() {
- fail("Not yet implemented");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setUrl",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getUrl",
- args = {}
- )
- })
- public void testSetGetUrl() {
- fail("Not yet implemented");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setUsername",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getUsername",
- args = {}
- )
- })
- public void testSetGetUsername() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "isReadOnly",
- args = {}
- )
- public void testIsReadOnly() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "removeRowSetListener",
- args = {javax.sql.RowSetListener.class}
- )
- public void testRemoveRowSetListener() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setArray",
- args = {int.class, java.sql.Array.class}
- )
- public void testSetArray() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setAsciiStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
- public void testSetGetAsciiStream() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBigDecimal",
- args = {int.class, java.math.BigDecimal.class}
- )
- public void testSetGetBigDecimal() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBinaryStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
- public void testSetGetBinaryStream() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBlob",
- args = {int.class, java.sql.Blob.class}
- )
- public void testSetGetBlob() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBoolean",
- args = {int.class, boolean.class}
- )
- public void testSetGetBoolean() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setByte",
- args = {int.class, byte.class}
- )
- public void testSetGetByte() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBytes",
- args = {int.class, byte[].class}
- )
- public void testSetGetBytes() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCharacterStream",
- args = {int.class, java.io.Reader.class, int.class}
- )
- public void testSetGetCharacterStream() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setClob",
- args = {int.class, java.sql.Clob.class}
- )
- public void testSetGetClob() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setConcurrency",
- args = {int.class}
- )
- public void testSetGetConcurrency() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDate",
- args = {int.class, java.sql.Date.class}
- )
- public void testSetGetDateIntDate() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDate",
- args = {int.class, java.sql.Date.class, java.util.Calendar.class}
- )
- public void testSetDateIntDateCalendar() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setEscapeProcessing",
- args = {boolean.class}
- )
- public void testSetEscapeProcessing() {
-
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDouble",
- args = {int.class, double.class}
- )
- public void testSetGetDouble() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setFloat",
- args = {int.class, float.class}
- )
- public void testSetGetFloat() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setInt",
- args = {int.class, int.class}
- )
- public void testSetGetInt() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setLong",
- args = {int.class, long.class}
- )
- public void testSetGetLong() {
- fail("Not yet implemented");
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getMaxFieldSize",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setMaxFieldSize",
- args = {int.class}
- )
- })
- public void testSetGetGetMaxFieldSize() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setNull",
- args = {int.class, int.class}
- )
- public void testSetGetNullIntInt() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setNull",
- args = {int.class, int.class, java.lang.String.class}
- )
- public void testSetGetNullIntIntString() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {int.class, java.lang.Object.class}
- )
- public void testSetGetObjectIntObject() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {int.class, java.lang.Object.class, int.class}
- )
- public void testSetGetObjectIntObjectInt() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {int.class, java.lang.Object.class, int.class, int.class}
- )
- public void testSetGetObjectIntObjectIntInt() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setPassword",
- args = {java.lang.String.class}
- )
- public void testSetPassword() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setQueryTimeout",
- args = {int.class}
- )
- public void testSetQueryTimeout() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setReadOnly",
- args = {boolean.class}
- )
- public void testSetReadOnly() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setRef",
- args = {int.class, java.sql.Ref.class}
- )
- public void testSetRef() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setShort",
- args = {int.class, short.class}
- )
- public void testSetShort() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setString",
- args = {int.class, java.lang.String.class}
- )
- public void testSetString() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTime",
- args = {int.class, java.sql.Time.class}
- )
- public void testSetTimeIntTime() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTime",
- args = {int.class, java.sql.Time.class, java.util.Calendar.class}
- )
- public void testSetTimeIntTimeCalendar() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTimestamp",
- args = {int.class, java.sql.Timestamp.class}
- )
- public void testSetTimestampIntTimestamp() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTimestamp",
- args = {int.class, java.sql.Timestamp.class, java.util.Calendar.class}
- )
- public void testSetTimestampIntTimestampCalendar() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTransactionIsolation",
- args = {int.class}
- )
- public void testSetTransactionIsolation() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setType",
- args = {int.class}
- )
- public void testSetType() {
- fail("Not yet implemented");
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTypeMap",
- args = {java.util.Map.class}
- )
- public void testSetTypeMap() {
- fail("Not yet implemented");
- }
-}
diff --git a/luni/src/test/java/tests/javax/sql/RowSetWriterTest.java b/luni/src/test/java/tests/javax/sql/RowSetWriterTest.java
deleted file mode 100644
index 1b9f972..0000000
--- a/luni/src/test/java/tests/javax/sql/RowSetWriterTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package tests.javax.sql;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.sql.RowSetInternal;
-import javax.sql.RowSetWriter;
-
-@TestTargetClass(RowSetWriter.class)
-public class RowSetWriterTest extends TestCase {
-
- /**
- * @tests {@link javax.sql.RowSetWriter#writeData(javax.sql.RowSetInternal)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeData",
- args = {javax.sql.RowSetInternal.class}
- )
- public void testWriteData() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/security/cert/X509CertSelectorTest.java b/luni/src/test/java/tests/security/cert/X509CertSelectorTest.java
index 383b578..04d6c48 100644
--- a/luni/src/test/java/tests/security/cert/X509CertSelectorTest.java
+++ b/luni/src/test/java/tests/security/cert/X509CertSelectorTest.java
@@ -658,16 +658,7 @@
Collection<List<?>> sans = sans1.getPairsList();
selector.setPathToNames(sans);
-
- Collection<List<?>> col = selector.getPathToNames();
- Iterator<List<?>> i = col.iterator();
- while (i.hasNext()) {
- Object o = i.next();
- if (!(o instanceof List)) {
- fail("expected a List");
- }
- }
-
+ selector.getPathToNames();
} catch (IOException e) {
e.printStackTrace();
fail("Unexpected IOException was thrown.");
@@ -1468,16 +1459,7 @@
Collection<List<?>> sans = sans1.getPairsList();
selector.setPathToNames(sans);
-
- Collection<List<?>> col = selector.getPathToNames();
- Iterator<List<?>> i = col.iterator();
- while (i.hasNext()) {
- Object o = i.next();
- if (!(o instanceof List)) {
- fail("expected a List");
- }
- }
-
+ selector.getPathToNames();
} catch (IOException e) {
e.printStackTrace();
fail("Unexpected IOException was thrown.");
@@ -1771,15 +1753,7 @@
selector.setSubjectAlternativeNames(sans);
- Collection<List<?>> col = selector.getSubjectAlternativeNames();
- Iterator<List<?>> i = col.iterator();
- while (i.hasNext()) {
- Object o = i.next();
- if (!(o instanceof List)) {
- fail("expected a List");
- }
- }
-
+ selector.getSubjectAlternativeNames();
} catch (IOException e) {
e.printStackTrace();
fail("Unexpected IOException was thrown.");
diff --git a/luni/src/test/java/tests/sql/AllTests.java b/luni/src/test/java/tests/sql/AllTests.java
deleted file mode 100644
index e782d84..0000000
--- a/luni/src/test/java/tests/sql/AllTests.java
+++ /dev/null
@@ -1,43 +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.sql;
-
-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 SQL test suites");
- // $JUnit-BEGIN$
- suite.addTest(tests.java.sql.AllTests.suite());
-
- // These don't do blackbox testing *and* crash JUnit on the RI
- // suite.addTest(tests.SQLite.AllTests.suite());
-
- suite.addTestSuite(tests.sql.ConnectionTest.class);
- suite.addTestSuite(tests.sql.PreparedStatementTest.class);
- suite.addTestSuite(tests.sql.ResultSetGetterTests.class);
- suite.addTestSuite(tests.sql.ResultSetMetaDataTest.class);
- suite.addTestSuite(tests.sql.ResultSetTest.class);
- suite.addTestSuite(tests.sql.StatementTest.class);
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/sql/ArrayTest.java b/luni/src/test/java/tests/sql/ArrayTest.java
deleted file mode 100644
index f3b49d6..0000000
--- a/luni/src/test/java/tests/sql/ArrayTest.java
+++ /dev/null
@@ -1,165 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.Array;
-import java.util.Map;
-
-/**
- * @author andrea@google.com (Your Name Here)
- *
- */
-@TestTargetClass(Array.class)
-public class ArrayTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.Array#getArray()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {}
- )
- public void testGetArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getArray(long, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {long.class, int.class}
- )
- public void testGetArrayLongInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getArray(long, int, java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {long.class, int.class, Map.class}
- )
- public void testGetArrayLongIntMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getArray(java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {Map.class}
- )
- public void testGetArrayMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getBaseType()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBaseType",
- args = {}
- )
- public void testGetBaseType() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getBaseTypeName()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBaseTypeName",
- args = {}
- )
- public void testGetBaseTypeName() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getResultSet()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getResultSet",
- args = {}
- )
- public void testGetResultSet() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getResultSet(long, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getResultSet",
- args = {long.class, int.class}
- )
- public void testGetResultSetLongInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getResultSet(long, int, java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getResultSet",
- args = {long.class, int.class, Map.class}
- )
- public void testGetResultSetLongIntMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Array#getResultSet(java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getResultSet",
- args = {Map.class}
- )
- public void testGetResultSetMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/BlobTest.java b/luni/src/test/java/tests/sql/BlobTest.java
deleted file mode 100644
index 43fb2a6..0000000
--- a/luni/src/test/java/tests/sql/BlobTest.java
+++ /dev/null
@@ -1,151 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.Blob;
-
-/**
- * @author andrea@google.com (Your Name Here)
- *
- */
-@TestTargetClass(Blob.class)
-public class BlobTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.Blob#getBinaryStream()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBinaryStream",
- args = {}
- )
- public void testGetBinaryStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#getBytes(long, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBytes",
- args = {long.class, int.class}
- )
- public void testGetBytes() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#length()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "length",
- args = {}
- )
- public void testLength() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#position(java.sql.Blob, long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "position",
- args = {Blob.class, long.class}
- )
- public void testPositionBlobLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#position(byte[], long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "position",
- args = {byte[].class, long.class}
- )
- public void testPositionByteArrayLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#setBinaryStream(long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBinaryStream",
- args = {long.class}
- )
- public void testSetBinaryStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#setBytes(long, byte[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBytes",
- args = {long.class, byte[].class}
- )
- public void testSetBytesLongByteArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#setBytes(long, byte[], int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBytes",
- args = {long.class, byte[].class, int.class, int.class}
- )
- public void testSetBytesLongByteArrayIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Blob#truncate(long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "truncate",
- args = {long.class}
- )
- public void testTruncate() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/CallableStatementTest.java b/luni/src/test/java/tests/sql/CallableStatementTest.java
deleted file mode 100644
index db7aca1..0000000
--- a/luni/src/test/java/tests/sql/CallableStatementTest.java
+++ /dev/null
@@ -1,1070 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.io.InputStream;
-import java.io.Reader;
-import java.math.BigDecimal;
-import java.net.URL;
-import java.sql.CallableStatement;
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Calendar;
-import java.util.Map;
-
-/**
- * @author andrea@google.com (Your Name Here)
- *
- */
-@TestTargetClass(CallableStatement.class)
-public class CallableStatementTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.CallableStatement#getArray(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {int.class}
- )
- public void testGetArrayInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getArray(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {String.class}
- )
- public void testGetArrayString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBigDecimal(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBigDecimal",
- args = {int.class}
- )
- public void testGetBigDecimalInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBigDecimal(int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBigDecimal",
- args = {int.class, int.class}
- )
- public void testGetBigDecimalIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBigDecimal(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBigDecimal",
- args = {String.class}
- )
- public void testGetBigDecimalString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBlob(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBlob",
- args = {int.class}
- )
- public void testGetBlobInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBlob(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBlob",
- args = {String.class}
- )
- public void testGetBlobString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBoolean(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBoolean",
- args = {int.class}
- )
- public void testGetBooleanInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBoolean(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBoolean",
- args = {String.class}
- )
- public void testGetBooleanString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getByte(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getByte",
- args = {int.class}
- )
- public void testGetByteInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getByte(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getByte",
- args = {String.class}
- )
- public void testGetByteString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBytes(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBytes",
- args = {int.class}
- )
- public void testGetBytesInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getBytes(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBytes",
- args = {String.class}
- )
- public void testGetBytesString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getClob(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getClob",
- args = {int.class}
- )
- public void testGetClobInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getClob(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getClob",
- args = {String.class}
- )
- public void testGetClobString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getDate(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDate",
- args = {int.class}
- )
- public void testGetDateInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getDate(int, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDate",
- args = {int.class, Calendar.class}
- )
- public void testGetDateIntCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getDate(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDate",
- args = {String.class}
- )
- public void testGetDateString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getDate(java.lang.String, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDate",
- args = {String.class, Calendar.class}
- )
- public void testGetDateStringCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getDouble(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDouble",
- args = {int.class}
- )
- public void testGetDoubleInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getDouble(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getDouble",
- args = {String.class}
- )
- public void testGetDoubleString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getFloat(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getFloat",
- args = {int.class}
- )
- public void testGetFloatInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getFloat(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getFloat",
- args = {String.class}
- )
- public void testGetFloatString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getInt(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getInt",
- args = {int.class}
- )
- public void testGetIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getInt(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getInt",
- args = {String.class}
- )
- public void testGetIntString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getLong(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLong",
- args = {int.class}
- )
- public void testGetLongInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getLong(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLong",
- args = {String.class}
- )
- public void testGetLongString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getObject(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {int.class}
- )
- public void testGetObjectInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getObject(int, java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {int.class, Map.class}
- )
- public void testGetObjectIntMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getObject(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {String.class}
- )
- public void testGetObjectString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getObject(java.lang.String, java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {String.class, Map.class}
- )
- public void testGetObjectStringMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getRef(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRef",
- args = {int.class}
- )
- public void testGetRefInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getRef(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRef",
- args = {String.class}
- )
- public void testGetRefString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getShort(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getShort",
- args = {int.class}
- )
- public void testGetShortInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getShort(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getShort",
- args = {String.class}
- )
- public void testGetShortString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getString(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getString",
- args = {int.class}
- )
- public void testGetStringInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getString(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getString",
- args = {String.class}
- )
- public void testGetStringString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTime(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTime",
- args = {int.class}
- )
- public void testGetTimeInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTime(int, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTime",
- args = {int.class, Calendar.class}
- )
- public void testGetTimeIntCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTime(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTime",
- args = {String.class}
- )
- public void testGetTimeString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTime(java.lang.String, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTime",
- args = {String.class, Calendar.class}
- )
- public void testGetTimeStringCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTimestamp(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTimestamp",
- args = {int.class}
- )
- public void testGetTimestampInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTimestamp(int, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTimestamp",
- args = {int.class, Calendar.class}
- )
- public void testGetTimestampIntCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTimestamp(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTimestamp",
- args = {String.class}
- )
- public void testGetTimestampString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getTimestamp(java.lang.String, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTimestamp",
- args = {String.class, Calendar.class}
- )
- public void testGetTimestampStringCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getURL(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getURL",
- args = {int.class}
- )
- public void testGetURLInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#getURL(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getURL",
- args = {String.class}
- )
- public void testGetURLString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#registerOutParameter(int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "registerOutParameter",
- args = {int.class, int.class}
- )
- public void testRegisterOutParameterIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#registerOutParameter(int, int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "registerOutParameter",
- args = {int.class, int.class, int.class}
- )
- public void testRegisterOutParameterIntIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#registerOutParameter(int, int, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "registerOutParameter",
- args = {int.class, int.class, String.class}
- )
- public void testRegisterOutParameterIntIntString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#registerOutParameter(java.lang.String, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "registerOutParameter",
- args = {String.class, int.class}
- )
- public void testRegisterOutParameterStringInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#registerOutParameter(java.lang.String, int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "registerOutParameter",
- args = {String.class, int.class, int.class}
- )
- public void testRegisterOutParameterStringIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#registerOutParameter(java.lang.String, int, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "registerOutParameter",
- args = {String.class, int.class, String.class}
- )
- public void testRegisterOutParameterStringIntString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setAsciiStream",
- args = {String.class, InputStream.class, int.class}
- )
- public void testSetAsciiStreamStringInputStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setBigDecimal(java.lang.String, java.math.BigDecimal)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBigDecimal",
- args = {String.class, BigDecimal.class}
- )
- public void testSetBigDecimalStringBigDecimal() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBinaryStream",
- args = {String.class, InputStream.class, int.class}
- )
- public void testSetBinaryStreamStringInputStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setBoolean(java.lang.String, boolean)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBoolean",
- args = {String.class, boolean.class}
- )
- public void testSetBooleanStringBoolean() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setByte(java.lang.String, byte)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setByte",
- args = {String.class, byte.class}
- )
- public void testSetByteStringByte() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setBytes(java.lang.String, byte[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setBytes",
- args = {String.class, byte[].class}
- )
- public void testSetBytesStringByteArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCharacterStream",
- args = {String.class, Reader.class, int.class}
- )
- public void testSetCharacterStreamStringReaderInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDate",
- args = {String.class, Date.class}
- )
- public void testSetDateStringDate() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDate",
- args = {String.class, Date.class, Calendar.class}
- )
- public void testSetDateStringDateCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setDouble(java.lang.String, double)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setDouble",
- args = {String.class, double.class}
- )
- public void testSetDoubleStringDouble() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setFloat(java.lang.String, float)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setFloat",
- args = {String.class, float.class}
- )
- public void testSetFloatStringFloat() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setInt(java.lang.String, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setInt",
- args = {String.class, int.class}
- )
- public void testSetIntStringInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setLong(java.lang.String, long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setLong",
- args = {String.class, long.class}
- )
- public void testSetLongStringLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setNull(java.lang.String, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setNull",
- args = {String.class, int.class}
- )
- public void testSetNullStringInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setNull(java.lang.String, int, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setNull",
- args = {String.class, int.class, String.class}
- )
- public void testSetNullStringIntString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {String.class, Object.class}
- )
- public void testSetObjectStringObject() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {String.class, Object.class, int.class}
- )
- public void testSetObjectStringObjectInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object, int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {String.class, Object.class, int.class, int.class}
- )
- public void testSetObjectStringObjectIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setShort(java.lang.String, short)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setShort",
- args = {String.class, short.class}
- )
- public void testSetShortStringShort() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setString(java.lang.String, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setString",
- args = {String.class, String.class}
- )
- public void testSetStringStringString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTime",
- args = {String.class, Time.class}
- )
- public void testSetTimeStringTime() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTime",
- args = {String.class, Time.class, Calendar.class}
- )
- public void testSetTimeStringTimeCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setTimestamp(java.lang.String, java.sql.Timestamp)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTimestamp",
- args = {String.class, Timestamp.class}
- )
- public void testSetTimestampStringTimestamp() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setTimestamp(java.lang.String, java.sql.Timestamp, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTimestamp",
- args = {String.class, Timestamp.class, Calendar.class}
- )
- public void testSetTimestampStringTimestampCalendar() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#setURL(java.lang.String, java.net.URL)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setURL",
- args = {String.class, URL.class}
- )
- public void testSetURLStringURL() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.CallableStatement#wasNull()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "wasNull",
- args = {}
- )
- public void testWasNull() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/ClobTest.java b/luni/src/test/java/tests/sql/ClobTest.java
deleted file mode 100644
index c0f218f..0000000
--- a/luni/src/test/java/tests/sql/ClobTest.java
+++ /dev/null
@@ -1,177 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.Clob;
-
-/**
- * @author andrea@google.com (Your Name Here)
- *
- */
-@TestTargetClass(Clob.class)
-public class ClobTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.Clob#getAsciiStream()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getAsciiStream",
- args = {}
- )
- public void testGetAsciiStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#getCharacterStream()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getCharacterStream",
- args = {}
- )
- public void testGetCharacterStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#getSubString(long, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getSubString",
- args = {long.class, int.class}
- )
- public void testGetSubString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#length()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "length",
- args = {}
- )
- public void testLength() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#position(java.sql.Clob, long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "position",
- args = {Clob.class, long.class}
- )
- public void testPositionClobLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#position(java.lang.String, long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "position",
- args = {String.class, long.class}
- )
- public void testPositionStringLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#setAsciiStream(long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setAsciiStream",
- args = {long.class}
- )
- public void testSetAsciiStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#setCharacterStream(long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setCharacterStream",
- args = {long.class}
- )
- public void testSetCharacterStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#setString(long, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setString",
- args = {long.class, String.class}
- )
- public void testSetStringLongString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#setString(long, java.lang.String, int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setString",
- args = {long.class, String.class, int.class, int.class}
- )
- public void testSetStringLongStringIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Clob#truncate(long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "truncate",
- args = {long.class}
- )
- public void testTruncate() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/ParameterMetaDataTest.java b/luni/src/test/java/tests/sql/ParameterMetaDataTest.java
deleted file mode 100644
index f522450..0000000
--- a/luni/src/test/java/tests/sql/ParameterMetaDataTest.java
+++ /dev/null
@@ -1,150 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.ParameterMetaData;
-
-/**
- *
- */
-@TestTargetClass(ParameterMetaData.class)
-public class ParameterMetaDataTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getParameterClassName(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getParameterClassName",
- args = {int.class}
- )
- public void testGetParameterClassName() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getParameterCount()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getParameterCount",
- args = {}
- )
- public void testGetParameterCount() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getParameterMode(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getParameterMode",
- args = {int.class}
- )
- public void testGetParameterMode() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getParameterType(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getParameterType",
- args = {int.class}
- )
- public void testGetParameterType() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getParameterTypeName(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getParameterTypeName",
- args = {int.class}
- )
- public void testGetParameterTypeName() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getPrecision(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getPrecision",
- args = {int.class}
- )
- public void testGetPrecision() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#getScale(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getScale",
- args = {int.class}
- )
- public void testGetScale() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#isNullable(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "isNullable",
- args = {int.class}
- )
- public void testIsNullable() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ParameterMetaData#isSigned(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "isSigned",
- args = {int.class}
- )
- public void testIsSigned() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/RefTest.java b/luni/src/test/java/tests/sql/RefTest.java
deleted file mode 100644
index 6109623..0000000
--- a/luni/src/test/java/tests/sql/RefTest.java
+++ /dev/null
@@ -1,87 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.Ref;
-import java.util.Map;
-
-/**
- * @author andrea@google.com (Your Name Here)
- *
- */
-@TestTargetClass(Ref.class)
-public class RefTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.Ref#getBaseTypeName()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBaseTypeName",
- args = {}
- )
- public void testGetBaseTypeName() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Ref#getObject()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {}
- )
- public void testGetObject() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Ref#getObject(java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {Map.class}
- )
- public void testGetObjectMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Ref#setObject(java.lang.Object)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setObject",
- args = {Object.class}
- )
- public void testSetObject() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/ResultSetGetterTests.java b/luni/src/test/java/tests/sql/ResultSetGetterTests.java
deleted file mode 100644
index 5cb50d5..0000000
--- a/luni/src/test/java/tests/sql/ResultSetGetterTests.java
+++ /dev/null
@@ -1,2183 +0,0 @@
-/*
- * Copyright (C) 2007 Google Inc.
- *
- * 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.sql;
-
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.sql.DatabaseMetaData;
-import java.sql.Date;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-
-/**
- * Tests based on
- * <a href="http://java.sun.com/products/jdbc/download.html">JDBC 1.0 API spec
- * </a> Table 1.0
- */
-@TestTargetClass(ResultSet.class)
-public class ResultSetGetterTests extends SQLTest {
-
- String queryAllSelect = "select * from type";
-
- ResultSet res = null;
-
- Statement st = null;
-
- // Judgement concerning support is based on the result of ResultSet.getOject
- // and Table 1 of JDBC 1.0 spec.
- static boolean booleanSupported = false;
- static boolean blobSupported = false;
- static boolean bigIntSupported = false;
- static boolean smallIntSupported = false;
- static boolean mediumIntSupported = false;
- static boolean realSupported = false;
- static boolean floatSupported = false;
- static boolean dateSupported = false;
- static boolean timeSupported = false;
- static boolean timeStampSupported = false;
- static boolean dateTimeSupported = false;
- static boolean urlSupported= false;
- static boolean tinyIntSupported = false;
- static boolean decimalSupported = false;
- static boolean numericSupported = false;
-
- static List<String> colNames = Arrays.asList("BoolVal", "IntVal", "LongVal",
- "Bint", "Tint", "Sint", "Mint", "IntegerVal", "RealVal",
- "DoubleVal", "FloatVal", "DecVal", "NumVal", "charStr",
- "dateVal", "timeVal", "TS", "DT", "TBlob", "BlobVal", "MBlob",
- "LBlob", "TText", "TextVal", "MText", "LText", "MaxLongVal",
- "MinLongVal", "validURL", "invalidURL");
-
- static List<String> values = Arrays.asList("1", "-1", "22", "2", "33",
- "3","1","2","3.9","23.2","33.3","44",
- "5", "test string", "1799-05-26", "12:35:45", "2007-10-09 14:28:02.0",
- "1221-09-22 10:11:55","1","2","3","4","Test text message tiny",
- "Test text", "Test text message medium",
- "Test text message long");
-
- static boolean[] supported = new boolean[]{
- booleanSupported,
- true,
- true,
- bigIntSupported,
- tinyIntSupported,
- smallIntSupported,
- mediumIntSupported,
- true,
- realSupported,
- true,
- floatSupported,
- decimalSupported,
- numericSupported,
- true,
- dateSupported,
- timeSupported,
- timeStampSupported,
- dateTimeSupported,
- blobSupported,
- blobSupported,
- blobSupported,
- blobSupported,
- true,
- true,
- true,
- true,
- bigIntSupported,
- bigIntSupported,
- urlSupported,
- urlSupported
- };
-
- // Not supported: BIT,VARBINARY, LONGVARBINARY, BINARY, VARCHAR, LONGVARCHAR
- static Class[] typeMap = new Class[]{
- java.lang.String.class, //
- java.lang.Integer.class,//Types.INTEGER,
- java.lang.Integer.class, //Types.LONG, not a JDBC 1.0 type
- java.lang.Long.class, // Types.BIGINT,
- java.lang.Byte.class, // Types.TINYINT,
- java.lang.Short.class, // Types.SMALLINT,
- java.lang.Integer.class, //Types.MEDIUMINT, , not a JDBC 1.0 type
- java.lang.Integer.class, // Types.Integer
- java.lang.Float.class, // Types.REAL,
- java.lang.Double.class, // Types.FLOAT,
- java.lang.Double.class, // Types.DOUBLE,
- java.math.BigDecimal.class, // Types.DECIMAL,
- java.math.BigDecimal.class, // Types.NUMERIC,
- java.lang.String.class, // Types.CHAR
- java.sql.Date.class, // Types.DATE,
- java.sql.Time.class, // Types.TIME,
- java.sql.Timestamp.class, // Types.TIMESTAMP,
- java.sql.Date.class, // types datetime, not a JDBC 1.0 type
- java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
- java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
- java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
- java.sql.Blob.class, // Types.BLOB, not a JDBC 1.0 type
- java.lang.String.class, // not a JDBC 1.0 type
- java.lang.String.class, // not a JDBC 1.0 type
- java.lang.String.class, // not a JDBC 1.0 type
- java.lang.String.class, // not a JDBC 1.0 type
- java.lang.Long.class, // Types.BIGINT,
- java.lang.Long.class, // Types.BIGINT,
- java.net.URL.class, // not a JDBC 1.0 type
- java.net.URL.class // not a JDBC 1.0 type
-
-
- };
-
- // first inserted row : actual values
- // second inserted row: null values
- String[] queries = {
- "create table type (" +
-
- " BoolVal BOOLEAN," + " IntVal INT," + " LongVal LONG,"
- + " Bint BIGINT," + " Tint TINYINT," + " Sint SMALLINT,"
- + " Mint MEDIUMINT, " +
-
- " IntegerVal INTEGER, " + " RealVal REAL, "
- + " DoubleVal DOUBLE, " + " FloatVal FLOAT, "
- + " DecVal DECIMAL, " +
-
- " NumVal NUMERIC, " + " charStr CHAR(20), "
- + " dateVal DATE, " + " timeVal TIME, " + " TS TIMESTAMP, "
- +
-
- " DT DATETIME, " + " TBlob TINYBLOB, " + " BlobVal BLOB, "
- + " MBlob MEDIUMBLOB, " + " LBlob LONGBLOB, " +
-
- " TText TINYTEXT, " + " TextVal TEXT, "
- + " MText MEDIUMTEXT, " + " LText LONGTEXT, " +
-
- " MaxLongVal BIGINT, MinLongVal BIGINT, "+
-
- " validURL URL, invalidURL URL "+
-
- ");"
- ,
-
- "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
- + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
- + "NumVal, charStr, dateVal, timeVal, TS,"
- + "DT, TBlob, BlobVal, MBlob, LBlob,"
- + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal,"
- + " validURL, invalidURL"
- + ") "
- + "values (1, -1, 22, 2, 33,"
- + "3, 1, 2, 3.9, 23.2, 33.3, 44,"
- + "5, 'test string', '1799-05-26', '12:35:45', '2007-10-09 14:28:02.0',"
- + "'1221-09-22 10:11:55', 1, 2, 3, 4,"
- + "'Test text message tiny', 'Test text',"
- + " 'Test text message medium', 'Test text message long', "
- + Long.MAX_VALUE+", "+Long.MIN_VALUE+", "
- + "'http://www.android.com', 'helloWorld' "+
- ");"
- ,
-
- "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
- + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
- + "NumVal, charStr, dateVal, timeVal, TS,"
- + "DT, TBlob, BlobVal, MBlob, LBlob,"
- + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal,"
- +" validURL, invalidURL"
- + ") "
- + "values (null, null, null, null, null,"
- + "null, null, null, null, null, null, null,"
- + "null, null, null, null, null,"
- + "null, null, null, null, null,"
- + "null, null, null, null,null, null, null, null);"
- };
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- try {
- conn.setAutoCommit(false);
- st = conn.createStatement();
- for (int i = 0; i < queries.length; i++) {
- st.execute(queries[i]);
- }
- res = st.executeQuery(queryAllSelect);
- assertTrue(res.next());
- } catch (SQLException e) {
- fail("SQLException is thrown: " + e.getMessage());
- }
- }
-
- public void tearDown() {
- try {
- st.execute("drop table if exists type");
- st.close();
- res.close();
- } catch (SQLException e) {
- fail("SQLException is thrown "+e.getMessage());
- } finally {
- try {
- st.close();
- res.close();
- } catch (SQLException ee) {
- }
- }
- super.tearDown();
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBytes(int)}.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exception testing",
- method = "getBytes",
- args = {int.class}
- )
- public void testGetBytesInt() {
- int i = 1;
-
-
- // null value
- try {
- i = 1;
- res.next();
- for (String t : values) {
- assertNull(res.getBytes(i));
- i++;
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.close();
- res.getBytes(24);
- fail("Should get Exception");
- } catch (SQLException e) {
- //ok
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBytes(int)}.
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "VARBINARY value",
- method = "getBytes",
- args = {int.class}
- )
- public void testGetBytesIntVarbinary() throws SQLException {
-
- Statement st = null;
- Statement stQuery = null;
- PreparedStatement stPrep = null;
- ResultSet res = null;
-
- // setup
- try {
- String testString = "HelloWorld";
- st = conn.createStatement();
- st.executeUpdate("create table testBinary (VARBINARY value);");
- stPrep = conn
- .prepareStatement("insert into testBinary values (?);");
- stPrep.setBytes(1, testString.getBytes());
- stPrep.execute();
-
- stQuery = conn.createStatement();
- res = stQuery.executeQuery("select * from testBinary");
- try {
- assertTrue(res.next());
- byte[] output = res.getBytes(1);
- String helloTest = new String(output);
- assertNotNull(helloTest);
- assertEquals(testString, helloTest);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- } finally {
- if (res != null) res.close();
- if (stPrep != null) stPrep.close();
- if (st != null) st.close();
- if (stQuery != null) stQuery.close();
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBytes(int)}.
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "BINARY value",
- method = "getBytes",
- args = {int.class}
- )
- public void testGetBytesIntBinary() throws SQLException {
-
- Statement st = null;
- Statement stQuery = null;
- PreparedStatement stPrep = null;
- ResultSet res = null;
-
-
- // setup
-
- String testString = "HelloWorld";
- st = conn.createStatement();
- st.executeUpdate("create table testBinary (BINARY value);");
- stPrep = conn.prepareStatement("insert into testBinary values (?);");
- stPrep.setBytes(1, testString.getBytes());
- stPrep.execute();
- try {
- stQuery = conn.createStatement();
- res = stQuery.executeQuery("select * from testBinary");
- try {
- assertTrue(res.next());
- byte[] output = res.getBytes(1);
- String helloTest = new String(output);
- assertNotNull(helloTest);
- assertEquals(testString, helloTest);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- } finally {
- if (res != null) res.close();
- if (stPrep != null) stPrep.close();
- if (st != null) st.close();
- if (stQuery != null) stQuery.close();
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBytes(String)}.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exception testing",
- method = "getBytes",
- args = {String.class}
- )
- public void testGetBytesString() {
- int i = 1;
-
- // null value
- try {
-
- res.next();
- for (String t : colNames) {
- assertNull(res.getBytes(t));
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.close();
- res.getBytes(colNames.get(24));
- fail("Should get Exception");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBytes(int)}.
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "VARBINARY value",
- method = "getBytes",
- args = {String.class}
- )
- @KnownFailure("last assertion fails: invalid conversion. Test passes on RI")
- public void testGetBytesStringVarbinary() throws SQLException {
-
- Statement st = null;
- Statement stQuery = null;
- PreparedStatement stPrep = null;
- ResultSet res = null;
-
- // setup
- try {
- String testString = "HelloWorld";
- st = conn.createStatement();
- st.executeUpdate("create table testBinary (VARBINARY value);");
- stPrep = conn
- .prepareStatement("insert into testBinary values (?);");
- stPrep.setBytes(1, testString.getBytes());
- stPrep.execute();
-
- stQuery = conn.createStatement();
- res = stQuery.executeQuery("select value from testBinary");
- try {
- assertTrue(res.next());
- byte[] output = res.getBytes("value");
- String helloTest = new String(output);
- assertNotNull(helloTest);
- assertEquals(testString, helloTest);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- } finally {
- if (res != null) res.close();
- if (stPrep != null) stPrep.close();
- if (st != null) st.close();
- if (stQuery != null) stQuery.close();
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBytes(int)}.
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "BINARY value",
- method = "getBytes",
- args = {String.class}
- )
- @KnownFailure("last assertion fails: invalid conversion. Test passes on RI")
- public void testGetBytesStringBinary() throws SQLException {
-
- Statement st = null;
- Statement stQuery = null;
- PreparedStatement stPrep = null;
- ResultSet res = null;
-
-
- // setup
-
- String testString = "HelloWorld";
- st = conn.createStatement();
- st.executeUpdate("create table testBinary (BINARY value);");
- stPrep = conn.prepareStatement("insert into testBinary values (?);");
- stPrep.setBytes(1, testString.getBytes());
- stPrep.execute();
- try {
- stQuery = conn.createStatement();
- res = stQuery.executeQuery("select value from testBinary");
- try {
- assertTrue(res.next());
- byte[] output = res.getBytes("value");
- String helloTest = new String(output);
- assertNotNull(helloTest);
- assertEquals(testString, helloTest);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- } finally {
- if (res != null) res.close();
- if (stPrep != null) stPrep.close();
- if (st != null) st.close();
- if (stQuery != null) stQuery.close();
- }
- }
-
- public void testGetConcurrency() {
- try {
- assertEquals(ResultSet.CONCUR_UPDATABLE, res.getConcurrency());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getDate(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDate",
- args = {int.class}
- )
- public void testGetDateInt() {
- try {
-
- GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
- Date input = new Date(testCal.getTimeInMillis());
- Date d = res.getDate(15);
- assertEquals(input.toString(),"1799-05-26");
- assertEquals(input,d);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- try {
- Date d = res.getDate(500);
- fail("Should get exception");
- } catch (SQLException e) {
- //ok
- } catch (Exception e) {
- fail("Got unspecified Exception "+ e.getMessage());
- }
-
- // null value
- try {
- assertTrue(res.next());
- Date d = res.getDate(15);
- assertNull(d);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getDate(int, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Not fully supported",
- method = "getDate",
- args = {int.class, java.util.Calendar.class}
- )
- public void testGetDateIntCalendar() {
- GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
- try {
-
- Date input = new Date(testCal.getTimeInMillis());
- Date d = res.getDate(15, testCal);
-
- assertEquals(input.toString(),"1799-05-26");
- assertEquals(input,d);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- try {
- Date d = res.getDate(500, testCal);
- fail("Should get exception");
- } catch (SQLException e) {
- //ok
- } catch (Exception e) {
- fail("Got unspecified Exception "+ e.getMessage());
- }
-
-
- // null value
- try {
- assertTrue(res.next());
- Date d = res.getDate(15,testCal);
- assertNull(d);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getDate(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Not fully supported",
- method = "getDate",
- args = {java.lang.String.class}
- )
- public void testGetDateString() {
- try {
- GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
- Date input = new Date(testCal.getTimeInMillis());
- Date d = res.getDate("dateVal");
- assertEquals(input.toString(),"1799-05-26");
- assertEquals(input,d);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- try {
- Date d = res.getDate("bla");
- fail("Should get exception");
- } catch (SQLException e) {
- //ok
- }
-
- // null value
- try {
- assertTrue(res.next());
- Date d = res.getDate("dateVal");
- assertNull(d);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getDate(java.lang.String, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDate",
- args = {java.lang.String.class, java.util.Calendar.class}
- )
- public void testGetDateStringCalendar() {
- GregorianCalendar testCal = new GregorianCalendar(1799, Calendar.MAY, 26, 0, 0);
- try {
- Date input = new Date(testCal.getTimeInMillis());
- Date d = res.getDate("dateVal", testCal);
-
- assertEquals(input.toString(),"1799-05-26");
- assertEquals(input,d);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- try {
- Date d = res.getDate("bla", testCal);
- fail("Should get exception");
- } catch (SQLException e) {
- //ok
- }
-
- // null value
- try {
- assertTrue(res.next());
- Date d = res.getDate("dateVal",testCal);
- assertNull(d);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getDouble(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDouble",
- args = {int.class}
- )
- public void testGetDoubleInt() {
-
- double output = 0.0;
- try {
- double[] input = {2.0, 3.9 , 23.2};
-
- output = res.getDouble(8);
- assertEquals(input[0],output);
-
- output = res.getDouble(9);
- assertEquals(input[1],output);
-
- output = res.getDouble(10);
- assertEquals(input[2],output);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getDouble(500);
- } catch (SQLException e) {
- //ok
- }
-
- // null value
- try {
- res.next();
- output = res.getDouble(8);
- assertEquals(0.0,output);
-
- output = res.getDouble(9);
- assertEquals(0.0,output);
-
- output = res.getDouble(10);
- assertEquals(0.0,output);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getDouble(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Not fully supported: eg. getDouble from TinyInt ",
- method = "getDouble",
- args = {java.lang.String.class}
- )
- public void testGetDoubleString() {
- double input = 23.2;
- double output = 0.0;
-
- try{
- output = res.getDouble("DoubleVal");
- assertEquals (input,output);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try{
- output = res.getDouble("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
-
- // null value
- try{
- assertTrue(res.next());
- output = res.getDouble("DoubleVal");
- assertEquals (0.0 , output);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getFloat(int)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Not fully supported: eg.: getFloat from TinyInt according to JDBC 1.0 spec",
- method = "getFloat",
- args = {int.class}
- )
- public void testGetFloatInt() {
- float defaultF = 0.0f;
- try {
- float[] input = {3.9f, 23.2f, 33.3f};
-
-
- float output = res.getFloat(9);
- assertEquals(input[0], output);
-
- output = res.getFloat(10);
- assertEquals(input[1], output);
-
- output = res.getFloat(11);
- assertEquals(input[2], output);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getFloat(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
- float output = res.getFloat(8);
- assertEquals(defaultF, output);
-
- output = res.getFloat(9);
- assertEquals(defaultF, output);
-
- output = res.getFloat(10);
- assertEquals(defaultF, output);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getFloat(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Not fully supported",
- method = "getFloat",
- args = {java.lang.String.class}
- )
- public void testGetFloatString() {
- float defaultF = 0.0f;
- try {
- String[] input = {"RealVal", "DoubleVal", "FloatVal"};
- float[] inputF = {3.9f, 23.2f, 33.3f};
-
-
- float output = res.getFloat(input[0]);
- assertEquals(inputF[0], output);
-
- output = res.getFloat(input[1]);
- assertEquals(inputF[1], output);
-
- output = res.getFloat(input[2]);
- assertEquals(inputF[2], output);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getFloat(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
- float output = res.getFloat(8);
- assertEquals(defaultF, output);
-
- output = res.getFloat(9);
- assertEquals(defaultF, output);
-
- output = res.getFloat(10);
- assertEquals(defaultF, output);
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getInt(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInt",
- args = {int.class}
- )
- public void testGetIntInt() {
-
- // real input val -1, 22, 2, 33,3, 1, 2
- List<Integer> input = Arrays.asList(1, -1, 22, 2, 33,3, 1, 2);
- ListIterator<Integer> it = input.listIterator();
- Double test2 = new Double(23.2);
- try {
- for (int i = 1;i<9;i++ ) {
- assertEquals(it.next().intValue(),res.getInt(i));
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getInt(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
- for (int i = 2;i<11;i++ ) {
- assertEquals(0,res.getInt(i));
- }
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getInt(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInt",
- args = {java.lang.String.class}
- )
- public void testGetIntString() {
- List<String> inputS = Arrays.asList("BoolVal", "IntVal", "LongVal",
- "Bint", "Tint", "Sint", "Mint", "IntegerVal");
- ListIterator<String> itS = inputS.listIterator();
- List<Integer> input = Arrays.asList(1, -1, 22, 2, 33, 3, 1, 2);
- ListIterator<Integer> it = input.listIterator();
- try {
- while (it.hasNext()) {
- assertEquals(it.next().intValue(), res.getInt(itS.next()));
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getInt("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
- for (String s : inputS) {
- assertEquals(0, res.getInt(s));
- }
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getLong(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {int.class}
- )
- public void testGetLongInt() {
- long maxVal = Long.MAX_VALUE;
- long minVal = Long.MIN_VALUE;
-
- try {
- assertEquals(maxVal, res.getLong(27));
- assertEquals(minVal, res.getLong(28));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getInt(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
-
- assertEquals(0,res.getLong(27));
- assertEquals(0,res.getLong(28));
-
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getLong(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {java.lang.String.class}
- )
- public void testGetLongString() {
- long maxVal = Long.MAX_VALUE;
- long minVal = Long.MIN_VALUE;
-
- try {
- assertEquals(maxVal, res.getLong("MaxLongVal"));
- assertEquals(minVal, res.getLong("MinLongVal"));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getInt("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
-
- assertEquals(0,res.getLong("MaxLongVal"));
- assertEquals(0,res.getLong("MinLongVal"));
-
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getMetaData()}.
- * type mappings according to
- * http://java.sun.com/j2se/1.3/docs/guide/jdbc/spec/jdbc-spec.frame8.html
- * Not supported datatypes are not checked.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "checks supported data types ,not supported types are not checked.",
- method = "getMetaData",
- args = {}
- )
- })
- @KnownFailure("Wrong value returned for Long: java.lang.String (VARCHAR)")
- public void testGetMetaData() {
- /*
- * List<String> types = Arrays.asList("BOOLEAN", "INT", "LONG",
- * "BIGINT", "TINYINT", "SMALLINT", "MEDIUMINT", "INTEGER", "REAL",
- * "DOUBLE", "FLOAT", "DECIMAL", "NUMERIC", "CHAR(20)", "DATE", "TIME",
- * "TIMESTAMP", "DATETIME", "TINYBLOB", "BLOB", "MEDIUMBLOB",
- * "LONGBLOB", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT", "BIGINT",
- * "BIGINT","URL","URL");
- */
- List<String> types = Arrays.asList("VARCHAR", "INTEGER", "INTEGER",
- "BIGINT", "SMALLINT", "SHORT", "INTEGER", "INTEGER", "FLOAT",
- "DOUBLE", "DOUBLE", "DECIMAL", "NUMERIC", "VARCHAR", "DATE",
- "TIME", "TIMESTAMP", "DATETIME", "BLOB", "BLOB", "BLOB",
- "BLOB", "VARCHAR", "VARCHAR", "VARCHAR", "VARCHAR", "BIGINT",
- "BIGINT", "URL", "URL");
-
-
-
- ListIterator<String> it = types.listIterator();
- ListIterator<String> colNameIt = colNames.listIterator();
- try {
- ResultSetMetaData meta = res.getMetaData();
- assertNotNull(meta);
- assertEquals("Error in test setup. Columns do not match", types
- .size(), meta.getColumnCount());
- for (int i = 1; i < 31; i++) {
- String colName = colNameIt.next();
- String type = it.next();
- if (supported[i - 1]) {
- assertTrue("Wrong column name at " + i, colName
- .equalsIgnoreCase(meta.getColumnName(i)));
- assertTrue("Wrong type at " + i+" required" +type+ " but is "+meta.getColumnTypeName(i), type.equalsIgnoreCase(meta
- .getColumnTypeName(i)));
- }
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getObject(int)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not supported types BIT,VARBINARY, LONGVARBINARY, BINARY, VARCHAR, LONGVARCHAR",
- method = "getObject",
- args = {int.class}
- )
- @KnownFailure("Wrong value returned for Long: java.lang.String")
- public void testGetObjectInt() {
-
- try {
- for (int i = 1; i <= typeMap.length; i++) {
- if (supported[i-1]) {
- Object value = res.getObject(i);
- assertTrue("value " + value.getClass().getName()
- + " does not correspond " + typeMap[i-1] + "at "+i, value
- .getClass().equals(typeMap[i-1]));
- }
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getObject(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- try {
- res.next();
- for (int i = 1; i <= typeMap.length; i++) {
- Object value = res.getObject(i);
- assertNull(value);
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getObject(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not fully supported",
- method = "getObject",
- args = {java.lang.String.class}
- )
- @KnownFailure("Wrong value returned for Long: java.lang.String")
- public void testGetObjectString() {
- ListIterator<String> colNameIt = colNames.listIterator();
- try {
- for (int i = 1; i <= typeMap.length; i++) {
- String name = colNameIt.next();
- if (supported[i-1]) {
- Object value = res.getObject(name);
- assertTrue("value " + value.getClass().getName()
- + " for "+name+" does not correspond " + typeMap[i-1] + "at "+i, value
- .getClass().equals(typeMap[i-1]));
- }
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getObject("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
-
- try {
- colNameIt = colNames.listIterator();
- res.next();
- for (int i = 1; i <= typeMap.length; i++) {
- Object value = res.getObject(colNameIt.next());
- assertNull(value);
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getRow()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exception testing missed, test fails. According to spec afterlast row is 0 but returns 3",
- method = "getRow",
- args = {}
- )
- @KnownFailure("If there is no current row 0 must be returned. res.close() does not wrap up")
- public void testGetRow() {
- try {
- assertEquals(1, res.getRow());
- assertTrue(res.isFirst());
- res.next();
- assertEquals(2, res.getRow());
- assertTrue(res.isLast());
- res.next();
- assertTrue(res.isAfterLast());
- assertEquals(0, res.getRow());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.close();
- res.getRow();
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getShort(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getShort",
- args = {int.class}
- )
- public void testGetShortInt() {
- try {
- short shorty = res.getShort(6);
- assertEquals(3,shorty);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
- short shorty = res.getShort(6);
- assertEquals(0,shorty);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- res.getShort(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getShort(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getShort",
- args = {java.lang.String.class}
- )
- public void testGetShortString() {
- try {
- short shorty = res.getShort("Sint");
- assertEquals(3,shorty);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
- short shorty = res.getShort("Sint");
- assertEquals(0,shorty);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- res.getShort("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getStatement()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test fails. According to spec info.getStatement should return"+
- " null but an exception is thrown: stale result set.",
- method = "getStatement",
- args = {}
- )
- @KnownFailure("According to spec info.getStatement should return null"+
- " but an exception is thrown: stale result set.")
- public void testGetStatement() {
- try {
- DatabaseMetaData meta = conn.getMetaData();
- ResultSet info = meta.getTypeInfo();
- Statement statement2 = info.getStatement();
- assertNull(statement2);
- } catch(SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- Statement statement2 = res.getStatement();
- assertEquals(st, statement2);
- } catch(SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- // exception testing
- try {
- res.close();
- res.getStatement();
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getString(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getString",
- args = {int.class}
- )
- public void testGetStringInt() {
- List<String> texts = Arrays.asList("Test text message tiny",
- "Test text", "Test text message medium",
- "Test text message long");
- int i = 23;
-
- //text and exception testing
- try {
- for (String t : texts) {
- assertEquals(t, res.getString(i));
- i++;
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- // the rest: everything should work with getString
-
- texts = Arrays.asList("1", "-1", "22", "2", "33",
- "3","1","2","3.9","23.2","33.3","44",
- "5", "test string", "1799-05-26", "12:35:45", "2007-10-09 14:28:02.0",
- "1221-09-22 10:11:55","1","2","3","4");
- i= 1;
-
- try {
- for (String t : texts) {
- assertEquals(t, res.getString(i));
- i++;
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- //null testing
-
- try {
- i = 1;
- res.next();
- for (String t : values) {
- assertNull(res.getString(i));
- i++;
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- // exception testing
- try {
- res.getString(500);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getString(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "exception test missed",
- method = "getString",
- args = {java.lang.String.class}
- )
- public void testGetStringString() {
-
- ListIterator<String> colNameIt = colNames.listIterator();
- try {
- for (String t : values) {
- assertEquals(t, res.getString(colNameIt.next()));
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
-
- for (String name: colNames) {
- assertNull(res.getString(name));
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getString("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTime(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTime",
- args = {int.class}
- )
- @KnownFailure("getTime should return Time value for a TIMESTAMP type but returns null")
- public void testGetTimeInt() {
- // values "12:35:45", "2007-10-09 14:28:02.0", "1221-09-22 10:11:55"
-
- Calendar cal = new GregorianCalendar();
- cal.clear();
- cal.set(Calendar.HOUR_OF_DAY, 12);
- cal.set(Calendar.MINUTE, 35);
- cal.set(Calendar.SECOND, 45);
- cal.set(Calendar.MILLISECOND, 0);
- // set with calendar value (correct init time: since epoch)
- long millis = cal.getTime().getTime();
- Time t1 = new java.sql.Time(millis);
- assertNotNull("t1", t1);
-
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis2 = cal2.getTime().getTime();
- Time t2 = new java.sql.Time(millis2);
-
- int i = 16;
-
- try {
- Time resTime = res.getTime(i);
- assertNotNull("Pos " + i + " null", resTime);
- assertEquals(t1.toString(), resTime.toString());
- assertEquals(t1.getTime(), resTime.getTime());
- assertEquals(t1, resTime);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- // Compatibility Test: TIMESTAMP value
- i = 17;
-
- try {
- Time resTime = res.getTime(i);
- assertNotNull("Pos " + i + " null", resTime);
- assertEquals(t2.toString(), resTime.toString());
- assertEquals(t2.getTime(), resTime.getTime());
- assertEquals(t2, resTime);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- i = 16;
- res.next();
- assertNull(res.getTime(i));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime(500);
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTime(int, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTime",
- args = {int.class, java.util.Calendar.class}
- )
- @KnownFailure("getTime on TIMESTAMP value fails: returns null")
- public void testGetTimeIntCalendar() {
- List<Time> times = new LinkedList<Time>();
- List<Calendar> cals = new LinkedList<Calendar>();
- // Arrays.asList("12:35:45", "2007-10-09 14:28:02.0",
- // "1221-09-22 10:11:55");
-
- Calendar cal1 = new GregorianCalendar();
- cal1.clear();
- cal1.set(Calendar.HOUR_OF_DAY, 12);
- cal1.set(Calendar.MINUTE, 35);
- cal1.set(Calendar.SECOND, 45);
- cal1.set(Calendar.MILLISECOND, 0);
-
- long millis = cal1.getTime().getTime();
- Time t1 = new java.sql.Time(millis);
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis2 = cal2.getTime().getTime();
- Time t2 = new java.sql.Time(millis2);
-
- // TIME value
-
- int i = 16;
-
- try {
- Time timeRes = res.getTime(i,new GregorianCalendar());
- assertNotNull(timeRes);
- assertEquals(t1.toString(), timeRes.toString());
- assertEquals(t1.getTime(), timeRes.getTime());
- assertEquals(t1, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- // TIMESTAMP value
- i = 17;
-
- try {
- Time timeRes = res.getTime(i,new GregorianCalendar());
- assertNotNull(timeRes);
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.getTime(), timeRes.getTime());
- assertEquals(t2, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
-
- for (Calendar c : cals) {
- assertNull(res.getTime(16,c));
- i++;
- }
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime(500,Calendar.getInstance());
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTime(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getTime",
- args = {java.lang.String.class}
- )
- @KnownFailure("getTime should return a Time value for a TIMESTAMP type but returns null")
- public void testGetTimeString() {
- List<Time> times = new LinkedList<Time>();
-
- List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
- Iterator<String> it = stringTimes.iterator();
-
- // Arrays.asList("12:35:45", "2007-10-09 14:28:02.0",
- // "1221-09-22 10:11:55");
-
- Calendar cal = new GregorianCalendar();
- cal.clear();
- cal.set(Calendar.HOUR_OF_DAY, 12);
- cal.set(Calendar.MINUTE, 35);
- cal.set(Calendar.SECOND, 45);
- cal.set(Calendar.MILLISECOND, 0);
-
- long millis = cal.getTime().getTime();
- Time t1 = new java.sql.Time(millis);
-
- String col = it.next();
-
- try {
- Time timeRes = res.getTime(col);
- assertNotNull(timeRes);
- assertEquals(t1.toString(), timeRes.toString());
- assertEquals(t1.getTime(), timeRes.getTime());
- assertEquals(t1, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis2 = cal.getTime().getTime();
- Time t2 = new java.sql.Time(millis2);
-
- col = it.next();
-
- try {
- Time timeRes = res.getTime(col);
- assertNotNull(timeRes);
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.getTime(), timeRes.getTime());
- assertEquals(t2, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- res.next();
-
- assertNull(res.getTime(col));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTime(java.lang.String, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Testing getTime with TIME, TIMESTAMP value",
- method = "getTime",
- args = {java.lang.String.class, java.util.Calendar.class}
- )
- @KnownFailure("getTime on TIMESTAMP value fails: returns null")
- public void testGetTimeStringCalendar() {
- List<Time> times = new LinkedList<Time>();
-
- List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
- Iterator<String> it = stringTimes.iterator();
- List<Calendar> cals = new LinkedList<Calendar>();
-
- // Arrays.asList("12:35:45", "2007-10-09 14:28:02.0",
- // "1221-09-22 10:11:55");
-
- Calendar cal1 = new GregorianCalendar();
- cal1.clear();
- cal1.set(Calendar.HOUR_OF_DAY, 12);
- cal1.set(Calendar.MINUTE, 35);
- cal1.set(Calendar.SECOND, 45);
- cal1.set(Calendar.MILLISECOND, 0);
-
- long millis = cal1.getTime().getTime();
- Time t1 = new java.sql.Time(millis);
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis2 = cal2.getTime().getTime();
- Time t2 = new java.sql.Time(millis2);
-
- // TIME value
- String col = it.next();
-
- try {
- Time timeRes = res.getTime(col, new GregorianCalendar());
- assertNotNull(timeRes);
- assertEquals(t1.toString(), timeRes.toString());
- assertEquals(t1.getTime(), timeRes.getTime());
- assertEquals(t1, res.getTime(col));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- //TIMESTAMP value
- col = it.next();
-
- try {
- Time timeRes = res.getTime(col, new GregorianCalendar());
- assertNotNull(timeRes);
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.getTime(), timeRes.getTime());
- assertEquals(t2, res.getTime(col));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
-
- try {
- res.next();
- assertNull(res.getTime(stringTimes.get(0), new GregorianCalendar()));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTimestamp(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimestamp",
- args = {int.class}
- )
- public void testGetTimestampInt() {
- List<Timestamp> times = new LinkedList<Timestamp>();
-
- List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
- Iterator<String> it = stringTimes.iterator();
- List<Calendar> cals = new LinkedList<Calendar>();
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis = cal2.getTime().getTime();
- Timestamp t2 = new Timestamp(millis);
- times.add(t2);
-
- Calendar cal3 = new GregorianCalendar();
- cal3.set(Calendar.YEAR, 1221);
- cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
- cal3.set(Calendar.DATE, 22);
- cal3.set(Calendar.HOUR_OF_DAY, 10);
- cal3.set(Calendar.MINUTE, 11);
- cal3.set(Calendar.SECOND, 55);
- cal3.set(Calendar.MILLISECOND, 0);
-
- millis = cal3.getTime().getTime();
- Timestamp t3 = new Timestamp(millis);
- times.add(t3);
- // TIMESTAMP value
- int i = 17;
-
- try {
- Timestamp timeRes = res.getTimestamp(i);
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.getTime(), timeRes.getTime());
- assertEquals(t2, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- // DATE value
- i = 18;
- try {
- Timestamp timeRes = res.getTimestamp(i);
- assertEquals(t3.toString(), timeRes.toString());
- assertEquals(t3.getTime(), timeRes.getTime());
- assertEquals(t3, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
- assertNull(res.getTime(i));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime(500);
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTimestamp(int, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimestamp",
- args = {int.class, java.util.Calendar.class}
- )
- public void testGetTimestampIntCalendar() {
- List<Timestamp> times = new LinkedList<Timestamp>();
-
- List<String> stringTimes = Arrays.asList("timeVal", "TS", "DT");
- Iterator<String> it = stringTimes.iterator();
-// List<Calendar> cals = new LinkedList<Calendar>();
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis = cal2.getTime().getTime();
- Timestamp t2 = new Timestamp(millis);
- times.add(t2);
- //
- Calendar cal3 = new GregorianCalendar();
- cal3.set(Calendar.YEAR, 1221);
- cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
- cal3.set(Calendar.DATE, 22);
- cal3.set(Calendar.HOUR_OF_DAY, 10);
- cal3.set(Calendar.MINUTE, 11);
- cal3.set(Calendar.SECOND, 55);
- cal3.set(Calendar.MILLISECOND, 0);
-
- millis = cal3.getTime().getTime();
- Timestamp t3 = new Timestamp(millis);
- times.add(t3);
-
-// cals.add(cal1);
-// cals.add(cal2);
-// cals.add(cal3);
-//
-// ListIterator<Calendar> calIt = cals.listIterator();
-
- int i = 17;
-
- try {
- Timestamp timeRes = res.getTimestamp(i,new GregorianCalendar());
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- i = 18;
-
- try {
- Timestamp timeRes = res.getTimestamp(i,new GregorianCalendar());
- assertEquals(t3.toString(), timeRes.toString());
- assertEquals(t3, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
- assertNull(res.getTime(17,cal2));
- assertNull(res.getTime(18,cal3));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime(500);
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTimestamp(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimestamp",
- args = {java.lang.String.class}
- )
- public void testGetTimestampString() {
- List<Timestamp> times = new LinkedList<Timestamp>();
-
- List<String> stringTimes = Arrays.asList( "TS", "DT");
- Iterator<String> it = stringTimes.iterator();
-// List<Calendar> cals = new LinkedList<Calendar>();
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis = cal2.getTime().getTime();
- Timestamp t2 = new Timestamp(millis);
- times.add(t2);
- //
- Calendar cal3 = new GregorianCalendar();
- cal3.set(Calendar.YEAR, 1221);
- cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
- cal3.set(Calendar.DATE, 22);
- cal3.set(Calendar.HOUR_OF_DAY, 10);
- cal3.set(Calendar.MINUTE, 11);
- cal3.set(Calendar.SECOND, 55);
- cal3.set(Calendar.MILLISECOND, 0);
-
- millis = cal3.getTime().getTime();
- Timestamp t3 = new Timestamp(millis);
- times.add(t3);
-
- String col = it.next();
-
- try {
- Timestamp timeRes = res.getTimestamp(col);
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.getTime(), timeRes.getTime());
- assertEquals(t2, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- // DATE value
- col = it.next();
-
- try {
- Timestamp timeRes = res.getTimestamp(col);
- assertEquals(t3.toString(), timeRes.toString());
- assertEquals(t3.toString(), timeRes.toString());
- assertEquals(t3.getTime(), timeRes.getTime());
- assertEquals(t3, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.next();
- assertNull(res.getTime(stringTimes.get(0)));
- assertNull(res.getTime(stringTimes.get(1)));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime(500);
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getTimestamp(java.lang.String, java.util.Calendar)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimestamp",
- args = {java.lang.String.class, java.util.Calendar.class}
- )
- public void testGetTimestampStringCalendar() {
- List<Timestamp> times = new LinkedList<Timestamp>();
-
- List<String> stringTimes = Arrays.asList( "TS", "DT");
- Iterator<String> it = stringTimes.iterator();
-
- Calendar cal2 = new GregorianCalendar();
- cal2.set(Calendar.YEAR, 2007);
- cal2.set(Calendar.MONTH, Calendar.OCTOBER);
- cal2.set(Calendar.DATE, 9);
- cal2.set(Calendar.HOUR_OF_DAY, 14);
- cal2.set(Calendar.MINUTE, 28);
- cal2.set(Calendar.SECOND, 02);
- cal2.set(Calendar.MILLISECOND, 0);
-
- long millis = cal2.getTime().getTime();
- Timestamp t2 = new Timestamp(millis);
- times.add(t2);
- //
- Calendar cal3 = new GregorianCalendar();
- cal3.set(Calendar.YEAR, 1221);
- cal3.set(Calendar.MONTH, Calendar.SEPTEMBER);
- cal3.set(Calendar.DATE, 22);
- cal3.set(Calendar.HOUR_OF_DAY, 10);
- cal3.set(Calendar.MINUTE, 11);
- cal3.set(Calendar.SECOND, 55);
- cal3.set(Calendar.MILLISECOND, 0);
-
- millis = cal3.getTime().getTime();
- Timestamp t3 = new Timestamp(millis);
- times.add(t3);
-
- try {
- Timestamp timeRes = res.getTimestamp(stringTimes.get(0),cal2);
- assertEquals(t2.toString(), timeRes.toString());
- assertEquals(t2.getTime(), timeRes.getTime());
- assertEquals(t2, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- // DATE value
- try {
- Timestamp timeRes = res.getTimestamp(stringTimes.get(1),cal3);
- assertEquals(t3.toString(), timeRes.toString());
- assertEquals(t3.getTime(), timeRes.getTime());
- assertEquals(t3, timeRes);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- // calIt = cals.listIterator();
-
- try {
- res.next();
- assertNull(res.getTime(stringTimes.get(0),cal2));
- assertNull(res.getTime(stringTimes.get(1),cal3));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- res.getTime(500);
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getType()}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SQLException checking missed. Only one ResultSet type supported: default values, Test fails.Not fully supported. Always returns ResultSet.TYPE_SCROLL_INSENSITIVE. Wrong default value.",
- method = "getType",
- args = {}
- )
- @KnownFailure("res.close() does not wrap up")
- public void testGetType() {
- try {
- assertEquals(ResultSet.TYPE_FORWARD_ONLY, res.getType());
- } catch (SQLException e) {
- fail("Unexpected exception " + e.getMessage());
- }
-
- try {
- st.close();
- res.getType();
- fail("Exception not thrown.");
- } catch (SQLException e) {
- //ok
- }
-
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getURL(int)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not fully supported type",
- method = "getURL",
- args = {int.class}
- )
- public void testGetURLInt() {
- try {
- URL input = new URL("http://www.android.com");
- URL validURL = res.getURL(29);
- assertEquals(input, validURL);
- } catch (SQLException e) {
- fail("Unexpected exception " + e.getMessage());
- } catch (MalformedURLException e) {
- fail("Unexpected exception " + e.getMessage());
- }
-
- try {
- URL invalidURL = res.getURL(30);
- assertNull(invalidURL);
- } catch (SQLException e) {
- // ok
- }
-
- try {
- res.next();
- assertNull(res.getURL(29));
- assertNull(res.getURL(30));
- } catch (SQLException e) {
- fail("Unexpected exception " + e.getMessage());
- }
-
- try {
- res.getURL(500);
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getURL(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "not fully supported type",
- method = "getURL",
- args = {java.lang.String.class}
- )
- public void testGetURLString() {
- try {
- URL input = new URL("http://www.android.com");
- URL validURL = res.getURL("validURL");
- assertEquals(input, validURL);
- } catch (SQLException e) {
- fail("Unexpected exception " + e.getMessage());
- } catch (MalformedURLException e) {
- fail("Unexpected exception " + e.getMessage());
- }
-
- try {
- URL invalidURL = res.getURL("invalidURL");
- assertNull(invalidURL);
- } catch (SQLException e) {
- // ok
- }
-
- try {
- res.next();
- assertNull(res.getURL("validURL"));
- assertNull(res.getURL("invalidURL"));
- } catch (SQLException e) {
- fail("Unexpected exception " + e.getMessage());
- }
-
- try {
- res.getURL("bla");
- fail("Exception expected");
- } catch (SQLException e) {
- // ok
- }
- }
-}
diff --git a/luni/src/test/java/tests/sql/ResultSetNotSupportedTests.java b/luni/src/test/java/tests/sql/ResultSetNotSupportedTests.java
deleted file mode 100644
index dd91f1a..0000000
--- a/luni/src/test/java/tests/sql/ResultSetNotSupportedTests.java
+++ /dev/null
@@ -1,1352 +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 tests.sql;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import java.sql.Ref;
-import java.sql.ResultSet;
-
-@TestTargetClass(ResultSet.class)
-public class ResultSetNotSupportedTests extends SQLTest {
-
- /**
- * Test method for {@link java.sql.ResultSet#getArray(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {int.class}
- )
- public void testGetArrayInt() {
-
- fail();
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getArray(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getArray",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetArrayString() {
- fail("Not yet implemented");
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getAsciiStream(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getAsciiStream",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetAsciiStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getAsciiStream(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getAsciiStream",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetAsciiStreamString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBigDecimal(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBigDecimal",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBigDecimalInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBigDecimal(int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getBigDecimal",
- args = {int.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBigDecimalIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBigDecimal(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBigDecimal",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBigDecimalString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBigDecimal(java.lang.String, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBigDecimal",
- args = {java.lang.String.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBigDecimalStringInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBinaryStream(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBinaryStream",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBinaryStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBinaryStream(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBinaryStream",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBinaryStreamString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBlob(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBlob",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBlobInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBlob(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBlob",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBlobString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBoolean(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getBoolean",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBooleanInt() {
- /*
- try {
- assertTrue(res.first());
- boolean b = res.getBoolean(1);
- assertTrue(b);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- boolean b = res.getBoolean(5);
- fail("Should get exception");
- } catch (SQLException e) {
- //ok
- }
-
-
-
- // null value
- try {
- assertTrue(res.next());
- boolean b = res.getBoolean(1);
- assertFalse(b);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- */
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getBoolean(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getBoolean",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetBooleanString() {
- fail("Not yet implemented");
- }
-
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getByte(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getByte",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetByteString() {
- fail("Not yet implemented");
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getByte(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "getByte",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetByteInt() {
- /*
- try {
- assertTrue(res.first());
- byte b = res.getByte(14);
- String testString = Byte.toString(b);
- assertEquals("test string",testString);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- byte b = res.getByte(5);
- fail("Should get exception");
- } catch (SQLException e) {
- //ok
- }
-
- // null value
- try {
- assertTrue(res.next());
- byte b = res.getByte(14);
- assertNull(b);
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- */
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getCharacterStream(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getCharacterStream",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetCharacterStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getCharacterStream(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getCharacterStream",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetCharacterStreamString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getClob(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getClob",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetClobInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getClob(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getClob",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetClobString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getCursorName()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported, setColumnName is not supported, therefore GetColumname can not be tested",
- method = "getCursorName",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testGetCursorName() {
- /*
- try {
- assertNull(res.getCursorName());
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- ResultSet rs2 = null;
- Statement stmt;
- String inputCName = "my \"\"\"\"quoted\"\"\"\" cursor\"\"";
- try {
- assertNull(res.getCursorName());
- stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
- ResultSet.CONCUR_READ_ONLY);
- stmt.setCursorName(inputCName);
- rs2 = stmt.executeQuery("select * from type");
- rs2.next();
- String name = rs2.getCursorName();
- assertEquals(inputCName, name);
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- rs2.close();
- rs2.getCursorName();
- fail("Should throw exception");
- } catch (Exception e) {
- //ok
- }
- */
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getFetchDirection()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported.",
- method = "getFetchDirection",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testGetFetchDirection() {
- /*
- try {
- assertEquals(ResultSet.TYPE_FORWARD_ONLY, res.getFetchDirection());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- */
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#getFetchSize()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getFetchSize",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testGetFetchSize() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getObject(int, java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {int.class, java.util.Map.class}
- )
- @KnownFailure("Not Supported")
- public void testGetObjectIntMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getObject(java.lang.String, java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getObject",
- args = {java.lang.String.class, java.util.Map.class}
- )
- @KnownFailure("Not Supported")
- public void testGetObjectStringMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getRef(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRef",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetRefInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getRef(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRef",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetRefString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getUnicodeStream(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getUnicodeStream",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testGetUnicodeStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getUnicodeStream(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getUnicodeStream",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testGetUnicodeStreamString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#getWarnings()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getWarnings",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testGetWarnings() {
- /*
- try {
- res.close();
- res.getWarnings();
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- */
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#cancelRowUpdates()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "SQLException checking missed",
- method = "cancelRowUpdates",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testCancelRowUpdates() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#deleteRow()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "deleteRow",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testDeleteRow() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#insertRow()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "insertRow",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testInsertRow() {
- fail("Not yet implemented");
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#moveToCurrentRow()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "moveToCurrentRow",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testMoveToCurrentRow() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#moveToInsertRow()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "moveToInsertRow",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testMoveToInsertRow() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#refreshRow()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "refreshRow",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testRefreshRow() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#rowDeleted()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "rowDeleted",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testRowDeleted() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#rowInserted()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "rowInserted",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testRowInserted() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#rowUpdated()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "rowUpdated",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testRowUpdated() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#setFetchDirection(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setFetchDirection",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testSetFetchDirection() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#setFetchSize(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setFetchSize",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testSetFetchSize() {
- fail("Not yet implemented");
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#updateArray(int, java.sql.Array)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateArray",
- args = {int.class, java.sql.Array.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateArrayIntArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateArray(java.lang.String, java.sql.Array)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateArray",
- args = {java.lang.String.class, java.sql.Array.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateArrayStringArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateAsciiStream(int, java.io.InputStream, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateAsciiStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateAsciiStreamIntInputStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateAsciiStream(java.lang.String, java.io.InputStream, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateAsciiStream",
- args = {String.class, java.io.InputStream.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateAsciiStreamStringInputStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBigDecimal(int, java.math.BigDecimal)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBigDecimal",
- args = {int.class, java.math.BigDecimal.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBigDecimalIntBigDecimal() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBigDecimal(java.lang.String, java.math.BigDecimal)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBigDecimal",
- args = {java.lang.String.class, java.math.BigDecimal.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBigDecimalStringBigDecimal() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBinaryStream(int, java.io.InputStream, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBinaryStream",
- args = {int.class, java.io.InputStream.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBinaryStreamIntInputStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBinaryStream(java.lang.String, java.io.InputStream, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBinaryStream",
- args = {java.lang.String.class, java.io.InputStream.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBinaryStreamStringInputStreamInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBlob(int, java.sql.Blob)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBlob",
- args = {int.class, java.sql.Blob.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBlobIntBlob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBlob(java.lang.String, java.sql.Blob)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBlob",
- args = {java.lang.String.class, java.sql.Blob.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBlobStringBlob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBoolean(int, boolean)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBoolean",
- args = {int.class, boolean.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBooleanIntBoolean() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBoolean(java.lang.String, boolean)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBoolean",
- args = {java.lang.String.class, boolean.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBooleanStringBoolean() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateByte(int, byte)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateByte",
- args = {int.class, byte.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateByteIntByte() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateByte(java.lang.String, byte)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateByte",
- args = {java.lang.String.class, byte.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateByteStringByte() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBytes(int, byte[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBytes",
- args = {int.class, byte[].class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBytesIntByteArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateBytes(java.lang.String, byte[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateBytes",
- args = {java.lang.String.class, byte[].class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateBytesStringByteArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateCharacterStream(int, java.io.Reader, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateCharacterStream",
- args = {int.class, java.io.Reader.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateCharacterStreamIntReaderInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateCharacterStream(java.lang.String, java.io.Reader, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateCharacterStream",
- args = {java.lang.String.class, java.io.Reader.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateCharacterStreamStringReaderInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateClob(int, java.sql.Clob)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateClob",
- args = {int.class, java.sql.Clob.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateClobIntClob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateClob(java.lang.String, java.sql.Clob)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateClob",
- args = {java.lang.String.class, java.sql.Clob.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateClobStringClob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateDate(int, java.sql.Date)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateDate",
- args = {int.class, java.sql.Date.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateDateIntDate() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateDate(java.lang.String, java.sql.Date)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateDate",
- args = {java.lang.String.class, java.sql.Date.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateDateStringDate() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateDouble(int, double)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateDouble",
- args = {int.class, double.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateDoubleIntDouble() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateDouble(java.lang.String, double)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateDouble",
- args = {java.lang.String.class, double.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateDoubleStringDouble() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateFloat(int, float)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateFloat",
- args = {int.class, float.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateFloatIntFloat() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateFloat(java.lang.String, float)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateFloat",
- args = {java.lang.String.class, float.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateFloatStringFloat() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateInt(int, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateInt",
- args = {int.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateIntIntInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateInt(java.lang.String, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateInt",
- args = {String.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateIntStringInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateLong(int, long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateLong",
- args = {int.class, long.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateLongIntLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateLong(java.lang.String, long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateLong",
- args = {java.lang.String.class, long.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateLongStringLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateNull(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateNull",
- args = {int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateNullInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateNull(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateNull",
- args = {java.lang.String.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateNullString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateObject(int, java.lang.Object)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateObject",
- args = {int.class, java.lang.Object.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateObjectIntObject() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateObject(int, java.lang.Object, int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateObject",
- args = {int.class, java.lang.Object.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateObjectIntObjectInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateObject(String, Object) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateObject",
- args = {String.class, Object.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateStringObject() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateObject(String, Object, int) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateObject",
- args = {String.class, Object.class, int.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateStringObjectInt() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateRef(int, java.sql.Ref) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateRef",
- args = {int.class, Ref.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateRefIntRef() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateRef(String, Ref) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateRef",
- args = {String.class, Ref.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateRefStringRef() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateRow() }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateRow",
- args = {}
- )
- @KnownFailure("Not Supported")
- public void testUpdateRow() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateShort(int, short) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateShort",
- args = {int.class, short.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateShortIntShort() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateShort(String, short) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateShort",
- args = {String.class, short.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateShortStringShort() {
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateString(int, String) }.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "updateString",
- args = {int.class, String.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateStringIntString() {
-
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#updateTime(int, java.sql.Time)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateTime",
- args = {int.class, java.sql.Time.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateTimeIntTime() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateTime(java.lang.String, java.sql.Time)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateTime",
- args = {java.lang.String.class, java.sql.Time.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateTimeStringTime() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateTimestamp(int, java.sql.Timestamp)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateTimestamp",
- args = {int.class, java.sql.Timestamp.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateTimestampIntTimestamp() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#updateTimestamp(java.lang.String, java.sql.Timestamp)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateTimestamp",
- args = {java.lang.String.class, java.sql.Timestamp.class}
- )
- @KnownFailure("Not Supported")
- public void testUpdateTimestampStringTimestamp() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/ResultSetTest.java b/luni/src/test/java/tests/sql/ResultSetTest.java
deleted file mode 100644
index c515453..0000000
--- a/luni/src/test/java/tests/sql/ResultSetTest.java
+++ /dev/null
@@ -1,847 +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.sql;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import tests.support.DatabaseCreator;
-
-import java.io.IOException;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-/**
- * @author andrea@google.com (Your Name Here)
- *
- */
-@TestTargetClass(ResultSet.class)
-public class ResultSetTest extends SQLTest {
-
- ResultSet target = null;
- ResultSet emptyTarget = null;
- ResultSet scrollableTarget = null;
- ResultSet writableTarget = null;
- Statement stForward = null;
- Statement stScrollable = null;
- Statement stWritable = null;
- final String selectAllAnimals = "select id, name from zoo";
- final String selectEmptyTable = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
- /* (non-Javadoc)
- * @see junit.framework.TestCase#setUp()
- */
- @Override
- public void setUp() throws Exception {
- super.setUp();
- try {
- conn.setAutoCommit(false);
- stForward = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
- ResultSet.CONCUR_READ_ONLY);
- stForward.execute(selectAllAnimals);
- target = stForward.getResultSet();
- assertNotNull(target);
-
- // empty table
- stForward = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
- ResultSet.CONCUR_READ_ONLY);
- stForward.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
- stForward.execute(selectEmptyTable);
- emptyTarget = stForward.getResultSet();
-
- } catch (SQLException e) {
- fail("SQLException was thrown: " + e.getMessage());
- }
- }
-
- /* (non-Javadoc)
- * @see junit.framework.TestCase#tearDown()
- */
- public void tearDown() {
- super.tearDown();
- try {
- target.close();
- stForward.close();
- } catch (SQLException e) {
- fail("Error in test setup");
- e.printStackTrace();
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#absolute(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "absolute",
- args = {int.class}
- )
- public void testAbsolute() {
- try {
- assertTrue(target.isBeforeFirst());
- assertFalse(target.absolute(0));
- assertTrue(target.absolute(1));
- assertTrue(target.isFirst());
- assertTrue(target.absolute(-1));
- assertTrue(target.isLast());
- target.next();
- assertTrue(target.isAfterLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#afterLast()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "afterLast",
- args = {}
- )
- @KnownFailure("res.close() does not wrap up")
- public void testAfterLast() {
- try {
- target.afterLast();
- assertTrue(target.isAfterLast());
- assertFalse(target.next());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- emptyTarget.afterLast();
- assertFalse(emptyTarget.isAfterLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- target.beforeFirst();
- fail("Should get SQLException");
- } catch (SQLException e) {
-
- }
-
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#beforeFirst()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "beforeFirst",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testBeforeFirst() {
-
- try {
- target.beforeFirst();
- assertTrue(target.isBeforeFirst());
- assertTrue(target.next());
- assertFalse(target.isBeforeFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- emptyTarget.beforeFirst();
- assertFalse(emptyTarget.isBeforeFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- target.beforeFirst();
- fail("Should get SQLException");
- } catch (SQLException e) {
-
- }
-
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#clearWarnings()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Not supported",
- method = "clearWarnings",
- args = {}
- )
- @KnownFailure("Not supported")
- public void testClearWarnings() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#close()}.
- *
- * According to the JDBC spec close has to "Releases this ResultSet
- * object's database and JDBC resources immediately", and this implies
- * the fields should be released as well (so that garbage collection
- * can take place)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test immediate release of resources, test fails",
- method = "close",
- args = {}
- )
- @KnownFailure("Resultset.close() does not wrap up")
- public void testClose1() {
- try {
- target.close();
- target.next();
- fail("Should get SQLException");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#close()}.
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "test that exception in one prepared statement does not affect second statement. (Atomicity Rule)",
- method = "close",
- args = {}
- )
- public void testClose() {
- PreparedStatement ps1 = null;
- PreparedStatement ps2 = null;
- try {
-
- Statement s = conn.createStatement();
- s.addBatch("create table t1 (a text);");
-
- s.addBatch("insert into t1 values('abc');");
- s.addBatch("insert into t1 values('def');");
- s.addBatch("insert into t1 values('ghi');");
- s.executeBatch();
- s.close();
-
- conn.commit();
- ps1 = conn.prepareStatement("select * from t1");
- ps2 = conn
- .prepareStatement("select * from t1 whe a like '?000'");
-
- ResultSet rs1 = ps1.executeQuery();
-
- try {
- ResultSet rs2 = ps2.executeQuery();
- while (rs2.next()){
- // do nothing
- }
- fail("Should get SQLException");
- } catch (SQLException sqle) {
- // ok : Division by zero
- }
-
- // Although exception happened on ps2 rs1 should still work
- // Isolation property if ACID rules
-
- while (rs1.next()) {
- // do nothing: switching of rows should be possible
- }
-
- conn.commit();
-
- rs1.close();
- ps1.close();
- ps2.close();
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- } finally {
- try {
- if (ps1 != null) ps1.close();
- if (ps2 != null) ps2.close();
- conn.rollback();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
-
-
- /**
- * Test method for {@link java.sql.ResultSet#findColumn(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findColumn",
- args = {java.lang.String.class}
- )
- public void testFindColumn() {
- try {
- assertEquals(1, target.findColumn("id"));
- assertEquals(2, target.findColumn("name"));
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- target.findColumn("bla");
- fail("Should get SQLException");
- } catch (SQLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#first()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "first",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testtestFirst() {
- try {
- assertFalse(emptyTarget.first());
- assertTrue(target.first());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- // releases all resources such that it can be finalized!
- target.first();
- fail("Should get SQLException");
- } catch (SQLException e) {
-
- }
-
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#isAfterLast()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "isAfterLast",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testtestIsAfterLast() {
- try {
- assertFalse(target.isAfterLast());
- target.absolute(-1); // last
- target.next();
- assertTrue(target.isAfterLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- assertFalse(emptyTarget.isAfterLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- // releases all resources such that it can be finalized!
- target.isAfterLast();
- fail("Should get SQLException");
- } catch (SQLException e) {
-
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#isBeforeFirst()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "isBeforeFirst",
- args = {}
- )
- @KnownFailure("In Second code block assertion fails. statment. "+
- "close() does not wrap up")
- public void testtestIsBeforeFirst() {
- try {
- assertTrue(target.isBeforeFirst());
- assertTrue(target.next());
- assertFalse(target.isBeforeFirst());
- assertTrue(target.isFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- assertTrue(emptyTarget.isBeforeFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- // releases all resources such that it can be finalized!
- target.isBeforeFirst();
- fail("Should get SQLException");
- } catch (SQLException e) {
- //ok
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#isFirst()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "isFirst",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testtestIsFirst() {
- try {
- assertFalse(target.isFirst());
- target.first();
- assertTrue(target.isFirst());
- target.next();
- assertFalse(target.isFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- assertFalse(emptyTarget.isFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- // releases all resources such that it can be finalized!
- target.isFirst();
- fail("Should get SQLException");
- } catch (SQLException e) {
-
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#isLast()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails. Test for empty result set fails",
- method = "isLast",
- args = {}
- )
- @KnownFailure("Second block first assertion fails. Is Last should evaluate "+
- "true if the row on which the cursor is actually provides a result."+
- "statment.close() does not wrap up")
- public void testtestIsLast() {
-
- try {
- assertFalse(target.isLast());
- target.absolute(-1);
- assertTrue(target.isLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- //check default value no valid row
- try {
- assertFalse(emptyTarget.isLast());
- assertFalse(emptyTarget.next());
- assertFalse(emptyTarget.isLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
-
- try {
- target.close();
- target.isLast();
- fail("Should get SQLException");
- } catch (SQLException e) {
- // ok
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#last()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SQLException test fails",
- method = "last",
- args = {}
- )
- @KnownFailure("statment.close() does not wrap up")
- public void testtestLast() {
- try {
- assertFalse(target.isLast());
- target.last();
- assertTrue(target.isLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- target.close();
- target.last();
- fail("Should get SQLException");
- } catch (SQLException e) {
- // ok
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#next()}.
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SQLException checking test fails. Clearing of warnings"+
- " and closed streams not supported.",
- method = "next",
- args = {}
- )
- @KnownFailure("Resultset.close() does not wrap up")
- public void testNext() throws SQLException {
- try {
- //before first - first
- assertTrue(target.next());
- //first - second
- assertTrue(target.next());
- //after last
- assertFalse(target.next());
- assertTrue(target.isAfterLast());
- // one more
- assertFalse(target.next());
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- assertFalse(emptyTarget.next());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- target.close();
- try {
- target.next();
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
-
- }
-
- public void testPrevious() throws SQLException {
- try {
- target.first();
- target.previous();
- assertTrue(target.isBeforeFirst());
-
- target.last();
- target.next();
- target.previous();
- assertFalse(target.isAfterLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- target.close();
- try {
- target.previous();
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#relative(int)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test fails: no exception is thrown when moving cursor backwards",
- method = "relative",
- args = {int.class}
- )
- @KnownFailure("no exception is thrown when moving cursor backwards"
- +" on forward only statement")
- public void testRelative() {
-
- // forward only
- try {
- int initialRow = target.getRow();
- assertFalse(target.relative(0));
- assertEquals(initialRow, target.getRow());
-
- assertTrue(target.relative(1));
- assertTrue(target.isFirst());
- assertEquals(1, target.getRow());
-
- assertTrue(target.relative(1));
- assertFalse(target.isFirst());
- assertEquals(2, target.getRow());
-
-
- assertFalse(target.relative(2));
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
-
- try {
- // should not be able to scroll backwards in forward only RS
- target.relative(-2);
- assertEquals(2,target.getRow());
- fail("Should get SQLException");
- } catch (SQLException e) {
- // ok
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- assertFalse(emptyTarget.relative(Integer.MAX_VALUE));
- assertTrue(emptyTarget.isAfterLast());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#relative(int)}.
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test fails: does not move before first row on min_value",
- method = "relative",
- args = {int.class}
- )
- @KnownFailure("Scrollable resultSet. Not supported")
- public void testRelativeScrollableResultSet() throws SQLException {
- // scrollable resultSet
- try {
-
- int initialRow = scrollableTarget.getRow();
- assertFalse(scrollableTarget.relative(0));
- assertEquals(initialRow, scrollableTarget.getRow());
-
- assertTrue(scrollableTarget.relative(1));
- assertTrue(scrollableTarget.isFirst());
- assertEquals(1, scrollableTarget.getRow());
-
- assertTrue(scrollableTarget.relative(1));
- assertFalse(scrollableTarget.isFirst());
-
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- assertEquals(2, scrollableTarget.getRow());
- assertFalse(scrollableTarget.relative(2));
- scrollableTarget.relative(-2);
- assertEquals(2,scrollableTarget.getRow());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- assertFalse(scrollableTarget.relative(Integer.MIN_VALUE));
- assertTrue(scrollableTarget.isBeforeFirst());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- stScrollable.close();
- try {
- scrollableTarget.relative(1);
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
-
-
- /**
- * Test method for {@link java.sql.ResultSet#updateObject(java.lang.String, java.lang.Object)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "not supported",
- method = "updateObject",
- args = {java.lang.String.class, java.lang.Object.class}
- )
- @KnownFailure("not supported")
- public void testUpdateObjectStringObject() {
- try {
- writableTarget.next();
- writableTarget.updateObject("family","bird");
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- try {
- target.next();
- target.updateObject("family","bird");
- fail("SQLException was not thrown");
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
-
- /**
- * Test method for {@link java.sql.ResultSet#updateString(java.lang.String, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "not supported. Only exception testing. Missing testing for wrong type",
- method = "updateString",
- args = {java.lang.String.class, java.lang.String.class}
- )
- @KnownFailure("Feature not supported")
- public void testUpdateStringStringString() throws Exception {
- try {
- writableTarget.next();
- writableTarget.updateString("family","bird");
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- // non writable target.
- try {
- target.next();
- target.updateString("family","bird");
- fail("SQLException was not thrown");
- } catch (SQLException e) {
- //ok
- }
-
-
- // writable but wrong type
- try {
- target.updateString(1,"test");
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- }
-
- target.close();
-
- // Exception test
- try {
- target.updateString("family","test");
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-
- /**
- * Test method for {@link java.sql.ResultSet#wasNull()}.
- * Spec sais: if something was read... -> if nothing was read it should be false
- * @throws SQLException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "failing tests.",
- method = "wasNull",
- args = {}
- )
- @KnownFailure("the default tests, and exception tests fail.")
- public void testWasNull() throws SQLException {
-
- // Check default: select statement executed but no get on target called yet
- // Either false or throw an exception.
- try {
- assertFalse(target.wasNull());
- } catch (SQLException e) {
- //ok
- }
-
-
- try {
- stForward.execute("insert into zoo values(8,null,null);");
- stForward.execute(selectAllAnimals);
- target = stForward.getResultSet();
- assertNotNull(target);
- assertTrue(target.last());
- assertNull(target.getObject(2));
- assertTrue(target.wasNull());
- assertNotNull(target.getObject(1));
- assertFalse(target.wasNull());
- } catch (SQLException e) {
- fail("Unexpected exception: " + e.getMessage());
- e.printStackTrace();
- }
-
- target.close();
- try {
- target.wasNull();
- fail("Exception expected");
- } catch (SQLException e) {
- //ok
- }
- }
-}
diff --git a/luni/src/test/java/tests/sql/SQLDataTest.java b/luni/src/test/java/tests/sql/SQLDataTest.java
deleted file mode 100644
index 1aed820..0000000
--- a/luni/src/test/java/tests/sql/SQLDataTest.java
+++ /dev/null
@@ -1,72 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.SQLData;
-import java.sql.SQLInput;
-import java.sql.SQLOutput;
-
-
-@TestTargetClass(SQLData.class)
-public class SQLDataTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.SQLData#getSQLTypeName()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getSQLTypeName",
- args = {}
- )
- public void testGetSQLTypeName() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLData#readSQL(java.sql.SQLInput, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readSQL",
- args = {SQLInput.class, String.class}
- )
- public void testReadSQL() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLData#writeSQL(java.sql.SQLOutput)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeSQL",
- args = {SQLOutput.class}
- )
- public void testWriteSQL() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/SQLInputTest.java b/luni/src/test/java/tests/sql/SQLInputTest.java
deleted file mode 100644
index 818818b..0000000
--- a/luni/src/test/java/tests/sql/SQLInputTest.java
+++ /dev/null
@@ -1,328 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.SQLInput;
-
-@TestTargetClass(SQLInput.class)
-public class SQLInputTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.SQLInput#readString()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readString",
- args = {}
- )
- public void testReadString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readBoolean()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readBoolean",
- args = {}
- )
- public void testReadBoolean() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readByte()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readByte",
- args = {}
- )public void testReadByte() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readShort()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readShort",
- args = {}
- )
- public void testReadShort() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readInt()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readInt",
- args = {}
- )
- public void testReadInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readLong()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readLong",
- args = {}
- )
- public void testReadLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readFloat()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readFloat",
- args = {}
- )
- public void testReadFloat() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readDouble()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readDouble",
- args = {}
- )
- public void testReadDouble() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readBigDecimal()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readBigDecimal",
- args = {}
- )
- public void testReadBigDecimal() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readBytes()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readBytes",
- args = {}
- )
- public void testReadBytes() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readDate()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readDate",
- args = {}
- )
- public void testReadDate() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readTime()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readTime",
- args = {}
- )
- public void testReadTime() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readTimestamp()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readTimestamp",
- args = {}
- )
- public void testReadTimestamp() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readCharacterStream()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readCharacterStream",
- args = {}
- )
- public void testReadCharacterStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readAsciiStream()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readAsciiStream",
- args = {}
- )
- public void testReadAsciiStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readBinaryStream()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readBinaryStream",
- args = {}
- )
- public void testReadBinaryStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readObject()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readObject",
- args = {}
- )
- public void testReadObject() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readRef()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readRef",
- args = {}
- )
- public void testReadRef() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readBlob()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readBlob",
- args = {}
- )
- public void testReadBlob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readClob()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readClob",
- args = {}
- )
- public void testReadClob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readArray()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readArray",
- args = {}
- )
- public void testReadArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#wasNull()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "wasNull",
- args = {}
- )
- public void testWasNull() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLInput#readURL()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "readURL",
- args = {}
- )
- public void testReadURL() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/SQLOutputTest.java b/luni/src/test/java/tests/sql/SQLOutputTest.java
deleted file mode 100644
index 13ef4b1..0000000
--- a/luni/src/test/java/tests/sql/SQLOutputTest.java
+++ /dev/null
@@ -1,347 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.io.InputStream;
-import java.io.Reader;
-import java.math.BigDecimal;
-import java.net.URL;
-import java.sql.Array;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.Date;
-import java.sql.Ref;
-import java.sql.SQLData;
-import java.sql.SQLOutput;
-import java.sql.Struct;
-import java.sql.Time;
-import java.sql.Timestamp;
-
-@TestTargetClass(SQLOutput.class)
-public class SQLOutputTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeString(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeString",
- args = {String.class}
- )
- public void testWriteString() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeBoolean(boolean)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeBoolean",
- args = {boolean.class}
- )
- public void testWriteBoolean() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeByte(byte)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeByte",
- args = {byte.class}
- )
- public void testWriteByte() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeShort(short)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeShort",
- args = {short.class}
- )
- public void testWriteShort() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeInt(int)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeInt",
- args = {int.class}
- )
- public void testWriteInt() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeLong(long)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeLong",
- args = {long.class}
- )
- public void testWriteLong() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeFloat(float)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeFloat",
- args = {float.class}
- )
- public void testWriteFloat() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeDouble(double)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeDouble",
- args = {double.class}
- )
- public void testWriteDouble() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for
- * {@link java.sql.SQLOutput#writeBigDecimal(java.math.BigDecimal)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeBigDecimal",
- args = {BigDecimal.class}
- )
- public void testWriteBigDecimal() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeBytes(byte[])}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeBytes",
- args = {byte[].class}
- )
- public void testWriteBytes() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeDate(java.sql.Date)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeDate",
- args = {Date.class}
- )
- public void testWriteDate() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeTime(java.sql.Time)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeTime",
- args = {Time.class}
- )
- public void testWriteTime() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for
- * {@link java.sql.SQLOutput#writeTimestamp(java.sql.Timestamp)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeTimestamp",
- args = {Timestamp.class}
- )
- public void testWriteTimestamp() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for
- * {@link java.sql.SQLOutput#writeCharacterStream(java.io.Reader)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeCharacterStream",
- args = {Reader.class}
- )
- public void testWriteCharacterStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for
- * {@link java.sql.SQLOutput#writeAsciiStream(java.io.InputStream)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeAsciiStream",
- args = {InputStream.class}
- )
- public void testWriteAsciiStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for
- * {@link java.sql.SQLOutput#writeBinaryStream(java.io.InputStream)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeBinaryStream",
- args = {InputStream.class}
- )
- public void testWriteBinaryStream() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeObject(java.sql.SQLData)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeObject",
- args = {SQLData.class}
- )
- public void testWriteObject() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeRef(java.sql.Ref)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeRef",
- args = {Ref.class}
- )
- public void testWriteRef() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeBlob(java.sql.Blob)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeBlob",
- args = {Blob.class}
- )
- public void testWriteBlob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeClob(java.sql.Clob)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeClob",
- args = {Clob.class}
- )
- public void testWriteClob() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeStruct(java.sql.Struct)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeStruct",
- args = {Struct.class}
- )
- public void testWriteStruct() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeArray(java.sql.Array)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeArray",
- args = {Array.class}
- )
- public void testWriteArray() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.SQLOutput#writeURL(java.net.URL)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "writeURL",
- args = {URL.class}
- )
- public void testWriteURL() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/SavepointTest.java b/luni/src/test/java/tests/sql/SavepointTest.java
deleted file mode 100644
index dedf032..0000000
--- a/luni/src/test/java/tests/sql/SavepointTest.java
+++ /dev/null
@@ -1,59 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.Savepoint;
-
-/**
- *
- */
-@TestTargetClass(Savepoint.class)
-public class SavepointTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.Savepoint#getSavepointId()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getSavepointId",
- args = {}
- )
- public void testGetSavepointId() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Savepoint#getSavepointName()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getSavepointName",
- args = {}
- )
- public void testGetSavepointName() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/luni/src/test/java/tests/sql/StructTest.java b/luni/src/test/java/tests/sql/StructTest.java
deleted file mode 100644
index e4c0fd4..0000000
--- a/luni/src/test/java/tests/sql/StructTest.java
+++ /dev/null
@@ -1,72 +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 tests.sql;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.sql.Struct;
-import java.util.Map;
-
-@TestTargetClass(Struct.class)
-public class StructTest extends TestCase {
-
- /**
- * Test method for {@link java.sql.Struct#getSQLTypeName()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getSQLTypeName",
- args = {}
-
- )
- public void testGetSQLTypeName() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Struct#getAttributes()}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
-
- method = "getAttributes",
- args = {}
- )
- public void testGetAttributes() {
- fail("Not yet implemented");
- }
-
- /**
- * Test method for {@link java.sql.Struct#getAttributes(java.util.Map)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getAttributes",
- args = {Map.class}
- )
- public void testGetAttributesMapOfStringClassOfQ() {
- fail("Not yet implemented");
- }
-
-}
diff --git a/sqlite-jdbc/Android.mk b/sqlite-jdbc/Android.mk
index 8cc23ce..1e25524 100644
--- a/sqlite-jdbc/Android.mk
+++ b/sqlite-jdbc/Android.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
sqlite_jdbc_src_files := \
src/main/native/sqlite_jni.c
diff --git a/support/src/test/java/libcore/java/security/TestKeyStore.java b/support/src/test/java/libcore/java/security/TestKeyStore.java
index 94daaf5..8a6a64d 100644
--- a/support/src/test/java/libcore/java/security/TestKeyStore.java
+++ b/support/src/test/java/libcore/java/security/TestKeyStore.java
@@ -16,8 +16,13 @@
package libcore.java.security;
+import com.android.org.bouncycastle.asn1.DEROctetString;
import com.android.org.bouncycastle.asn1.x509.BasicConstraints;
+import com.android.org.bouncycastle.asn1.x509.GeneralName;
+import com.android.org.bouncycastle.asn1.x509.GeneralNames;
+import com.android.org.bouncycastle.asn1.x509.GeneralSubtree;
import com.android.org.bouncycastle.asn1.x509.KeyUsage;
+import com.android.org.bouncycastle.asn1.x509.NameConstraints;
import com.android.org.bouncycastle.asn1.x509.X509Extensions;
import com.android.org.bouncycastle.asn1.x509.X509Name;
import com.android.org.bouncycastle.jce.X509Principal;
@@ -27,14 +32,16 @@
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.InetAddress;
-import java.security.Key;
+import java.net.UnknownHostException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
+import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore.TrustedCertificateEntry;
-import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PublicKey;
@@ -46,9 +53,12 @@
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
+import java.util.List;
+import java.util.Vector;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
@@ -66,6 +76,14 @@
*/
public final class TestKeyStore extends Assert {
+ private static TestKeyStore ROOT_CA;
+
+ private static TestKeyStore SERVER;
+ private static TestKeyStore CLIENT;
+ private static TestKeyStore CLIENT_CERTIFICATE;
+
+ private static TestKeyStore CLIENT_2;
+
static {
if (StandardNames.IS_RI) {
// Needed to create BKS keystore but add at end so most
@@ -74,6 +92,7 @@
Security.getProviders().length+1);
}
}
+
private static final boolean TEST_MANAGERS = true;
public final KeyStore keyStore;
@@ -84,9 +103,8 @@
public final TestKeyManager keyManager;
public final TestTrustManager trustManager;
- private TestKeyStore(KeyStore keyStore,
- char[] storePassword,
- char[] keyPassword) {
+ private TestKeyStore(KeyStore keyStore, char[] storePassword, char[] keyPassword)
+ throws Exception {
this.keyStore = keyStore;
this.storePassword = storePassword;
this.keyPassword = keyPassword;
@@ -96,90 +114,70 @@
this.trustManager = (TestTrustManager)trustManagers[0];
}
- public static KeyManager[] createKeyManagers(final KeyStore keyStore,
- final char[] storePassword) {
+ public static KeyManager[] createKeyManagers(KeyStore keyStore, char[] storePassword)
+ throws Exception {
+ String kmfa = KeyManagerFactory.getDefaultAlgorithm();
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfa);
+ kmf.init(keyStore, storePassword);
+ return TestKeyManager.wrap(kmf.getKeyManagers());
+ }
+
+ public static TrustManager[] createTrustManagers(final KeyStore keyStore) throws Exception {
+ String tmfa = TrustManagerFactory.getDefaultAlgorithm();
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfa);
+ tmf.init(keyStore);
+ return TestTrustManager.wrap(tmf.getTrustManagers());
+ }
+
+ /**
+ * Lazily create shared test certificates.
+ */
+ private static synchronized void initCerts() {
+ if (ROOT_CA != null) {
+ return;
+ }
try {
- String kmfa = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfa);
- kmf.init(keyStore, storePassword);
- return TestKeyManager.wrap(kmf.getKeyManagers());
+ ROOT_CA = new Builder()
+ .aliasPrefix("RootCA")
+ .subject("Test Root Certificate Authority")
+ .ca(true)
+ .build();
+ TestKeyStore intermediateCa = new Builder()
+ .aliasPrefix("IntermediateCA")
+ .subject("Test Intermediate Certificate Authority")
+ .ca(true)
+ .signer(ROOT_CA.getPrivateKey("RSA", "RSA"))
+ .rootCa(ROOT_CA.getRootCertificate("RSA"))
+ .build();
+ SERVER = new Builder()
+ .aliasPrefix("server")
+ .signer(intermediateCa.getPrivateKey("RSA", "RSA"))
+ .rootCa(intermediateCa.getRootCertificate("RSA"))
+ .build();
+ CLIENT = new TestKeyStore(createClient(intermediateCa.keyStore), null, null);
+ CLIENT_CERTIFICATE = new Builder()
+ .aliasPrefix("client")
+ .subject("test@user")
+ .signer(intermediateCa.getPrivateKey("RSA", "RSA"))
+ .rootCa(intermediateCa.getRootCertificate("RSA"))
+ .build();
+ TestKeyStore rootCa2 = new Builder()
+ .aliasPrefix("RootCA2")
+ .subject("Test Root Certificate Authority 2")
+ .ca(true)
+ .build();
+ CLIENT_2 = new TestKeyStore(createClient(rootCa2.keyStore), null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
- public static TrustManager[] createTrustManagers(final KeyStore keyStore) {
- try {
- String tmfa = TrustManagerFactory.getDefaultAlgorithm();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfa);
- tmf.init(keyStore);
- return TestTrustManager.wrap(tmf.getTrustManagers());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private static final TestKeyStore ROOT_CA
- = create(new String[] { "RSA" },
- null,
- null,
- "RootCA",
- x509Principal("Test Root Certificate Authority"),
- 0,
- true,
- null,
- null);
- private static final TestKeyStore INTERMEDIATE_CA
- = create(new String[] { "RSA" },
- null,
- null,
- "IntermediateCA",
- x509Principal("Test Intermediate Certificate Authority"),
- 0,
- true,
- ROOT_CA.getPrivateKey("RSA", "RSA"),
- ROOT_CA.getRootCertificate("RSA"));
- private static final TestKeyStore SERVER
- = create(new String[] { "RSA" },
- null,
- null,
- "server",
- localhost(),
- 0,
- false,
- INTERMEDIATE_CA.getPrivateKey("RSA", "RSA"),
- INTERMEDIATE_CA.getRootCertificate("RSA"));
- private static final TestKeyStore CLIENT
- = new TestKeyStore(createClient(INTERMEDIATE_CA.keyStore), null, null);
- private static final TestKeyStore CLIENT_CERTIFICATE
- = create(new String[] { "RSA" },
- null,
- null,
- "client",
- x509Principal("test@user"),
- 0,
- false,
- INTERMEDIATE_CA.getPrivateKey("RSA", "RSA"),
- INTERMEDIATE_CA.getRootCertificate("RSA"));
-
- private static final TestKeyStore ROOT_CA_2
- = create(new String[] { "RSA" },
- null,
- null,
- "RootCA2",
- x509Principal("Test Root Certificate Authority 2"),
- 0,
- true,
- null,
- null);
- private static final TestKeyStore CLIENT_2
- = new TestKeyStore(createClient(ROOT_CA_2.keyStore), null, null);
-
/**
* Return a server keystore with a matched RSA certificate and
* private key as well as a CA certificate.
*/
public static TestKeyStore getServer() {
+ initCerts();
return SERVER;
}
@@ -187,6 +185,7 @@
* Return a keystore with a CA certificate
*/
public static TestKeyStore getClient() {
+ initCerts();
return CLIENT;
}
@@ -195,6 +194,7 @@
* private key as well as a CA certificate.
*/
public static TestKeyStore getClientCertificate() {
+ initCerts();
return CLIENT_CERTIFICATE;
}
@@ -204,32 +204,111 @@
* testing.
*/
public static TestKeyStore getClientCA2() {
+ initCerts();
return CLIENT_2;
}
/**
- * Create a new KeyStore containing the requested key types.
- * Since key generation can be expensive, most tests should reuse
- * the RSA-only singleton instance returned by TestKeyStore.get
- *
- * @param keyAlgorithms The requested key types to generate and include
- * @param keyStorePassword Password used to protect the private key
- * @param aliasPrefix A unique prefix to identify the key aliases
- * @param keyUsage {@link KeyUsage} bit mask for 2.5.29.15 extension
- * @param ca true If the keys being created are for a CA
- * @param signer If non-null, a private key entry to be used for signing, otherwise self-sign
- * @param signer If non-null, a root CA to include in the final store
+ * Creates KeyStores containing the requested key types. Since key
+ * generation can be expensive, most tests should reuse the RSA-only
+ * singleton instance returned by TestKeyStore.get.
*/
- public static TestKeyStore create(String[] keyAlgorithms,
- char[] storePassword,
- char[] keyPassword,
- String aliasPrefix,
- X509Principal subject,
- int keyUsage,
- boolean ca,
- PrivateKeyEntry signer,
- Certificate rootCa) {
- try {
+ public static class Builder {
+ private String[] keyAlgorithms = { "RSA" };
+ private char[] storePassword;
+ private char[] keyPassword;
+ private String aliasPrefix;
+ private X509Principal subject;
+ private int keyUsage;
+ private boolean ca;
+ private PrivateKeyEntry signer;
+ private Certificate rootCa;
+ private final List<GeneralName> subjectAltNames = new ArrayList<GeneralName>();
+ private final Vector<GeneralSubtree> permittedNameConstraints
+ = new Vector<GeneralSubtree>();
+ private final Vector<GeneralSubtree> excludedNameConstraints = new Vector<GeneralSubtree>();
+
+ public Builder() throws Exception {
+ subject = localhost();
+ }
+
+ /**
+ * Sets the requested key types to generate and include. The default is
+ * RSA only.
+ */
+ public Builder keyAlgorithms(String... keyAlgorithms) {
+ this.keyAlgorithms = keyAlgorithms;
+ return this;
+ }
+
+ /** A unique prefix to identify the key aliases */
+ public Builder aliasPrefix(String aliasPrefix) {
+ this.aliasPrefix = aliasPrefix;
+ return this;
+ }
+
+ /**
+ * Sets the subject common name. The default is the local host's
+ * canonical name.
+ */
+ public Builder subject(X509Principal subject) {
+ this.subject = subject;
+ return this;
+ }
+
+ public Builder subject(String commonName) {
+ return subject(x509Principal(commonName));
+ }
+
+ /** {@link KeyUsage} bit mask for 2.5.29.15 extension */
+ public Builder keyUsage(int keyUsage) {
+ this.keyUsage = keyUsage;
+ return this;
+ }
+
+ /** true If the keys being created are for a CA */
+ public Builder ca(boolean ca) {
+ this.ca = ca;
+ return this;
+ }
+
+ /** a private key entry to be used for signing, otherwise self-sign */
+ public Builder signer(PrivateKeyEntry signer) {
+ this.signer = signer;
+ return this;
+ }
+
+ /** a root CA to include in the final store */
+ public Builder rootCa(Certificate rootCa) {
+ this.rootCa = rootCa;
+ return this;
+ }
+
+ private Builder addSubjectAltName(GeneralName generalName) {
+ subjectAltNames.add(generalName);
+ return this;
+ }
+
+ public Builder addSubjectAltNameIpAddress(byte[] ipAddress) {
+ return addSubjectAltName(
+ new GeneralName(GeneralName.iPAddress, new DEROctetString(ipAddress)));
+ }
+
+ private Builder addNameConstraint(boolean permitted, GeneralName generalName) {
+ if (permitted) {
+ permittedNameConstraints.add(new GeneralSubtree(generalName));
+ } else {
+ excludedNameConstraints.add(new GeneralSubtree(generalName));
+ }
+ return this;
+ }
+
+ public Builder addNameConstraint(boolean permitted, byte[] ipAddress) {
+ return addNameConstraint(permitted,
+ new GeneralName(GeneralName.iPAddress, new DEROctetString(ipAddress)));
+ }
+
+ public TestKeyStore build() throws Exception {
if (StandardNames.IS_RI) {
// JKS does not allow null password
if (storePassword == null) {
@@ -239,28 +318,17 @@
keyPassword = "password".toCharArray();
}
}
+
KeyStore keyStore = createKeyStore();
- boolean ecRsa = false;
for (String keyAlgorithm : keyAlgorithms) {
String publicAlias = aliasPrefix + "-public-" + keyAlgorithm;
String privateAlias = aliasPrefix + "-private-" + keyAlgorithm;
if (keyAlgorithm.equals("EC_RSA") && signer == null && rootCa == null) {
- createKeys(keyStore, keyPassword,
- keyAlgorithm,
- publicAlias, privateAlias,
- subject,
- keyUsage,
- ca,
- privateKey(keyStore, keyPassword, "RSA", "RSA"));
+ createKeys(keyStore, keyAlgorithm, publicAlias, privateAlias,
+ privateKey(keyStore, keyPassword, "RSA", "RSA"));
continue;
}
- createKeys(keyStore, keyPassword,
- keyAlgorithm,
- publicAlias, privateAlias,
- subject,
- keyUsage,
- ca,
- signer);
+ createKeys(keyStore, keyAlgorithm, publicAlias, privateAlias, signer);
}
if (rootCa != null) {
keyStore.setCertificateEntry(aliasPrefix
@@ -269,10 +337,180 @@
rootCa);
}
return new TestKeyStore(keyStore, storePassword, keyPassword);
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
+ }
+
+ /**
+ * Add newly generated keys of a given key type to an existing
+ * KeyStore. The PrivateKey will be stored under the specified
+ * private alias name. The X509Certificate will be stored on the
+ * public alias name and have the given subject distinguished
+ * name.
+ *
+ * If a CA is provided, it will be used to sign the generated
+ * certificate. Otherwise, the certificate will be self
+ * signed. The certificate will be valid for one day before and
+ * one day after the time of creation.
+ *
+ * Based on:
+ * org.bouncycastle.jce.provider.test.SigTest
+ * org.bouncycastle.jce.provider.test.CertTest
+ */
+ private KeyStore createKeys(KeyStore keyStore,
+ String keyAlgorithm,
+ String publicAlias,
+ String privateAlias,
+ PrivateKeyEntry signer) throws Exception {
+ PrivateKey caKey;
+ X509Certificate caCert;
+ X509Certificate[] caCertChain;
+ if (signer == null) {
+ caKey = null;
+ caCert = null;
+ caCertChain = null;
+ } else {
+ caKey = signer.getPrivateKey();
+ caCert = (X509Certificate)signer.getCertificate();
+ caCertChain = (X509Certificate[])signer.getCertificateChain();
+ }
+
+ PrivateKey privateKey;
+ X509Certificate x509c;
+ if (publicAlias == null && privateAlias == null) {
+ // don't want anything apparently
+ privateKey = null;
+ x509c = null;
+ } else {
+ // 1.) we make the keys
+ int keySize;
+ String signatureAlgorithm;
+ if (keyAlgorithm.equals("RSA")) {
+ keySize = StandardNames.IS_RI ? 1024 : 512; // 512 breaks SSL_RSA_EXPORT_* on RI
+ signatureAlgorithm = "sha1WithRSA";
+ } else if (keyAlgorithm.equals("DSA")) {
+ keySize = 512;
+ signatureAlgorithm = "sha1WithDSA";
+ } else if (keyAlgorithm.equals("EC")) {
+ keySize = 256;
+ signatureAlgorithm = "sha1WithECDSA";
+ } else if (keyAlgorithm.equals("EC_RSA")) {
+ keySize = 256;
+ keyAlgorithm = "EC";
+ signatureAlgorithm = "sha1WithRSA";
+ } else {
+ throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
+ }
+
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm);
+ kpg.initialize(keySize, new SecureRandom());
+
+ KeyPair kp = kpg.generateKeyPair();
+ privateKey = kp.getPrivate();
+ PublicKey publicKey = kp.getPublic();
+ // 2.) use keys to make certificate
+
+ // note that there doesn't seem to be a standard way to make a
+ // certificate using java.* or javax.*. The CertificateFactory
+ // interface assumes you want to read in a stream of bytes a
+ // factory specific format. So here we use Bouncy Castle's
+ // X509V3CertificateGenerator and related classes.
+ X509Principal issuer;
+ if (caCert == null) {
+ issuer = subject;
+ } else {
+ Principal xp = caCert.getSubjectDN();
+ issuer = new X509Principal(new X509Name(xp.getName()));
+ }
+
+ long millisPerDay = 24 * 60 * 60 * 1000;
+ long now = System.currentTimeMillis();
+ Date start = new Date(now - millisPerDay);
+ Date end = new Date(now + millisPerDay);
+ BigInteger serial = BigInteger.valueOf(1);
+
+ X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
+ x509cg.setSubjectDN(subject);
+ x509cg.setIssuerDN(issuer);
+ x509cg.setNotBefore(start);
+ x509cg.setNotAfter(end);
+ x509cg.setPublicKey(publicKey);
+ x509cg.setSignatureAlgorithm(signatureAlgorithm);
+ x509cg.setSerialNumber(serial);
+ if (keyUsage != 0) {
+ x509cg.addExtension(X509Extensions.KeyUsage,
+ true,
+ new KeyUsage(keyUsage));
+ }
+ if (ca) {
+ x509cg.addExtension(X509Extensions.BasicConstraints,
+ true,
+ new BasicConstraints(true));
+ }
+ for (GeneralName subjectAltName : subjectAltNames) {
+ x509cg.addExtension(X509Extensions.SubjectAlternativeName, false,
+ new GeneralNames(subjectAltName).getEncoded());
+ }
+ if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
+ x509cg.addExtension(X509Extensions.NameConstraints, true,
+ new NameConstraints(permittedNameConstraints, excludedNameConstraints));
+ }
+
+ PrivateKey signingKey = (caKey == null) ? privateKey : caKey;
+ if (signingKey instanceof ECPrivateKey) {
+ /*
+ * bouncycastle needs its own ECPrivateKey implementation
+ */
+ KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
+ PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(signingKey.getEncoded());
+ signingKey = kf.generatePrivate(ks);
+ }
+ x509c = x509cg.generateX509Certificate(signingKey);
+ if (StandardNames.IS_RI) {
+ /*
+ * The RI can't handle the BC EC signature algorithm
+ * string of "ECDSA", since it expects "...WITHEC...",
+ * so convert from BC to RI X509Certificate
+ * implementation via bytes.
+ */
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
+ Certificate c = cf.generateCertificate(bais);
+ x509c = (X509Certificate) c;
+ }
+ }
+
+ X509Certificate[] x509cc;
+ if (privateAlias == null) {
+ // don't need certificate chain
+ x509cc = null;
+ } else if (caCertChain == null) {
+ x509cc = new X509Certificate[] { x509c };
+ } else {
+ x509cc = new X509Certificate[caCertChain.length+1];
+ x509cc[0] = x509c;
+ System.arraycopy(caCertChain, 0, x509cc, 1, caCertChain.length);
+ }
+
+ // 3.) put certificate and private key into the key store
+ if (privateAlias != null) {
+ keyStore.setKeyEntry(privateAlias, privateKey, keyPassword, x509cc);
+ }
+ if (publicAlias != null) {
+ keyStore.setCertificateEntry(publicAlias, x509c);
+ }
+ return keyStore;
+ }
+
+ private X509Principal localhost() throws UnknownHostException {
+ return x509Principal(InetAddress.getLocalHost().getCanonicalHostName());
+ }
+
+ /**
+ * Create an X509Principal with the given attributes
+ */
+ public static X509Principal x509Principal(String commonName) {
+ Hashtable attributes = new Hashtable();
+ attributes.put(X509Principal.CN, commonName);
+ return new X509Principal(attributes);
}
}
@@ -320,187 +558,12 @@
}
/**
- * Add newly generated keys of a given key type to an existing
- * KeyStore. The PrivateKey will be stored under the specified
- * private alias name. The X509Certificate will be stored on the
- * public alias name and have the given subject distiguished
- * name.
- *
- * If a CA is provided, it will be used to sign the generated
- * certificate. Otherwise, the certificate will be self
- * signed. The certificate will be valid for one day before and
- * one day after the time of creation.
- *
- * Based on:
- * org.bouncycastle.jce.provider.test.SigTest
- * org.bouncycastle.jce.provider.test.CertTest
- */
- public static KeyStore createKeys(KeyStore keyStore,
- char[] keyPassword,
- String keyAlgorithm,
- String publicAlias,
- String privateAlias,
- X509Principal subject,
- int keyUsage,
- boolean ca,
- PrivateKeyEntry signer) throws Exception {
- PrivateKey caKey;
- X509Certificate caCert;
- X509Certificate[] caCertChain;
- if (signer == null) {
- caKey = null;
- caCert = null;
- caCertChain = null;
- } else {
- caKey = signer.getPrivateKey();
- caCert = (X509Certificate)signer.getCertificate();
- caCertChain = (X509Certificate[])signer.getCertificateChain();
- }
-
- PrivateKey privateKey;
- X509Certificate x509c;
- if (publicAlias == null && privateAlias == null) {
- // don't want anything apparently
- privateKey = null;
- x509c = null;
- } else {
- // 1.) we make the keys
- int keySize;
- String signatureAlgorithm;
- if (keyAlgorithm.equals("RSA")) {
- keySize = StandardNames.IS_RI ? 1024 : 512; // 512 breaks SSL_RSA_EXPORT_* on RI
- signatureAlgorithm = "sha1WithRSA";
- } else if (keyAlgorithm.equals("DSA")) {
- keySize = 512;
- signatureAlgorithm = "sha1WithDSA";
- } else if (keyAlgorithm.equals("EC")) {
- keySize = 256;
- signatureAlgorithm = "sha1WithECDSA";
- } else if (keyAlgorithm.equals("EC_RSA")) {
- keySize = 256;
- keyAlgorithm = "EC";
- signatureAlgorithm = "sha1WithRSA";
- } else {
- throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
- }
-
- KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm);
- kpg.initialize(keySize, new SecureRandom());
-
- KeyPair kp = kpg.generateKeyPair();
- privateKey = (PrivateKey)kp.getPrivate();
- PublicKey publicKey = (PublicKey)kp.getPublic();
- // 2.) use keys to make certficate
-
- // note that there doesn't seem to be a standard way to make a
- // certificate using java.* or javax.*. The CertificateFactory
- // interface assumes you want to read in a stream of bytes a
- // factory specific format. So here we use Bouncy Castle's
- // X509V3CertificateGenerator and related classes.
- X509Principal issuer;
- if (caCert == null) {
- issuer = subject;
- } else {
- Principal xp = caCert.getSubjectDN();
- issuer = new X509Principal(new X509Name(xp.getName()));
- }
-
- long millisPerDay = 24 * 60 * 60 * 1000;
- long now = System.currentTimeMillis();
- Date start = new Date(now - millisPerDay);
- Date end = new Date(now + millisPerDay);
- BigInteger serial = BigInteger.valueOf(1);
-
- X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
- x509cg.setSubjectDN(subject);
- x509cg.setIssuerDN(issuer);
- x509cg.setNotBefore(start);
- x509cg.setNotAfter(end);
- x509cg.setPublicKey(publicKey);
- x509cg.setSignatureAlgorithm(signatureAlgorithm);
- x509cg.setSerialNumber(serial);
- if (keyUsage != 0) {
- x509cg.addExtension(X509Extensions.KeyUsage,
- true,
- new KeyUsage(keyUsage));
- }
- if (ca) {
- x509cg.addExtension(X509Extensions.BasicConstraints,
- true,
- new BasicConstraints(true));
- }
- PrivateKey signingKey = (caKey == null) ? privateKey : caKey;
- if (signingKey instanceof ECPrivateKey) {
- /*
- * bouncycastle needs its own ECPrivateKey implementation
- */
- KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
- PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(signingKey.getEncoded());
- signingKey = (PrivateKey) kf.generatePrivate(ks);
- }
- x509c = x509cg.generateX509Certificate(signingKey);
- if (StandardNames.IS_RI) {
- /*
- * The RI can't handle the BC EC signature algorithm
- * string of "ECDSA", since it expects "...WITHEC...",
- * so convert from BC to RI X509Certificate
- * implementation via bytes.
- */
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
- Certificate c = cf.generateCertificate(bais);
- x509c = (X509Certificate) c;
- }
- }
-
- X509Certificate[] x509cc;
- if (privateAlias == null) {
- // don't need certificate chain
- x509cc = null;
- } else if (caCertChain == null) {
- x509cc = new X509Certificate[] { x509c };
- } else {
- x509cc = new X509Certificate[caCertChain.length+1];
- x509cc[0] = x509c;
- System.arraycopy(caCertChain, 0, x509cc, 1, caCertChain.length);
- }
-
- // 3.) put certificate and private key into the key store
- if (privateAlias != null) {
- keyStore.setKeyEntry(privateAlias, privateKey, keyPassword, x509cc);
- }
- if (publicAlias != null) {
- keyStore.setCertificateEntry(publicAlias, x509c);
- }
- return keyStore;
- }
-
- /**
- * Create an X509Principal with the given attributes
- */
- public static X509Principal localhost() {
- try {
- return x509Principal(InetAddress.getLocalHost().getCanonicalHostName());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Create an X509Principal with the given attributes
- */
- public static X509Principal x509Principal(String commonName) {
- Hashtable attributes = new Hashtable();
- attributes.put(X509Principal.CN, commonName);
- return new X509Principal(attributes);
- }
-
- /**
* Return the only private key in a TestKeyStore for the given
* algorithms. Throws IllegalStateException if there are are more
* or less than one.
*/
- public PrivateKeyEntry getPrivateKey(String keyAlgorithm, String signatureAlgorithm) {
+ public PrivateKeyEntry getPrivateKey(String keyAlgorithm, String signatureAlgorithm)
+ throws Exception {
return privateKey(keyStore, keyPassword, keyAlgorithm, signatureAlgorithm);
}
@@ -509,43 +572,37 @@
* algorithms. Throws IllegalStateException if there are are more
* or less than one.
*/
- public static PrivateKeyEntry privateKey(KeyStore keyStore,
- char[] keyPassword,
- String keyAlgorithm,
- String signatureAlgorithm) {
- try {
- PrivateKeyEntry found = null;
- PasswordProtection password = new PasswordProtection(keyPassword);
- for (String alias: Collections.list(keyStore.aliases())) {
- if (!keyStore.entryInstanceOf(alias, PrivateKeyEntry.class)) {
- continue;
- }
- PrivateKeyEntry privateKey = (PrivateKeyEntry) keyStore.getEntry(alias, password);
- if (!privateKey.getPrivateKey().getAlgorithm().equals(keyAlgorithm)) {
- continue;
- }
- X509Certificate certificate = (X509Certificate) privateKey.getCertificate();
- if (!certificate.getSigAlgName().contains(signatureAlgorithm)) {
- continue;
- }
- if (found != null) {
- throw new IllegalStateException("keyStore has more than one private key for "
- + " keyAlgorithm: " + keyAlgorithm
- + " signatureAlgorithm: " + signatureAlgorithm
- + "\nfirst: " + found.getPrivateKey()
- + "\nsecond: " + privateKey.getPrivateKey() );
- }
- found = privateKey;
+ public static PrivateKeyEntry privateKey(KeyStore keyStore, char[] keyPassword,
+ String keyAlgorithm, String signatureAlgorithm) throws Exception {
+ PrivateKeyEntry found = null;
+ PasswordProtection password = new PasswordProtection(keyPassword);
+ for (String alias: Collections.list(keyStore.aliases())) {
+ if (!keyStore.entryInstanceOf(alias, PrivateKeyEntry.class)) {
+ continue;
}
- if (found == null) {
- throw new IllegalStateException("keyStore contained no private key for "
+ PrivateKeyEntry privateKey = (PrivateKeyEntry) keyStore.getEntry(alias, password);
+ if (!privateKey.getPrivateKey().getAlgorithm().equals(keyAlgorithm)) {
+ continue;
+ }
+ X509Certificate certificate = (X509Certificate) privateKey.getCertificate();
+ if (!certificate.getSigAlgName().contains(signatureAlgorithm)) {
+ continue;
+ }
+ if (found != null) {
+ throw new IllegalStateException("keyStore has more than one private key for "
+ " keyAlgorithm: " + keyAlgorithm
- + " signatureAlgorithm: " + signatureAlgorithm);
+ + " signatureAlgorithm: " + signatureAlgorithm
+ + "\nfirst: " + found.getPrivateKey()
+ + "\nsecond: " + privateKey.getPrivateKey() );
}
- return found;
- } catch (Exception e) {
- throw new RuntimeException(e);
+ found = privateKey;
}
+ if (found == null) {
+ throw new IllegalStateException("keyStore contained no private key for "
+ + " keyAlgorithm: " + keyAlgorithm
+ + " signatureAlgorithm: " + signatureAlgorithm);
+ }
+ return found;
}
/**
@@ -553,7 +610,7 @@
* for the given algorithm. Throws IllegalStateException if there
* are are more or less than one.
*/
- public Certificate getRootCertificate(String algorithm) {
+ public Certificate getRootCertificate(String algorithm) throws Exception {
return rootCertificate(keyStore, algorithm);
}
@@ -562,61 +619,51 @@
* the given algorithm. Throws IllegalStateException if there are
* are more or less than one.
*/
- public static Certificate rootCertificate(KeyStore keyStore,
- String algorithm) {
- try {
- Certificate found = null;
- for (String alias: Collections.list(keyStore.aliases())) {
- if (!keyStore.entryInstanceOf(alias, TrustedCertificateEntry.class)) {
- continue;
- }
- TrustedCertificateEntry certificateEntry =
- (TrustedCertificateEntry) keyStore.getEntry(alias, null);
- Certificate certificate = certificateEntry.getTrustedCertificate();
- if (!certificate.getPublicKey().getAlgorithm().equals(algorithm)) {
- continue;
- }
- if (!(certificate instanceof X509Certificate)) {
- continue;
- }
- X509Certificate x = (X509Certificate) certificate;
- if (!x.getIssuerDN().equals(x.getSubjectDN())) {
- continue;
- }
- if (found != null) {
- throw new IllegalStateException("keyStore has more than one root CA for "
- + algorithm
- + "\nfirst: " + found
- + "\nsecond: " + certificate );
- }
- found = certificate;
+ public static Certificate rootCertificate(KeyStore keyStore, String algorithm)
+ throws Exception {
+ Certificate found = null;
+ for (String alias: Collections.list(keyStore.aliases())) {
+ if (!keyStore.entryInstanceOf(alias, TrustedCertificateEntry.class)) {
+ continue;
}
- if (found == null) {
- throw new IllegalStateException("keyStore contained no root CA for " + algorithm);
+ TrustedCertificateEntry certificateEntry =
+ (TrustedCertificateEntry) keyStore.getEntry(alias, null);
+ Certificate certificate = certificateEntry.getTrustedCertificate();
+ if (!certificate.getPublicKey().getAlgorithm().equals(algorithm)) {
+ continue;
}
- return found;
- } catch (Exception e) {
- throw new RuntimeException(e);
+ if (!(certificate instanceof X509Certificate)) {
+ continue;
+ }
+ X509Certificate x = (X509Certificate) certificate;
+ if (!x.getIssuerDN().equals(x.getSubjectDN())) {
+ continue;
+ }
+ if (found != null) {
+ throw new IllegalStateException("keyStore has more than one root CA for "
+ + algorithm
+ + "\nfirst: " + found
+ + "\nsecond: " + certificate );
+ }
+ found = certificate;
}
+ if (found == null) {
+ throw new IllegalStateException("keyStore contained no root CA for " + algorithm);
+ }
+ return found;
}
/**
* Create a client key store that only contains self-signed certificates but no private keys
*/
- public static KeyStore createClient(KeyStore caKeyStore) {
- try {
- KeyStore clientKeyStore = createKeyStore();
- copySelfSignedCertificates(clientKeyStore, caKeyStore);
- return clientKeyStore;
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
+ public static KeyStore createClient(KeyStore caKeyStore) throws Exception {
+ KeyStore clientKeyStore = createKeyStore();
+ copySelfSignedCertificates(clientKeyStore, caKeyStore);
+ return clientKeyStore;
}
/**
- * Copy self-signed certifcates from one key store to another.
+ * Copy self-signed certificates from one key store to another.
* Returns true if successful, false if no match found.
*/
public static boolean copySelfSignedCertificates(KeyStore dst, KeyStore src) throws Exception {
@@ -636,7 +683,7 @@
}
/**
- * Copy named certifcates from one key store to another.
+ * Copy named certificates 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)
@@ -658,64 +705,57 @@
/**
* Dump a key store for debugging.
*/
- public static void dump(String context,
- KeyStore keyStore,
- char[] keyPassword) {
- try {
- PrintStream out = System.out;
- out.println("context=" + context);
- out.println("\tkeyStore=" + keyStore);
- out.println("\tkeyStore.type=" + keyStore.getType());
- out.println("\tkeyStore.provider=" + keyStore.getProvider());
- out.println("\tkeyPassword="
- + ((keyPassword == null) ? null : new String(keyPassword)));
- out.println("\tsize=" + keyStore.size());
- for (String alias: Collections.list(keyStore.aliases())) {
- out.println("alias=" + alias);
- out.println("\tcreationDate=" + keyStore.getCreationDate(alias));
- if (keyStore.isCertificateEntry(alias)) {
- out.println("\tcertificate:");
- out.println("==========================================");
- out.println(keyStore.getCertificate(alias));
- out.println("==========================================");
- continue;
- }
- if (keyStore.isKeyEntry(alias)) {
- out.println("\tkey:");
- out.println("==========================================");
- String key;
- try {
- key = ("Key retreived using password\n"
- + keyStore.getKey(alias, keyPassword));
- } catch (UnrecoverableKeyException e1) {
- try {
- key = ("Key retreived without password\n"
- + keyStore.getKey(alias, null));
- } catch (UnrecoverableKeyException e2) {
- key = "Key could not be retreived";
- }
- }
- out.println(key);
- out.println("==========================================");
- Certificate[] chain = keyStore.getCertificateChain(alias);
- if (chain == null) {
- out.println("No certificate chain associated with key");
- out.println("==========================================");
- } else {
- for (int i = 0; i < chain.length; i++) {
- out.println("Certificate chain element #" + i);
- out.println(chain[i]);
- out.println("==========================================");
- }
- }
- continue;
- }
- out.println("\tunknown entry type");
+ public static void dump(String context, KeyStore keyStore, char[] keyPassword)
+ throws KeyStoreException, NoSuchAlgorithmException {
+ PrintStream out = System.out;
+ out.println("context=" + context);
+ out.println("\tkeyStore=" + keyStore);
+ out.println("\tkeyStore.type=" + keyStore.getType());
+ out.println("\tkeyStore.provider=" + keyStore.getProvider());
+ out.println("\tkeyPassword="
+ + ((keyPassword == null) ? null : new String(keyPassword)));
+ out.println("\tsize=" + keyStore.size());
+ for (String alias: Collections.list(keyStore.aliases())) {
+ out.println("alias=" + alias);
+ out.println("\tcreationDate=" + keyStore.getCreationDate(alias));
+ if (keyStore.isCertificateEntry(alias)) {
+ out.println("\tcertificate:");
+ out.println("==========================================");
+ out.println(keyStore.getCertificate(alias));
+ out.println("==========================================");
+ continue;
}
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
+ if (keyStore.isKeyEntry(alias)) {
+ out.println("\tkey:");
+ out.println("==========================================");
+ String key;
+ try {
+ key = ("Key retrieved using password\n"
+ + keyStore.getKey(alias, keyPassword));
+ } catch (UnrecoverableKeyException e1) {
+ try {
+ key = ("Key retrieved without password\n"
+ + keyStore.getKey(alias, null));
+ } catch (UnrecoverableKeyException e2) {
+ key = "Key could not be retrieved";
+ }
+ }
+ out.println(key);
+ out.println("==========================================");
+ Certificate[] chain = keyStore.getCertificateChain(alias);
+ if (chain == null) {
+ out.println("No certificate chain associated with key");
+ out.println("==========================================");
+ } else {
+ for (int i = 0; i < chain.length; i++) {
+ out.println("Certificate chain element #" + i);
+ out.println(chain[i]);
+ out.println("==========================================");
+ }
+ }
+ continue;
+ }
+ out.println("\tunknown entry type");
}
}
diff --git a/luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java b/support/src/test/java/libcore/javax/net/ssl/FakeSSLSession.java
similarity index 95%
rename from luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java
rename to support/src/test/java/libcore/javax/net/ssl/FakeSSLSession.java
index 4a793dd..4d876e7 100644
--- a/luni/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java
+++ b/support/src/test/java/libcore/javax/net/ssl/FakeSSLSession.java
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-package org.apache.harmony.xnet.provider.jsse;
+package libcore.javax.net.ssl;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import java.security.cert.Certificate;
import java.security.Principal;
-class FakeSession implements SSLSession {
+public class FakeSSLSession implements SSLSession {
final String host;
- FakeSession(String host) {
+ public FakeSSLSession(String host) {
this.host = host;
}
diff --git a/xml/src/main/java/org/kxml2/io/KXmlSerializer.java b/xml/src/main/java/org/kxml2/io/KXmlSerializer.java
index d676c41..d1965d6 100644
--- a/xml/src/main/java/org/kxml2/io/KXmlSerializer.java
+++ b/xml/src/main/java/org/kxml2/io/KXmlSerializer.java
@@ -22,6 +22,7 @@
package org.kxml2.io;
import java.io.*;
+import java.util.Locale;
import org.xmlpull.v1.*;
public class KXmlSerializer implements XmlSerializer {
@@ -332,21 +333,19 @@
? new OutputStreamWriter(os)
: new OutputStreamWriter(os, encoding));
this.encoding = encoding;
- if (encoding != null
- && encoding.toLowerCase().startsWith("utf"))
+ if (encoding != null && encoding.toLowerCase(Locale.US).startsWith("utf")) {
unicode = true;
+ }
}
- public void startDocument(
- String encoding,
- Boolean standalone)
- throws IOException {
+ public void startDocument(String encoding, Boolean standalone) throws IOException {
writer.write("<?xml version='1.0' ");
if (encoding != null) {
this.encoding = encoding;
- if (encoding.toLowerCase().startsWith("utf"))
+ if (encoding.toLowerCase(Locale.US).startsWith("utf")) {
unicode = true;
+ }
}
if (this.encoding != null) {